Lesson 1 of 12 AWS Lambda

Understanding Lambda Functions, Handlers and Runtimes

This lesson introduces the Lambda programming model: what a function is, how the handler receives the event and context objects, which runtimes and package types are available, where logs go and how cost is calculated. The later lessons in this module build on these ideas.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain what a Lambda function consists of and which responsibilities AWS and the developer each hold.
  • Identify the handler setting for Python, Node.js and Java functions and the errors caused by a mismatch.
  • Describe the information carried by the event object and the context object.
  • Distinguish managed runtimes, OS-only runtimes and container images, and .zip and container image packages.
  • Explain how a synchronous invocation reports a function error.
  • Calculate the cost of a function from its requests, memory and duration.

What a Lambda function is

AWS Lambda is a serverless, event-driven compute service. A developer supplies a function, which consists of code, its dependencies and a configuration that sets the runtime, the handler, the memory size, the timeout and the execution role. Lambda does nothing until something invokes the function. It then runs the code for that event, scales the number of running copies with the number of events, and stops charging when the events stop.

Serverless does not mean that there are no servers; it means that the developer does not manage them. The shared responsibility model for Lambda divides the work as follows. AWS operates the hardware, the operating system, the network, scaling and availability across multiple Availability Zones, and for managed runtimes it also patches the language runtime. The developer is responsible for the function code and its libraries, the function configuration, the permissions in the execution role and the protection of the data the function handles.

The following table contrasts Lambda with the two other compute options that DVA-C03 questions most often offer as alternatives.

CharacteristicAWS LambdaAmazon ECS on AWS FargateAmazon EC2
Unit you deployA functionA container image run as a taskA virtual server
What starts the codeAn event or a requestA service or a scheduled taskThe instance is always running
Maximum run time15 minutes per invocationNo limitNo limit
ScalingAutomatic, per eventService Auto Scaling of tasksEC2 Auto Scaling of instances
You pay forRequests and compute time usedvCPU and memory while tasks runInstance time, whether busy or idle
You manageCode and configurationImage, task definition and scalingOperating system, runtime and scaling

Lambda suits short, event-driven work with variable traffic. Long-running processes, workloads that need more than 15 minutes per unit of work, and software that must listen on a port for long periods are better placed on Fargate or EC2.

The handler

The handler is the method in the code that Lambda calls for each invocation. The function's Handler setting tells the runtime where to find it, and its format depends on the language. For Python it is the file name without its extension followed by the function name, so app.handler means the handler function in app.py. For Node.js it is the file and the exported function, such as index.handler. For Java it is the fully qualified class and method, such as com.example.OrderHandler::handleRequest. If the setting does not match the code, every invocation fails with Runtime.HandlerNotFound or Runtime.ImportModuleError.

A Python handler receives two arguments, the event and the context, and returns a result:

# app.py  (Handler setting: app.handler)
import json

def handler(event, context):
    name = event.get("name", "world")
    return {"message": f"Hello, {name}", "requestId": context.aws_request_id}

The equivalent Node.js handler is an exported async function:

// index.mjs  (Handler setting: index.handler)
export const handler = async (event, context) => {
  const name = event.name ?? "world";
  return { message: `Hello, ${name}`, requestId: context.awsRequestId };
};

The value the handler returns, or the exception it raises, decides the outcome of the invocation. The following list explains what happens in each case.

  • Return a value. Lambda serialises it to JSON. A synchronous caller receives it as the response, and for an asynchronous invocation it is passed to an on-success destination if one is configured.
  • Raise an exception. Lambda reports a function error with an errorType, an errorMessage and a stack trace. A synchronous caller receives the error, and an asynchronous invocation is retried, as the next lesson explains.
  • Exceed the timeout. Lambda stops the invocation and reports Task timed out, which is handled in the same way as an error.

From Node.js 24 onwards, Lambda no longer supports callback-style handlers of the form (event, context, callback), so Node.js functions should use async handlers. A Node.js 24 function also no longer waits for promises that are still unresolved when the handler returns, so all work must be awaited before returning. Code outside the handler runs once when an execution environment starts; Configuring Memory, Timeouts and Quotas for Performance and Cost explains this lifecycle and why clients belong there.

Complete the sentence

Match the Handler setting to the code

