AlgoViz

AWS Lambda

medium 25 min

AWS Lambda runs your function when an event arrives and stops charging when it ends.

Video lesson · Chapter 1 of 5

The first thumbnail after a quiet morning

0:00 / 4:23

Cold and warm starts in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

AWS Lambda is functions as a service. You upload code and say which events start it. AWS finds a machine, prepares an isolated environment, runs the code and keeps or removes the environment afterwards.

You do not choose servers. You choose memory (which also sets the CPU share), a timeout, permissions and limits on concurrency. A function can run at zero copies or at thousands.

This page is about the classic form, which AWS now calls event functions: one event at a time per environment. Lambda has newer forms too, such as web functions, durable functions and managed instances, which are named where they matter.

Why it exists

Much code runs rarely or in bursts: resizing an upload, answering a webhook, a nightly clean-up. A server for it waits most of the day, needs patches all year and is too small on the busiest day.

Lambda turns that into a cost per run. The trade is less control: limited run time, no lasting local state, start-up delay and a platform that belongs to one provider.

A short history

  1. November 2014

    AWS announces Lambda in preview: run code in response to events, without servers.

  2. October 2018

    The longest run time goes from 5 to 15 minutes.

  3. November 2018

    AWS releases Firecracker, the small virtual machine monitor it built for serverless work, as open source.

  4. December 2019

    Provisioned concurrency arrives: environments prepared before the request.

  5. By November 2026

    The quotas page lists up to 30 minutes for a function, and 90 minutes for asynchronous and most event-source invocations on managed instances.

Words to know

Handler
The method Lambda calls for each event.
Execution environment
The isolated place where your function runs. It is reused while it stays warm.
Cold start
Creating and initializing a new environment before the handler can run.
Concurrency
How many requests are in progress at the same moment.
Reserved concurrency
A guaranteed share that is also a hard cap for one function.
Provisioned concurrency
Environments prepared in advance, for a charge.
Event source mapping
A Lambda component that polls a queue or stream and invokes your function with batches.
Layer
A shared package of libraries or a runtime, at most five per function.

How it works

Step through the idea, or press Play.

Step 1 of 3

An event arrives. A request, a file, a message or a timer

Understand it

Start here

The helper and the bell

Imagine a counter with a bell. Nobody stands there. When the bell rings, a helper appears. The first time they must put on an apron, which takes a moment. If another ring comes soon, they are ready at once. Two rings at the same time need two helpers.

Ring for help
Nobody there

The apron is the cold start. The number of helpers is the concurrency.

What you get

Why teams choose it

  • No servers to run

    Provisioning, patching the platform and scaling are done by AWS.

  • Pay per use

    Requests and duration, measured per millisecond. Idle on-demand functions cost no compute.

  • Fast growth

    Each function may add 1,000 environments every 10 seconds, up to the account limit.

  • Event triggers

    S3, API Gateway, SNS, SQS, DynamoDB Streams, Kinesis, EventBridge and more.

  • Several zones

    Functions run across Availability Zones. The service level agreement is 99.95% per Region and month.

  • Quick to ship

    Upload a zip file or a container image and it is live.

Architecture

What happens to an invocation

Inside the service

A client calls API Gateway, and S3 sends events. Both reach the Lambda front end inside the Lambda service. The front end hands the work to one of two execution environments, each its own box with one request. The environments fetch code from storage and write logs to CloudWatch.
Each thick box is one environment with one request in it. You never see the machines below.
  1. 1

    Request

    An API call waits for the answer. A file or a notification is handed over. A queue is polled.

  2. 2

    Front end

    Lambda checks permissions and the concurrency limits. Above the limit it throttles.

  3. 3

    Find an environment

    A worker manager gives out a warm one, or asks for a new one.

  4. 4

    Initialize if new

    Download the code, start the runtime and extensions, run everything outside the handler. This phase may take up to 10 seconds for on-demand functions.

  5. 5

    Run the handler

    The event arrives as JSON together with a context object. CPU follows memory: 1,769 MB equals one vCPU.

  6. 6

    Freeze

    The answer is returned and the environment freezes. It may serve again. Lambda ends environments every few hours even when they are busy.

Two requests, one environment

Anything left in memory or in the temporary directory may still be there. Never depend on it, and never keep one user's data there.

Two planes

PlaneDoesWhy the split
Control planeCreate functions, change code and settingsRare, and may be slower
Data planeInvoke functionsMust keep working while nothing is being changed
Published research by the Firecracker team describes front ends, a worker manager, placement and a fleet of worker machines. It is background, not something you configure.

