Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 70 ยท Serverless and messaging

Lambda Functions

Learn how AWS Lambda works: the handler model, event and context, runtimes, packaging, layers, execution roles and invocation types, with a runnable handler runner.

AWS Lambda runs your code without you managing servers. You upload a function, tell AWS what should trigger it, and AWS finds a machine, runs the code, and bills you only for the time it actually ran. There is no instance to patch and nothing running (or costing money) while nobody calls your function.

This lesson covers the basic model: what a handler is, what arrives as event and context, how code is packaged, why every function needs an execution role, and the three ways a function can be invoked. The next lesson, Lambda Concurrency, Cold Starts and Limits, is about how Lambda scales.

Lambda itself cannot run on this site, and there is no AWS account here. Console steps, CLI commands and deployment code are read-only. The runnable examples are small Python stand-ins that call your function the way Lambda does: with an event dictionary and a context object, then turning errors into a result. They leave out sandboxing, networking and real timing.

The handler model

A Lambda function is a normal function with a fixed signature. You give Lambda the name of that function, called the handler, and Lambda calls it once per event:

Python
def lambda_handler(event, context):
    name = event.get("name", "world")
    return {"message": f"Hello, {name}!"}
  • event carries the input as JSON, converted to a Python dictionary. Its shape depends on the caller: an S3 upload gives a list of records, API Gateway gives an HTTP request, a test in the console gives whatever JSON you typed.
  • context is an object with facts about this invocation: the function name, the memory setting, a unique request ID, and how much time is left before the timeout.
  • The return value is serialized to JSON and sent back to the caller (for synchronous calls). If the function raises an exception, the invocation fails and Lambda reports the error type and message.

In the settings you write the handler as file.function, for example app.lambda_handler for the function lambda_handler in app.py. Other runtimes have their own handler formats, but the idea is the same.

Anything outside the handler (imports, creating clients, loading configuration) runs once per execution environment and is reused by later invocations. That is why SDK clients are created at the top of the file, not inside the handler.

A handler runner you can try

This stand-in builds a context with the same attribute names as the real one and calls the handler. It turns exceptions into an error document similar to what Lambda returns, and it fakes a clock so the remaining-time method is predictable.

Python Calling a handler with event and context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first call succeeds. The second raises ValueError, which the runner reports as errorType and errorMessage. The third has no amount key, so it fails with a KeyError. Both failures carry the same request ID that appeared in the log line: in real Lambda, that ID is what you search for in CloudWatch Logs. Anything your function prints (or logs) goes to a CloudWatch log group named after the function.

Runtimes

A runtime is the language environment Lambda starts for you: managed runtimes exist for Python, Node.js, Java, .NET and Ruby, and you can bring any other language with a custom runtime (the provided family) or by deploying a container image. AWS retires old runtime versions on a published schedule, so pick a current version when you create a function. Languages that compile to a native binary (Go, Rust) use the provided runtimes with a binary named bootstrap.

You also choose the CPU architecture: x86_64 or arm64 (Graviton). Arm functions usually cost about 20% less per millisecond and are often as fast or faster, as long as your dependencies have arm builds.

Packaging and layers

Lambda needs your code and its dependencies in one of two forms:

  • A zip archive: up to 50 MB zipped when you upload it directly, and 250 MB unzipped in total (including layers). Larger zips go through S3.
  • A container image up to 10 GB, stored in ECR. Use this for large dependencies or when your team already builds containers.

A layer is a zip of shared code or libraries that you attach to several functions (up to five layers per function). Layers keep your function package small and let you update a common library in one place, but they count toward the unzipped size limit and bring versioning to manage.

Terminal
# Package and deploy a Python function (read-only: needs an AWS account)
zip function.zip app.py

aws lambda create-function \
  --function-name hello \
  --runtime python3.13 \
  --handler app.lambda_handler \
  --zip-file fileb://function.zip \
  --role arn:aws:iam::123456789012:role/hello-execution-role

