Lambda & Serverless
Run code without managing servers, triggered by events and billed per invocation.
Lambda runs your code in response to events without you provisioning servers. You upload a function, pick memory/timeout, and AWS handles scaling — running as many concurrent copies as needed. You pay per request and duration, nothing when idle.
Functions are triggered by events: an S3 upload, an API Gateway request, a schedule, a queue message, a DynamoDB change. Common patterns: serverless APIs, event processing, glue/automation. Watch out for cold starts (first invocation latency), execution time limits (15 min max), and statelessness.
# A Lambda handler triggered by an event
def handler(event, context):
name = event.get("name", "world")
return {"statusCode": 200, "body": f"Hello, {name}!"}Event-driven patterns:
S3 upload → Lambda resizes the image
API Gateway → Lambda serves a REST endpoint
EventBridge cron → Lambda runs a nightly cleanup
SQS message → Lambda processes the job - Give three event sources that can trigger a Lambda function.
- Explain when Lambda is a better fit than an EC2 instance, and when it isn’t.
- Describe what a cold start is and one way to reduce it.
- Why must Lambda functions be stateless?
Cheat Sheet▾
| Aspect | Detail |
|---|---|
| Billing | Per request + duration |
| Scaling | Automatic, concurrent |
| Triggers | S3, API GW, EventBridge, SQS, … |
| Max runtime | 15 minutes |
| Cold start | First-invoke latency |
| State | Stateless (use S3/DynamoDB) |
Common Interview Questions▾
When would you choose Lambda over EC2?
For short, event-driven, bursty workloads where you don’t want to manage servers and want to pay only per execution. EC2 fits long-running, stateful, or highly-customized workloads needing full OS control.
What is a cold start?
The extra latency on the first invocation (or after scaling) while AWS initializes a new execution environment. Provisioned concurrency or lighter runtimes reduce it.