Exam skills 1.2.2 · 4.1.1

Learn how the Handler setting points at the code, and which error each kind of mismatch causes.

Log in to try this activity Interactive activities are free with an account.

The event object

The event is a JSON document that describes what triggered the invocation. Lambda passes it to the handler unchanged, so its structure is defined by the service that sent it. A function must therefore be written for the event shape of its trigger, and a function that serves two triggers must recognise both. The following table shows where the useful data sits in the events that the exam uses most often.

Event sourceShape of the eventWhere the data is
Direct SDK or CLI callWhatever JSON the caller sendsTop-level fields chosen by the caller
API Gateway (proxy integration)One HTTP requestbody as a string, plus headers, pathParameters and queryStringParameters
Amazon S3A Records listRecords[].s3.bucket.name and Records[].s3.object.key
Amazon SQSA Records list (a batch)Records[].body as a string, plus messageId
Amazon EventBridgeOne eventsource, detail-type and the detail object

Two details in this table cause frequent bugs. First, string fields such as an API Gateway body or an SQS message body contain JSON as text, so the code must parse them before reading their fields. Second, list-based events can contain more than one record, so the handler must loop over Records rather than read only the first item. The Lambda console provides sample events for each service, and the sam local generate-event command creates them for local tests.

Scenario questions

Read the data from each event

Exam skills 1.1.7 · 3.2.3

Practise reading the event shapes that exam questions use most often.

Log in to try this activity Interactive activities are free with an account.

The context object

The context object describes the invocation and the function rather than the event. The runtime creates it, and its property names follow each language's conventions; the following table uses the Python names.

Property or methodWhat it provides
aws_request_idThe unique ID of this invocation, also shown in the function's log lines
function_name, function_versionThe function's name and the version that is running
invoked_function_arnThe ARN used to invoke the function, which shows the alias or version the caller named
memory_limit_in_mbThe memory configured for the function
log_group_name, log_stream_nameWhere this invocation's logs are written
get_remaining_time_in_millis()The milliseconds left before the function times out

The request ID is useful for correlating a caller's report with a log entry. The remaining time lets a function that processes a list of items stop cleanly and save its progress before the timeout ends the invocation, instead of being stopped in the middle of an item.

Runtimes and architectures

A runtime provides the language environment that loads the code and calls the handler. Lambda offers three ways of supplying one, and they differ mainly in who keeps the language runtime patched.

Managed runtimes

A managed runtime is a language environment that AWS builds and maintains, such as python3.13, nodejs24.x, java21, dotnet8 or ruby3.4. The developer uploads only the code and its libraries, and AWS applies security patches to the runtime and the operating system. This is the usual choice for interpreted languages and for Java and .NET.

Managed runtimes have a deprecation date, usually linked to the end of community support for that language version. After that date AWS no longer patches the runtime. Lambda then blocks the creation of new functions on it and later blocks updates to existing functions, although existing functions continue to run. Upgrading means changing the Runtime setting and testing the code on the new version. The runtime management setting controls minor patches: Auto, the default, applies them automatically, Function update applies them on the next deployment, and Manual pins a runtime version for rollback.

OS-only runtimes

An OS-only runtime, provided.al2023, supplies only the Amazon Linux 2023 operating system. The developer provides an executable called bootstrap, which uses the Lambda Runtime API to fetch each event and post the result. Compiled languages use this model: the former go1.x managed runtime has been deprecated, so Go code is now compiled into a bootstrap binary and deployed on provided.al2023, and Rust works in the same way. A custom runtime for any other language is also built on it. AWS patches the operating system, but the developer must recompile the code to update the language libraries inside the binary.

Container images

A container image packages the runtime together with the code. AWS provides base images for each managed runtime, and any other base image can be used if it includes the runtime interface client, which implements the Runtime API. Because the runtime is inside the image, AWS cannot patch it: the developer must rebuild and redeploy the image to pick up security updates. The following table summarises the three options.

OptionExamplesWho maintains the language runtime
Managed runtimepython3.13, nodejs24.x, java21AWS, which applies patches automatically
OS-only runtimeprovided.al2023 with a bootstrap binaryThe developer, who recompiles the code; AWS patches the operating system
Container imageAn AWS base image or another image with the runtime interface clientThe developer, who rebuilds the image