aws lambda invoke --function-name hello \
  --payload '{"name":"Ada"}' --cli-binary-format raw-in-base64-out out.json

The execution role

Every function runs with an execution role: an IAM role that Lambda assumes for you. Whatever the role allows is exactly what your code may do with the AWS SDK. That is the one place where permissions for the function live; you do not put access keys into the code.

The role needs a trust policy that lets the Lambda service assume it, and permission policies for the things the function touches. At the very least it needs permission to write logs:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:*:123456789012:*"
    },
    {
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:PutItem"],
      "Resource": "arn:aws:dynamodb:eu-west-1:123456789012:table/orders"
    }
  ]
}

Give each function its own role with only the permissions it needs, as you learned in Writing IAM Policies. The execution role is about what the function can call. A different thing, the function's resource-based policy, is about who may invoke the function (for example, allowing S3 or API Gateway to call it).

Three ways to invoke a function

flowchart LR
    C1["Caller<br/>(console, API Gateway, SDK)"] -->|"Synchronous<br/>RequestResponse"| L1["Lambda"]
    L1 -->|"result or error"| C1
    C2["Event source<br/>(S3, SNS, EventBridge)"] -->|"Asynchronous<br/>Event"| Q["Internal queue"]
    Q --> L2["Lambda"]
    P["Poller<br/>(SQS, Kinesis, DynamoDB streams)"] -->|"batches"| L3["Lambda"]

Synchronous calls wait for the answer; asynchronous calls are queued and retried; pollers read batches from a stream or queue.

  1. Synchronous (RequestResponse). The caller waits and receives the result or the error. API Gateway and the CLI use this. Retries are the caller's job.
  2. Asynchronous (Event). Lambda accepts the event, answers 202 Accepted immediately and runs the function later. If it fails, Lambda retries twice by default, with waits in between, and then discards the event or sends it to a dead-letter queue or an on-failure destination. S3 and SNS invoke functions this way.
  3. Event source mappings. For queues and streams (SQS, Kinesis, DynamoDB streams), Lambda itself polls the source and invokes your function with a batch of records. Whether failures are retried depends on the source.

Because async and polled invocations can run more than once, your handler should be idempotent: processing the same event twice must be safe.

Python Synchronous and asynchronous invocation with retries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The synchronous caller sees the error immediately and must decide what to do. Event b fails every time, so after one try plus two retries it lands in the dead-letter queue, while c succeeds on its third attempt, which shows why idempotent handlers matter: it was invoked three times for one event.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the two arguments of a Lambda handler contain?

    The event is the JSON input from the caller; the context object describes the running invocation.
  2. 2. Where should you create an SDK client so that later invocations reuse it?

    Code outside the handler runs when the environment starts and is reused by later invocations.
  3. 3. What is the purpose of a Lambda execution role?

    Lambda assumes the execution role for the function, so its permissions are what your code can do. Who may invoke the function is decided by a resource-based policy.
  4. 4. By default, what happens when an asynchronously invoked function keeps failing?

    Async invocations get two retries by default. After that the event is discarded or sent to a configured DLQ or destination.
  5. 5. Why should handlers for async or queue-driven invocations be idempotent?

    Retries and at-least-once delivery mean duplicates happen, so repeating an event must not corrupt data.

Summary

  • A Lambda function is a handler called with event (input JSON) and context (invocation facts); the return value or exception becomes the result.
  • Code outside the handler runs once per execution environment, so create clients there.
  • Choose a runtime and architecture, package as a zip (50 MB direct, 250 MB unzipped) or a container image (up to 10 GB), and share libraries with layers.
  • The execution role defines what the function may do; a resource-based policy defines who may invoke it.
  • Invocation is synchronous, asynchronous (two retries, then DLQ or destination) or through event source mappings that poll batches. Make handlers idempotent.

Next: Lambda Concurrency, Cold Starts and Limits