AWS Lambda: Functions as a Service

How AWS Lambda works in practice: invocation models, the execution environment, packaging, permissions, concurrency, pricing and the newer options.

Cloud

AWS Lambda launched in 2014 and gave the industry the term Functions as a Service. You upload a handler, connect it to an event source, and AWS runs it when something happens: an HTTP request, a file landing in S3, a message on a queue, a timer. There is no instance to choose and nothing to patch, and when no events arrive, nothing runs and nothing is billed.

The previous article covered serverless architecture in general: cold starts, idempotency, event-driven design and when functions are the wrong tool. This one is specific to Lambda. It covers how invocations reach your code, what the execution environment does, how to package and secure a function, how concurrency works, what you pay for, and the newer features that have stretched what a Lambda function can be.

The pieces of a Lambda function

A Lambda function is a small bundle of configuration around your code:

  • Handler. The function Lambda calls for each event, such as app.handler in Python (the handler function in app.py).
  • Runtime. The language environment. Managed runtimes currently include Node.js 24, Python 3.14, Java 25 and .NET 10, along with older versions and Ruby. Go and Rust run on the OS-only runtime (provided.al2023), where you ship a compiled binary.
  • Memory. From 128 MB to 10,240 MB. This is the main performance setting, because CPU is allocated in proportion to memory.
  • Timeout. Up to 900 seconds (15 minutes) for a standard function.
  • Architecture. x86_64 or arm64 (Graviton). Arm is billed at a lower price per GB-second, and most interpreted code runs on it without changes.
  • Execution role. An IAM role the function assumes, which decides what AWS APIs your code can call.
  • Triggers. The event sources that invoke it.

Everything else, such as environment variables, VPC attachment, ephemeral storage in /tmp (512 MB by default, configurable up to 10,240 MB) and logging settings, is optional.

Here is the smallest useful example, a Python handler and the AWS CLI commands to deploy and call it:

# app.py
import json


def handler(event, context):
    name = event.get("name", "world")
    return {
        "message": f"Hello, {name}",
        "request_id": context.aws_request_id,
        "remaining_ms": context.get_remaining_time_in_millis(),
    }
zip function.zip app.py

aws lambda create-function \
  --function-name hello \
  --runtime python3.14 \
  --architectures arm64 \
  --handler app.handler \
  --memory-size 256 \
  --timeout 10 \
  --role arn:aws:iam::123456789012:role/hello-lambda-role \
  --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

The role must already exist and trust lambda.amazonaws.com. Attaching the AWS managed policy AWSLambdaBasicExecutionRole is enough for this function, since all it needs is permission to write logs to CloudWatch.

Three ways events reach your code

Every Lambda trigger falls into one of three invocation models, and the model decides who waits, who retries and where failures end up. Knowing which one a trigger uses tells you most of what you need about its error handling.

flowchart LR
  subgraph Sync["Synchronous"]
    A1["API Gateway or function URL"] --> L1["Lambda"]
    L1 -->|"Response"| A1
  end
  subgraph Async["Asynchronous"]
    A2["S3, SNS, EventBridge"] --> Q["Lambda internal queue"]
    Q --> L2["Lambda"]
    L2 --> D["Destination or DLQ"]
  end
  subgraph Poll["Event source mapping"]
    S["SQS, Kinesis, DynamoDB Streams, Kafka"] -->|"Lambda polls in batches"| L3["Lambda"]
  end

Synchronous invocation

The caller waits for the result. API Gateway, Application Load Balancer, Lambda function URLs and direct Invoke calls work this way. If the function throws an error or times out, the error goes back to the caller, and retrying is the caller’s job. The request and response payloads are each limited to 6 MB.

Asynchronous invocation

The caller hands the event to Lambda and gets an immediate acknowledgement. S3 notifications, SNS and EventBridge use this model. Lambda puts the event on an internal queue and invokes the function from there. If the function fails, Lambda retries twice by default, and it discards events older than the configured maximum event age (up to six hours). Configure an on-failure destination (SQS, SNS, EventBridge, S3 or another function) so failed events are kept instead of silently dropped. The async payload limit is 1 MB.

Event source mappings

For queues and streams, Lambda itself polls the source and invokes your function with batches of records. This covers SQS, Kinesis, DynamoDB Streams, Amazon MSK, self-managed Kafka, Amazon MQ and DocumentDB change streams. Retry behaviour depends on the source. A failed SQS batch becomes visible again on the queue after the visibility timeout. A failed stream batch blocks that shard until it succeeds, expires or hits the retry limit you set. Partial batch responses, shown in the previous article’s SQS example, let you report only the failed records.