Architectures

Each function also has an instruction set architecture: x86_64, the default, or arm64, which runs on AWS Graviton processors at a lower price per gigabyte-second. Interpreted code usually runs on either, but compiled binaries and native libraries must be built for the chosen architecture.

Deployment packages

Function code reaches Lambda in one of two package types. The package type is chosen when the function is created and cannot be changed afterwards, so moving from one to the other means creating a new function.

.zip file archives

A .zip archive contains the code and its dependencies, and Lambda supplies the runtime named in the function's Runtime setting. The archive can be uploaded directly, up to 50 MB zipped, or from Amazon S3, and the unzipped code, including any layers, can be up to 250 MB. The Handler setting names the method to call, and for interpreted languages the console's code editor can edit the code in place. A .zip archive is the simpler choice for most functions, and it is the only package type that can use layers.

Container images

A container image is built with a Dockerfile, pushed to an Amazon ECR repository and referenced by the function. Images can be up to 10 GB, which suits large dependencies such as machine learning libraries, and they fit teams that already build, scan and promote images in a container pipeline. Layers are not supported, so all dependencies are built into the image, and the handler is set by the image's CMD, which the function configuration can override. The console cannot edit the code of an image-based function. The following table summarises the differences.

Characteristic.zip file archiveContainer image
RuntimeSupplied by LambdaIncluded in the image
Stored inUploaded directly or from Amazon S3An Amazon ECR repository
Maximum size50 MB zipped for direct upload, 250 MB unzipped including layers10 GB
LayersSupportedNot supported
Handler set byThe Handler settingThe image's CMD

Packaging and publishing are covered in Sharing Code and Dependencies with Layers and in the AWS SAM module.

Environment variables

A function can also read environment variables, which hold configuration such as a table name so that the same code runs unchanged in each environment. Lambda also sets reserved variables, such as AWS_REGION and AWS_LAMBDA_FUNCTION_NAME, in every execution environment.

Creating, invoking and testing a function

The following AWS CLI commands create a Python function from a .zip archive and invoke it synchronously. The execution role, held in ROLE_ARN, must trust lambda.amazonaws.com; Granting Permissions with Execution Roles and Resource-Based Policies explains it in detail.

zip function.zip app.py
aws lambda create-function --function-name hello \
    --runtime python3.13 --handler app.handler --architectures arm64 \
    --role "$ROLE_ARN" --zip-file fileb://function.zip

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

A successful synchronous call returns a StatusCode of 200, and the handler's result is written to response.json. The status code needs careful reading. If the handler raises an exception, the call still returns 200, because Lambda itself ran the function successfully. The failure is shown by a FunctionError field with the value Unhandled, and the error details are written to the response file. Callers using the SDK must check this field rather than the status code. Other status codes come from Lambda itself: 202 for an asynchronous call made with --invocation-type Event, and 4xx or 5xx errors such as 429 for throttling.

Adding --log-type Tail returns the last 4 KB of the invocation's log in the response, encoded in Base64. In the console, the Test tab runs the function with a saved test event, and shareable test events can be stored with the function for the whole team. For local testing before deployment, sam local invoke runs the function in a container that emulates Lambda.

Sort into groups

What does the caller receive?

Exam skills 1.1.5 · 1.2.3

Learn what a caller sees when a function succeeds or fails, synchronously and asynchronously.

Log in to try this activity Interactive activities are free with an account.

Logging

Anything a function writes to standard output or standard error, including print statements and logging libraries, is sent to Amazon CloudWatch Logs. By default the log group is /aws/lambda/ followed by the function name, with a log stream for each execution environment, and a different log group can be configured. The execution role needs permission to write logs, which the AWSLambdaBasicExecutionRole managed policy grants. Without it, the function still runs, but no logs appear.

Lambda adds three platform lines to every invocation's logs, described in the following list. The REPORT line is the quickest source of performance data for a single invocation.

  • START marks the beginning of an invocation and shows its request ID and version.
  • END marks the end of the invocation.
  • REPORT shows the duration, the billed duration, the memory size, the maximum memory used and, after a cold start, the Init Duration.

