Lambda & Serverless

Difficulty: Intermediate

Question

What is AWS Lambda, how does it run your code, and what are its key limits?

Answer

AWS Lambda is a serverless compute service that runs your function in response to events (an HTTP request through API Gateway, a file landing in S3, a message on SQS, a schedule) and bills only for the time your code runs, rounded to the millisecond. You do not manage servers or scaling. The key limits are a 15-minute maximum timeout, 128 MB to 10,240 MB of memory, and a default of 1,000 concurrent executions per Region per account.

How a Lambda invocation works

  1. An event source triggers the function, either synchronously (API Gateway waits for a response), asynchronously (S3 or EventBridge hand the event to Lambda's internal queue), or via polling (Lambda reads batches from SQS, Kinesis, or DynamoDB Streams).
  2. Lambda looks for a warm execution environment (a Firecracker microVM with your runtime already loaded). If none is free, it creates one: this is the cold start.
  3. During a cold start Lambda downloads your code, starts the runtime, and runs your initialisation code outside the handler.
  4. The handler runs. When it finishes, the environment is frozen and kept around for reuse for a while.

Each environment handles one request at a time. Ten simultaneous requests need ten environments, which is what "concurrency" means.

Limits worth remembering

LimitValue
TimeoutUp to 900 seconds (15 minutes)
Memory128 MB to 10,240 MB; CPU scales with memory (up to 6 vCPUs)
Ephemeral /tmp storage512 MB default, up to 10,240 MB
Deployment package50 MB zipped (direct upload), 250 MB unzipped including layers; container images up to 10 GB
Synchronous payload6 MB request and 6 MB response
Concurrency1,000 per Region by default (a soft quota you can raise)
Environment variables4 KB total

Cold starts and how to reduce them

Cold starts add latency, typically from under a hundred milliseconds for small Node.js or Python functions to a second or more for heavy Java or .NET apps. Ways to reduce them:

  • Keep the package small and initialise SDK clients outside the handler so warm calls reuse them.
  • Provisioned Concurrency keeps a set number of environments initialised (you pay for them while they are idle).
  • SnapStart snapshots an initialised environment and restores it, available for Java, Python, and .NET.
  • Pick more memory: it also gives more CPU, which often makes init faster and can even lower cost.

When Lambda is a good fit, and when it is not

Good fits: APIs with uneven traffic, event processing (thumbnail generation on S3 upload, processing UPI payment webhooks), scheduled jobs, glue between AWS services.

Poor fits: jobs longer than 15 minutes (use Fargate, Step Functions, or Batch), workloads needing persistent connections or local state, steady high throughput where an always-on container is cheaper, and anything needing a GPU.

Gotchas

  • Lambda inside a VPC needs a NAT gateway or VPC endpoints to reach the internet or AWS APIs.
  • Many Lambdas hitting a relational database can exhaust its connections; use RDS Proxy.
  • Async invocations and SQS retry on failure, so handlers must be idempotent.
Lifecycle of a Lambda invocation. A cold start adds the init steps; warm invocations jump straight to the handler.
  1. Event arrives: API Gateway, S3, SQS, EventBridge, or a direct invoke.
  2. Find or create an environment: Reuse a warm microVM or start a new one (cold start).
  3. Init phase: Download code, start runtime, run code outside the handler.
  4. Invoke phase: Run the handler with the event, billed per millisecond.
  5. Freeze and reuse: Environment stays warm for later requests, then is reclaimed.

Code examples

Python handler that reuses clients across warm invocations

import json
import boto3

# Runs once per execution environment (cold start), reused when warm
s3 = boto3.client("s3")

def handler(event, context):
    # Triggered by an S3 ObjectCreated event
    for record in event["Records"]:
        bucket = record["s3"]["bucket"]["name"]
        key = record["s3"]["object"]["key"]
        head = s3.head_object(Bucket=bucket, Key=key)
        print(f"{key}: {head['ContentLength']} bytes")
    print("Time left (ms):", context.get_remaining_time_in_millis())
    return {"statusCode": 200, "body": json.dumps({"ok": True})}

Creating the boto3 client at module level means only the cold start pays for it. context.get_remaining_time_in_millis() helps long tasks stop cleanly before the timeout.

Tuning memory, timeout, and provisioned concurrency

aws lambda update-function-configuration \
  --function-name thumbnailer \
  --memory-size 1024 --timeout 60

# Provisioned concurrency must target a version or alias
aws lambda put-provisioned-concurrency-config \
  --function-name checkout-api --qualifier live \
  --provisioned-concurrent-executions 20

Raising memory also raises CPU. Provisioned concurrency keeps 20 environments warm on the 'live' alias for latency-sensitive endpoints.

Key points

  • Max timeout 15 minutes; memory 128 MB to 10,240 MB with CPU proportional to memory
  • Default 1,000 concurrent executions per Region, raisable via Service Quotas
  • Cold start = new environment plus init code; reduce with small packages, Provisioned Concurrency, or SnapStart
  • One environment serves one request at a time
  • Retries mean handlers must be idempotent

Common follow-up questions

  • What causes a cold start, and how would you measure it?
  • How does Lambda scale when 5,000 requests arrive at once?
  • What is the difference between synchronous and asynchronous invocation in terms of retries?
  • When would you choose Fargate over Lambda?

Interview tips

  • Quote the important limits accurately (15 minutes, 10,240 MB, 6 MB sync payload, 1,000 default concurrency); interviewers often probe one of them
  • Explain cold starts mechanically (new environment, init code) instead of just naming them
  • Close with where Lambda is the wrong tool; it shows judgement, not just feature recall

Concepts covered

AWS Lambda, Cold Start, Concurrency, Provisioned Concurrency, Execution Limits

More AWS & Cloud Fundamentals questions