SynchronousAsynchronousEvent source mapping
ExamplesAPI Gateway, function URLs, ALBS3, SNS, EventBridgeSQS, Kinesis, DynamoDB Streams, Kafka
Who waitsThe callerNobodyNobody
Who retriesThe callerLambda, twice by defaultLambda, per source rules
Failures go toThe caller as an errorDestination or dead-letter queueQueue redrive policy or on-failure destination
Payload limit6 MB each way1 MBBatch size settings

An S3-triggered function fails on some uploads, and those events disappear with no trace. What should you add?

  • A longer function timeout
  • An SQS event source mapping on the bucket
  • An on-failure destination for asynchronous invocations

Correct! S3 invokes Lambda asynchronously, so after Lambda's retries are exhausted the event is discarded unless an on-failure destination or dead-letter queue is configured.

Inside the execution environment

Each invocation runs inside an execution environment: a Firecracker microVM holding your runtime, your code and any layers. An environment has three phases.

sequenceDiagram
  participant L as Lambda service
  participant E as Execution environment
  L->>E: Init: start runtime, load code
  E->>E: Run module-level code
  L->>E: Invoke: event 1
  E-->>L: Result
  L->>E: Invoke: event 2 (warm)
  E-->>L: Result
  Note over E: Idle, frozen between invokes
  L->>E: Shutdown
  • Init starts the runtime and runs your code outside the handler: imports, SDK clients, configuration loading. It runs once per environment and is limited to 10 seconds for on-demand functions.
  • Invoke runs the handler for one event. A standard Lambda environment handles one invocation at a time.
  • Shutdown happens when Lambda decides to reclaim an idle environment. You don’t control when.

Since August 2025, Lambda bills the Init phase consistently for all function types, including zip-packaged functions on managed runtimes, where it used to be free. Slow initialization therefore costs money as well as latency, which is one more reason to keep packages small and imports lean.

Memory is also CPU

Lambda has no separate CPU setting. At 1,769 MB a function gets the equivalent of one full vCPU, and the allocation rises to six vCPUs at the 10,240 MB maximum. A CPU-bound function at 128 MB can run many times slower than the same code at 1,024 MB, and because you pay for memory multiplied by duration, the larger setting is sometimes cheaper overall. The open source AWS Lambda Power Tuning tool runs your function at several memory sizes and charts cost against speed, which beats guessing.

Reducing cold starts

Three features target the Init phase:

  • Provisioned concurrency keeps a set number of environments initialized and ready on a published version or alias. You pay for them while they are configured.
  • SnapStart takes a snapshot of the initialized environment when you publish a version, then restores from that snapshot instead of running Init again. It supports Java 11 and later, Python 3.12 and later and .NET 8 and later, now including container images built on AWS base images. It has no extra charge for Java; for Python and .NET there are caching and restore charges.
  • Smaller packages and lazy imports cost nothing. Load heavy libraries only in the code paths that need them.

Packaging and deploying

A function’s code ships in one of two formats.

Zip archiveContainer image
Size limit50 MB zipped for direct upload, 250 MB unzipped including layers10 GB
RuntimeManaged or OS-only runtimeAny, built on AWS base images or your own with the runtime interface client
Shared codeUp to five layersImage layers in your Dockerfile
Stored inLambda (or S3 for larger uploads)Amazon ECR
Good forMost functions, fast iterationLarge dependencies such as ML libraries, existing container tooling

Layers are zip archives of libraries or tools that several functions share. They are useful for a common dependency set, but they count toward the 250 MB unzipped limit, and they make it harder to see what version of a library a function actually runs. Many teams now bundle dependencies into each function and use layers mostly for things like monitoring extensions.

For anything beyond a demo, describe functions as infrastructure as code. The AWS Serverless Application Model (SAM) is an extension of CloudFormation with shorthand for functions and their triggers. This template creates an upload bucket, an output bucket and a function that runs for each new object:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources:
  UploadBucket:
    Type: AWS::S3::Bucket

  OutputBucket:
    Type: AWS::S3::Bucket

  IndexFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.handler
      Runtime: python3.14
      Architectures: [arm64]
      MemorySize: 512
      Timeout: 30
      Environment:
        Variables:
          OUTPUT_BUCKET: !Ref OutputBucket
      Policies:
        - S3ReadPolicy:
            BucketName: !Ref UploadBucket
        - S3WritePolicy:
            BucketName: !Ref OutputBucket
      Events:
        NewUpload:
          Type: S3
          Properties:
            Bucket: !Ref UploadBucket
            Events: s3:ObjectCreated:*

And the handler it deploys, which records each upload’s size and content type as a JSON document in the output bucket:

# src/app.py
import json
import os
from urllib.parse import unquote_plus

import boto3

s3 = boto3.client("s3")
OUTPUT_BUCKET = os.environ["OUTPUT_BUCKET"]


