Serverless
Lambda — Serverless Functions
Run code without managing servers using AWS Lambda — the foundation of serverless architecture.
AWS Lambda
Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume — no charge when code isn't running.
Key Features
- Event-driven: Triggered by HTTP requests, S3 events, database changes, schedules, and more
- Auto-scaling: Handles from 1 to thousands of concurrent executions
- Multiple runtimes: Node.js, Python, Java, Go, Ruby, .NET, custom
- Timeout: Up to 15 minutes per execution
- Memory: 128MB to 10GB
Cold Start
First invocation after inactivity takes longer (cold start) as Lambda needs to initialize. Can be mitigated with provisioned concurrency.
Lambda + API Gateway
Combine Lambda with API Gateway to build REST APIs without servers.
Example
javascript
// Lambda function handler (Node.js)
export const handler = async (event, context) => {
console.log('Event:', JSON.stringify(event, null, 2));
// HTTP event from API Gateway
if (event.httpMethod) {
const { httpMethod, path, body, queryStringParameters } = event;
try {
if (httpMethod === 'GET' && path === '/users') {
const users = await getUsersFromDB();
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(users),
};
}
if (httpMethod === 'POST' && path === '/users') {
const data = JSON.parse(body);
const user = await createUser(data);
return {
statusCode: 201,
body: JSON.stringify(user),
};
}
return { statusCode: 404, body: 'Not Found' };
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message }),
};
}
}
// S3 event trigger
if (event.Records?.[0]?.s3) {
const bucket = event.Records[0].s3.bucket.name;
const key = event.Records[0].s3.object.key;
console.log('Processing S3 file:', key, 'from bucket:', bucket);
// Process the uploaded file...
return { processed: true };
}
};
// Deploy via AWS CLI
// aws lambda create-function // --function-name my-function // --runtime nodejs20.x // --handler index.handler // --zip-file fileb://function.zip // --role arn:aws:iam::123456789012:role/lambda-roleTry it yourself — JAVASCRIPT