Isolation comes from Firecracker microVMs: small virtual machines on top of KVM, with a minimal device model. The project states a boot time under 125 ms and less than 5 MiB of memory overhead each, which is why thousands can share one machine.

Cold starts

Where the first delay comes from

AWS says cold starts typically occur in under 1% of invocations and take from under 100 ms to over 1 second. A large framework can take several seconds. They are more common in development than in busy production functions.

Reducing a cold start

Initialization time is billed as well, so a lighter start saves money.
RemedyHow it worksWatch out
Lighter initFewer imports, only the SDK clients you useMeasure before and after
More memoryMore CPU, so init and handler run fasterCost per second rises, duration may fall
Provisioned concurrencyEnvironments are ready before requestsCharged while configured. Above it, cold starts return
SnapStartRestore a snapshot taken after init (Java, Python, .NET)Random seeds, ids and connections must be renewed
SnapStart and provisioned concurrency cannot be used together on a function version. Reserved concurrency does not remove cold starts.

Concurrency

How many environments?

Concurrency from rate and duration

C=λ×t100 reqs×0.5 s=50C = \lambda \times t \qquad 100\,\tfrac{\text{req}}{\text{s}} \times 0.5\,\text{s} = 50
At a peak of 3 times the average, plan for 150. A dependency that becomes 4 times slower needs 4 times the concurrency for the same traffic.

Limits that act together

LimitValueMeaning
Regional concurrency1,000 by default, can be raisedShared by all functions. New accounts start lower
Scaling rate1,000 environments per 10 s, per functionA sudden jump can throttle for a moment
Requests per environment10 per second (synchronous)Very short functions hit this one first
Reserved concurrencyYou set it, no chargeA guarantee and a cap. Zero switches the function off
Unreserved pool100 always leftSo you can never reserve everything

Reserved

  • No charge
  • Protects a critical function from its neighbours
  • Caps a function that would overload a database

Provisioned

  • Charged while configured
  • Removes the cold start up to that number
  • Does not cap the function by itself

Invocation

Who waits, and who retries

ModelSourcesOn errorWhen throttled
SynchronousAPI Gateway, direct callReturned to the callerStatus 429, the caller retries
AsynchronousS3, SNS, EventBridgeTwo more tries, after 1 and 2 minutesBack to the queue for up to 6 hours
Queue pollingSQSMessage visible again after the timeoutThe poller slows down
Stream pollingKinesis, DynamoDB StreamsThe shard waits and retries the batchRetries until success or expiry
An error in a stream batch blocks its shard. Set a maximum number of retries, bisect the batch on error, and send failures to a destination.

An asynchronous event that keeps failing

Configure an on-failure destination or a dead-letter queue. Without one, the event is discarded.

SQS done right

  1. 1

    Report partial failures

    Turn on ReportBatchItemFailures and return the ids that failed. Otherwise one bad message repeats the whole batch.

  2. 2

    Put the dead-letter queue on the source queue

    The function's own dead-letter queue is for asynchronous invocations only.

  3. 3

    Long visibility timeout

    AWS recommends at least six times the function timeout.

  4. 4

    Cap with maximum concurrency

    From 2 up. A mapping starts with five concurrent batches, adds up to 300 a minute and stops at 1,250 by default.

Limits

The numbers

ResourceLimit
Memory128 MB to 10,240 MB, in 1 MB steps
Run time30 minutes. 90 on managed instances for asynchronous and most polled events
Temporary disk512 MB to 10,240 MB
Zip package50 MB zipped by direct upload, 250 MB unzipped with layers
Container image10 GB uncompressed
Layers5
Environment variables4 KB in total
Payload, synchronous6 MB each way, 200 MB for a streamed response
Payload, asynchronous1 MB
File descriptors, threads1,024 each
Defaults from the AWS quotas page in November 2026. Many older articles still say 15 minutes and 256 KB.

What you are billed for

GB-s=memory1024 MB×t5121024×1 s=0.5\text{GB-s} = \frac{\text{memory}}{1024\,\text{MB}} \times t \qquad \frac{512}{1024} \times 1\,\text{s} = 0.5
The bill is a charge per request plus a charge per GB-second. Doubling memory halves the time of CPU-bound code in the best case, which leaves the GB-seconds equal and the answer faster.

Network and security

VPC, permissions, secrets

  • Execution role

    What the function may do. Give each function its own, as small as possible.

  • Resource policy

    Who may invoke it, such as one bucket or one API.

  • VPC

    Attach it only to reach private resources. Shared Hyperplane network interfaces are made ahead of time, so the old long VPC cold start is gone. Internet access then needs a NAT or an endpoint.

  • Secrets

    Read them from a secrets service and cache them outside the handler. Environment variables are visible to anyone who can read the configuration.