The log format can be plain text or JSON. With the JSON format, Lambda writes structured records that CloudWatch Logs Insights can query by field, and the application and system log levels can be set so that, for example, DEBUG messages are dropped in production without a code change. Monitoring and tracing are covered in the Amazon CloudWatch and AWS X-Ray modules.

How Lambda is priced

Lambda charges for two things: the number of requests and the duration of each invocation, metered in 1 ms increments and multiplied by the configured memory. The combined unit is the gigabyte-second (GB-second): one second of run time with 1 GB of memory. Since August 2025 the billed duration also includes the Init phase after a cold start, for every type of function. The free tier includes 1 million requests and 400,000 GB-seconds each month.

The following table shows the calculation for a function invoked 5 million times a month with 512 MB of memory and an average billed duration of 120 ms. It uses the x86 prices for US East (N. Virginia), before the free tier is applied; arm64 functions cost about 20% less per GB-second.

ChargeCalculationCost
Requests5 million × USD 0.20 per millionUSD 1.00
Compute5,000,000 × 0.5 GB × 0.12 s = 300,000 GB-seconds × USD 0.0000166667USD 5.00
TotalUSD 6.00

Because cost depends on memory multiplied by time, adding memory does not always increase the bill. If doubling the memory to 1,024 MB halves the duration of a CPU-bound function to 60 ms, the compute charge stays at 300,000 GB-seconds and each response arrives twice as fast. Provisioned concurrency is billed separately, for the time it is configured, as Managing Concurrency, Throttling and Cold Starts explains.

AWS documentation now calls these functions Lambda Event Functions, to distinguish them from Lambda Web Functions, a separate form factor launched in October 2026 that runs a port-listening HTTP server, and from Lambda Managed Instances, which run functions on EC2 instances in the customer's account. Both are later additions that this study guide does not cover; every lesson in this module describes the standard, event-driven function model.

Worked example

An S3 handler that cannot find its object

A developer writes a function that S3 invokes for each uploaded file. It works in testing, but in production some invocations fail with NoSuchKey. Each failed object has a space or a special character in its name, such as March report.pdf.

The cause is in the event object. S3 URL-encodes object keys in event notifications, so a space arrives as + and other characters arrive as % sequences. The function passed March+report.pdf to GetObject, and no object has that key. The corrected handler decodes the key and processes every record in the event, rather than only the first:

import urllib.parse
import boto3

s3 = boto3.client("s3")   # created once per execution environment

def handler(event, context):
    for record in event["Records"]:
        bucket = record["s3"]["bucket"]["name"]
        key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
        obj = s3.get_object(Bucket=bucket, Key=key)
        print(f"{context.aws_request_id} read {key} ({obj['ContentLength']} bytes)")

Testing with the console's sample S3 event did not reveal the bug, because the sample key contains no special characters. Test events should include realistic edge cases, such as encoded keys, empty bodies and batches with more than one record.

Check yourself

A script calls a function synchronously with the SDK and treats an HTTP 200 response as success. Why does the script miss failures, and what should it check instead?

Show answer

Lambda returns 200 whenever it ran the function, even if the handler raised an exception. A function error is shown by the FunctionError field, set to Unhandled, and the payload then contains the errorType and errorMessage.

Exam Tips

Remember for the exam

  • The handler setting must match the code: file.function for Python, file.export for Node.js and package.Class::method for Java. A mismatch fails every invocation with Runtime.HandlerNotFound or Runtime.ImportModuleError.
  • The event's structure comes from the trigger. API Gateway and SQS bodies are JSON strings that must be parsed, S3 object keys are URL-encoded, and Records lists can hold several records.
  • The context object provides the request ID and get_remaining_time_in_millis(), which lets a function stop cleanly before its timeout.
  • A synchronous invocation whose handler raises an exception still returns HTTP 200; check the FunctionError field.
  • Go and Rust run on the OS-only provided.al2023 runtime as a binary named bootstrap. Container images make you responsible for patching the runtime inside the image.
  • Container images can be up to 10 GB but cannot use layers, and a function's package type cannot be changed after it is created.
  • Missing logs usually mean that the execution role lacks the CloudWatch Logs permissions in AWSLambdaBasicExecutionRole.
  • Cost is requests plus GB-seconds, so more memory can cost the same or less when it shortens a CPU-bound function's duration.