def handler(event, context):
    for record in event["Records"]:
        bucket = record["s3"]["bucket"]["name"]
        key = unquote_plus(record["s3"]["object"]["key"])

        head = s3.head_object(Bucket=bucket, Key=key)
        summary = {
            "source": f"s3://{bucket}/{key}",
            "size_bytes": head["ContentLength"],
            "content_type": head.get("ContentType"),
        }

        s3.put_object(
            Bucket=OUTPUT_BUCKET,
            Key=f"index/{key}.json",
            Body=json.dumps(summary).encode("utf-8"),
            ContentType="application/json",
        )

Two details matter here. Object keys arrive URL-encoded in S3 events, hence unquote_plus. And the function writes to a different bucket from the one that triggers it; writing back into the source bucket would invoke the function again for its own output. Lambda detects some recursive loops between Lambda, SQS, SNS and S3 and stops them, but you shouldn’t build anything that depends on that safety net. Deploy with sam build followed by sam deploy --guided.

Versions and aliases

Publishing a version freezes the code and configuration under a number. An alias, such as live, is a named pointer to a version, and callers and triggers should reference the alias. Rolling back is then just pointing the alias at the previous version. Aliases can also split traffic between two versions by weight, which is how SAM and CodeDeploy run gradual canary deployments.

aws lambda publish-version --function-name hello
aws lambda create-alias --function-name hello --name live --function-version 3

Permissions: two separate policies

Lambda security has two sides, and mixing them up is the most common source of “access denied” errors.

flowchart LR
  S3["S3 bucket"] -->|"Allowed by resource-based policy"| F["Lambda function"]
  APIGW["API Gateway"] -->|"Allowed by resource-based policy"| F
  F -->|"Allowed by execution role"| DDB[("DynamoDB")]
  F -->|"Allowed by execution role"| CW["CloudWatch Logs"]
  • The execution role controls what the function can do. It is an IAM role with policies granting specific actions on specific resources. Give each function its own role with only the permissions it needs, not a shared role with broad access.
  • The resource-based policy controls who can invoke the function. When you add an S3 or API Gateway trigger, the console or SAM adds a statement allowing that service to call lambda:InvokeFunction. Event source mappings are the exception: Lambda polls the queue or stream itself, so the execution role needs read permissions on the source instead.

Secrets belong in AWS Secrets Manager or Systems Manager Parameter Store, read at Init and cached, rather than in plain environment variables. Environment variables are encrypted at rest, but anyone who can read the function’s configuration can see them.

Calling a function over HTTP

For a plain HTTPS endpoint, a function URL gives a function its own https://<id>.lambda-url.<region>.on.aws/ address with no API Gateway in front. Its auth type is either AWS_IAM, which requires signed requests, or NONE, which makes it public, so your code has to do its own authentication. Function URLs also support response streaming, which sends the response as it is produced, up to 200 MB, instead of buffering it under the 6 MB limit. Choose API Gateway instead when you need request validation, usage plans, custom authorizers or many routes under one domain.

A function triggered by API Gateway gets AccessDenied when it writes to a DynamoDB table. Which policy needs to change?

  • The function's execution role
  • The function's resource-based policy
  • The API Gateway stage settings

Correct! The execution role governs what the function's code can do, including DynamoDB writes; the resource-based policy only controls who can invoke the function.

Concurrency and scaling

Concurrency is the number of invocations running at the same moment. Because each standard environment handles one request at a time, a function serving 200 requests per second that each take 500 ms needs about 100 concurrent environments.

The account default is 1,000 concurrent executions per Region, shared by all functions in it, and it can be raised through Service Quotas. New accounts may start lower and get raised automatically with usage. Each function can scale up by 1,000 execution environments every 10 seconds until it reaches the account limit, and requests beyond that are throttled.

Two controls shape this:

  • Reserved concurrency sets aside part of the account pool for one function, and also acts as its maximum. Use it to protect critical functions from noisy neighbours, and to cap functions in front of something fragile, such as a relational database. Setting it to zero stops a function from running at all, which is a useful emergency brake.
  • Provisioned concurrency, described above, pre-initializes environments for latency. It does not cap anything.
# Never run more than 50 copies of this function at once
aws lambda put-function-concurrency \
  --function-name orders-writer \
  --reserved-concurrent-executions 50

# Keep 5 environments warm on the live alias
aws lambda put-provisioned-concurrency-config \
  --function-name hello \
  --qualifier live \
  --provisioned-concurrent-executions 5

Functions attached to a VPC get elastic network interfaces in your subnets. Since 2019 these are created when the function is configured and shared across environments, so VPC attachment no longer adds per-invocation cold start time. It does mean the function needs a NAT gateway or VPC endpoints to reach the internet or other AWS APIs, just like any other resource in a private subnet.