Newer forms

Other ways to run on Lambda

FormDifferenceUse it for
Event functionOne request per environmentEvents, queues, small APIs
Web functionAn HTTP server, many requests per environmentWeb apps and API back ends
Durable functionCheckpoints and replays, up to one yearWorkflows that wait
Managed instancesRuns on instances you own, several requests per environmentSteady or special workloads
Step Functions is the service for workflows drawn as a graph across many AWS services.

Operations

Deploy and watch

Shell
zip -r function.zip index.mjs node_modules/aws lambda update-function-code --function-name my-function \  --zip-file fileb://function.zipaws lambda wait function-updated-v2 --function-name my-function# an immutable version, an alias, and ready environments on the aliasaws lambda publish-version --function-name my-functionaws lambda update-alias --function-name my-function --name prod \  --function-version 7aws lambda put-provisioned-concurrency-config \  --function-name my-function --qualifier prod \  --provisioned-concurrent-executions 10# protect the databaseaws lambda put-function-concurrency --function-name my-function \  --reserved-concurrent-executions 50
Provisioned concurrency belongs to a version or an alias, never to $LATEST.
YAML
AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31Resources:  MyFunction:    Type: AWS::Serverless::Function    Properties:      Handler: index.handler      Runtime: nodejs24.x      CodeUri: src/      MemorySize: 512      Timeout: 30      Events:        Api:          Type: Api          Properties:            Path: /hello            Method: get
An AWS SAM template. Managed runtimes exist for Node.js, Python, Java, .NET and Ruby. Go and others use the OS-only runtime.

Watch these

  1. 1

    Throttles and ConcurrentExecutions

    Per function and for the Region.

  2. 2

    Duration against timeout

    A timeout at the limit means lost work. Set it above the slow percentile, not at the maximum.

  3. 3

    Init duration

    In the report line of each cold invocation.

  4. 4

    Age of events

    AsyncEventAge, the age of the oldest SQS message, the iterator age of a stream.

  5. 5

    Failure destinations

    Alert when anything arrives there.

Choose

When Lambda, and when not

Choose Lambda

  • Reacting to uploads, messages, webhooks
  • Uneven traffic with idle hours
  • Work of seconds or minutes
  • Functions that must scale separately
  • Prototypes
  • Scheduled jobs

Choose something else

  • Work beyond 30 minutes in one go
  • Steady high load where containers are cheaper
  • Latency that cannot accept a rare cold start
  • GPUs or more than 10 GB of memory
  • Long-lived state in memory
  • Packages beyond 250 MB (or use an image)

Where should this code run?

Long, steady and strict are the three words that point away from a plain function.

Where else could it run?

LambdaFargateEC2Kubernetes
UnitFunction callTaskMachinePod
Scale to zeroYesOnly if you set it to zero tasksOnly by stopping machinesWith add-ons, the cluster stays
Run time30 minutesNo fixed limitNo fixed limitNo fixed limit
Paid byRequests and GB-secondsvCPU and memory secondsInstance timeNodes and control plane
You operateCodeImagesEverything above the hardwareCluster and images
PortabilityAWSAWS, standard containersHighHigh
AWS App Runner, once the simple choice for web containers, is closed to new customers. AWS points them to Amazon ECS Express Mode.

Strengths

  • No servers to patch
  • Nothing to pay for when idle
  • Grows in seconds
  • Triggers from many AWS services
  • Several zones by default

Costs

  • Cold starts
  • Bounded run time
  • No lasting local state
  • Deep ties to AWS
  • Steady load can cost more than containers
  • 10 GB of memory, CPU tied to it

Summary

The whole topic in one minute.

Lambda runs a function in an isolated environment per concurrent request. New environments cost a cold start, idle ones are frozen and reused. Concurrency equals requests per second times seconds per request, and it is limited per Region and by how fast each function may grow.

How the function is invoked decides who retries. A synchronous caller must retry, asynchronous events are tried up to three times by default, and queues and streams are polled in batches. All of them can repeat, so make the function idempotent. Use Lambda for events and spikes. Use containers for long, steady or stateful work.

  • One event function environment handles one request at a time.
  • Concurrency is rate times duration.
  • Reserved caps and protects. Provisioned removes cold starts up to a number.
  • The invocation model decides who retries.
  • Expect repeats and make effects idempotent.
  • Protect the database from your own scaling.

Sources