Triggers, Handlers & Cold Starts

How a Lambda function wakes up, what your code receives, and why the first run is slower.

1 min read

Lambda functions don't run all the time. They sleep until an event wakes them.

1. The trigger (event source)

Common triggers:

  • An HTTP request via API Gateway or a Lambda Function URL
  • A file uploaded to S3
  • A message arriving in an SQS queue
  • A schedule ("every day at 9 a.m.") from EventBridge
  • A change in a DynamoDB table (DynamoDB Streams)

2. The handler

Your code must contain a handler, the function Lambda calls. In Python:

Python
def lambda_handler(event, context):
    # event:   a dict describing what happened (the HTTP request, the S3 upload, ...)
    # context: runtime info, e.g. context.get_remaining_time_in_millis()
    return {"message": "hello"}

The shape of event depends on the trigger. An S3 event looks different from an HTTP request.

3. Cold starts vs. warm starts

The first time your function runs (or when Lambda adds capacity), AWS must create a fresh environment, download your code, and run your imports. That extra delay, typically a few hundred milliseconds, is a cold start. Afterwards the environment stays around for a while, so later calls are warm and fast.

Tip

Put expensive setup, like creating boto3 clients or loading config, outside the handler. It runs once per cold start and gets reused by every warm call.

How it flows
  1. 1Event happens

    Upload, HTTP call, schedule…

  2. 2Environment ready

    Cold: created. Warm: reused.

  3. 3Handler runs

    lambda_handler(event, context)

  4. 4Result returned

    Logs go to CloudWatch

Key takeaways

  • Functions run only when a trigger (event source) fires.
  • Your handler receives `event` (what happened) and `context` (runtime info).
  • Cold starts add latency on the first run, so put setup code outside the handler.

Check your understanding

Pick an answer to see the explanation.

  1. 1. Where should you create a boto3 client to make warm invocations fastest?

  2. 2. What is a cold start?