What Lambda costs

Standard Lambda pricing has two parts: a charge per request and a charge for compute duration, measured in GB-seconds (memory allocated multiplied by run time, metered per millisecond). Arm functions have a lower duration price than x86. The free tier includes 1 million requests and 400,000 GB-seconds per month, shared across both architectures. Provisioned concurrency, SnapStart for Python and .NET, extra ephemeral storage and data transfer are billed separately. Current rates are on the Lambda pricing page, and the AWS free tier and billing overview explains how to set budgets and alerts before you experiment.

A few habits keep bills predictable:

  • Measure before choosing memory; a bigger setting that finishes faster can cost less.
  • Set realistic timeouts. A function stuck waiting on an unresponsive API bills until the timeout.
  • Use arm64 unless a dependency needs x86.
  • Set CloudWatch Logs retention. Log storage for a busy function can outgrow its compute cost.

Newer options that stretch the model

Lambda’s core model has stayed the same for a decade, but since late 2025 AWS has added two capabilities that change where it fits.

Durable functions

Announced in December 2025, durable functions let a single Lambda function run a multi-step process that lasts far longer than 15 minutes. You write ordinary sequential code with an SDK. Each step is checkpointed with its result, and a wait suspends the execution without consuming compute. When the execution resumes, Lambda invokes the function again and the SDK replays it, returning stored results for steps that already completed instead of running them twice. Because of that replay, code outside steps must be deterministic.

Durable functions launched for Python and Node.js, with SDKs for Java and .NET following. They overlap with Step Functions. A rough split: durable functions suit developers who want workflow logic in code next to the rest of the function, while Step Functions suits workflows that coordinate many AWS services and benefit from a visual definition and execution history.

Lambda Managed Instances

Lambda Managed Instances, announced in November 2025, runs your functions on EC2 instances in your account that Lambda provisions, patches and scales through a capacity provider you configure. One execution environment can handle several invocations concurrently, there are no cold starts in the usual sense because capacity is already running, and you can choose instance types, including ones with more memory or specialised hardware. Since September 2026, functions on Managed Instances can run for up to 90 minutes, though synchronous invocations keep the 15-minute maximum.

The pricing is different: Lambda request charges, plus the EC2 instance cost, plus a management fee on top. Savings Plans and Reserved Instances can discount the EC2 portion. That makes Managed Instances a fit for steady, high-volume workloads where the standard per-millisecond model becomes expensive, which is exactly the case the previous article flagged as a weak spot for functions.

Standard LambdaLambda Managed Instances
Runs onFirecracker microVMs in AWS-owned capacityEC2 instances in your account, managed by Lambda
Requests per environment1Several at once
Scales to zeroYesNo, capacity stays provisioned
Maximum run time15 minutes90 minutes for non-synchronous invocations
BillingRequests plus GB-secondsRequests plus EC2 cost plus management fee
Best forSpiky or low trafficSteady, predictable high traffic

Observability

Every function writes to CloudWatch Logs, and Lambda publishes metrics for invocations, errors, throttles, duration and concurrent executions without any setup. Three additions make debugging a production system practical:

  • Structured JSON logs, which Lambda can emit natively with a log level setting, so you can filter and query fields instead of grepping text.
  • Tracing with AWS X-Ray or OpenTelemetry, so a request can be followed through API Gateway, several functions and the queues between them.
  • Alarms on errors, throttles and async event age, so failures show up before customers report them.

Powertools for AWS Lambda, an open source library for Python, TypeScript, Java and .NET, packages structured logging, metrics, tracing, idempotency and batch processing helpers, and is worth adding to most production functions.

Further reading

Key takeaways

  • A Lambda function is a handler plus configuration: runtime, memory (which also sets CPU), timeout up to 15 minutes, architecture, execution role and triggers.
  • Triggers use one of three invocation models: synchronous, asynchronous or event source mapping. The model decides who retries and where failed events go, so configure destinations or dead-letter queues for anything asynchronous.
  • Code outside the handler runs once per execution environment during Init, which is now billed. Keep it lean, and use provisioned concurrency or SnapStart when cold starts matter.
  • The execution role controls what a function can do; the resource-based policy controls who can invoke it.
  • Concurrency is shared across a Region’s functions. Use reserved concurrency to cap functions in front of fragile systems and to protect critical ones.
  • Pricing is per request plus GB-seconds. Tune memory by measurement and prefer arm64.
  • Durable functions extend Lambda to long-running, multi-step workflows in code, and Managed Instances move steady high-volume workloads onto EC2 capacity that Lambda manages.

Part 2 of 2 · Serverless Computing

  1. 01Understanding Serverless Architecture
  2. 02AWS Lambda: Functions as a Service
Ready to check your understanding?Take the Fluffy Computing quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open