A kitchen that only cooks when there's an order
Picture a kitchen where nobody stands around waiting. You hand in one recipe. Whenever an order ticket arrives, the head chef gives it to a cooking station, a cook makes the dish from your recipe, and the station is free again.
Tickets come from all sorts of places: a customer at the counter, a delivery left at the back door, a ticket on the rail, or the kitchen clock saying "it's nine, bake the bread". Each one is an event.
You don't rent the kitchen by the month. You pay a little for every dish and for every minute a station spends cooking it. A bigger station, with a stronger stove, costs more per minute but cooks faster. On a quiet day you pay nothing at all.
Functions run on events
AWS Lambda runs a function (your code plus a runtime such as Java 21) when an event invokes it. You don't provision or patch servers; that's what "serverless" means. Common triggers:
| Source | How it invokes |
|---|---|
| API Gateway, function URL | Synchronously, one invocation per HTTP request |
| S3 object created | Asynchronously, one event per notification |
| EventBridge schedule | Asynchronously, on a cron or rate expression |
| SQS, Kinesis, Kafka | Lambda polls the source (an event source mapping) and invokes with batches |
Pricing has two parts: a charge per request, and duration, measured in milliseconds (rounded up) and multiplied by the configured memory, so it's billed in GB-seconds. Memory can be set from 128 MB to 10,240 MB, and CPU is allocated in proportion to it (about one vCPU at 1,769 MB), so more memory often finishes CPU-bound work faster. With no invocations there is no compute charge, except for provisioned concurrency.
Setting up a station
When the first ticket of the day arrives, there's no station ready. Someone has to unpack the knives and light the stove before the cook can start, so that first dish is slow. That wait is called a cold start.
The next ticket usually goes to the same station. The stove is already hot, so it's quick. That's why a good recipe says "light the stove once, when you set up", not "light the stove for every dish".
But don't leave anything on the counter you'll need later. When the kitchen goes quiet, stations are cleared away without warning, leftovers and all. Anything worth keeping goes in the pantry.
Execution environments, cold and warm starts
Each invocation runs in an execution environment: an isolated micro-VM with your code, the runtime and a writable
/tmp. An environment handles one invocation at a time (in the default mode; Lambda Managed Instances, which run on EC2
capacity, can send several concurrent invocations to one environment).
- Cold start: no free environment exists, so Lambda creates one, downloads the code, starts the runtime (for Java, a JVM) and runs your init code, everything outside the handler method. Then it invokes the handler.
- Warm start: an existing environment is reused. Init doesn't run again, and objects created during init (SDK clients, connection pools, parsed config) are reused.
So create clients once, outside the handler, not on every call. Cold starts are worst for runtimes with heavy startup, such as a JVM loading a framework.
Functions should be stateless. Static fields and /tmp survive between invocations on the same environment and
make a handy cache, but Lambda reclaims idle environments without notice and runs many in parallel, so the next
request may land somewhere with none of it. Keep real state in DynamoDB, S3, a database or a cache service.
A busy lunchtime
One station cooks one dish at a time. When three orders arrive together, the head chef sets up three stations. The number of stations cooking at once is called concurrency.
There's a limit to how many stations the kitchen has room for. You can set some aside for your recipe, so a busy neighbour can't take them all, and that number is also the most your recipe may use. When every allowed station is busy, a customer at the counter is told "not right now, try again in a moment".
For a rush you know is coming, you can pay to have stations set up, stoves lit, before anyone orders. Nobody waits for a setup, but you pay for those stations even while they stand empty.
Concurrency, scaling and throttling
Concurrency is the number of invocations in flight at once, which equals the number of busy execution environments. Lambda scales out by creating environments as concurrency rises. Each function can add up to 1,000 environments every 10 seconds, and all functions in a Region share the account's concurrency quota (1,000 by default, raisable; new accounts may start lower).
- Reserved concurrency on a function both guarantees that many units from the account pool and caps the function at it. It costs nothing. Setting it to 0 stops the function from being invoked at all. It's also a way to protect a downstream database from a flood of connections.
- Provisioned concurrency keeps a number of environments initialized ahead of time, so requests up to that number skip the cold start. It's set on a version or alias and billed for as long as it's configured.
Beyond the limit, invocations are throttled. A synchronous caller gets 429 TooManyRequestsException and must
retry itself. Throttled asynchronous events go back on Lambda's internal queue and are retried for up to the
maximum event age.
Waiting at the counter, or leaving a ticket
A customer at the counter waits for the dish. If it goes wrong, they find out at once and can decide whether to ask again.
A delivery driver doesn't wait. They drop a note in the ticket tray, the kitchen says "got it", and they drive off. Now the kitchen is in charge of getting it done.
Every dish has a kitchen timer. If the dish isn't ready when it rings, it goes in the bin. For a tray ticket, the kitchen then tries twice more. If it still fails, the ticket goes in a failed box, if you've put one out, so someone can look at it later. With no box, it's thrown away. Trying again means a dish might get made twice, so the recipe should check the ticket number first.
Synchronous and asynchronous invocation
- Synchronous (
RequestResponse): the caller waits for the result. API Gateway and SDKInvokecalls work this way. Errors return to the caller, and Lambda itself doesn't retry; the client or service decides. - Asynchronous (
Event): Lambda puts the event on an internal queue and immediately returns202. S3, SNS and EventBridge invoke this way. If the function fails, Lambda retries twice by default (configurable 0 to 2), waiting about 1 minute before the first retry and 2 minutes before the second. Events stay queued for up to 6 hours by default (the maximum event age, configurable down to 60 seconds). After that, the event goes to an on-failure destination or dead-letter queue if you configured one, and is dropped otherwise.
The timeout is a per-function setting, 3 seconds by default and 900 seconds (15 minutes) at most. A function that hits it is stopped, and the invocation counts as an error, which triggers the same retries. Long jobs belong in Step Functions, ECS or a batch service instead.
For event source mappings (SQS, Kinesis, Kafka) the rules come from the source: an SQS message that fails returns to the queue after its visibility timeout, and a stream, by default, retries the batch until it succeeds or the records expire (configurable with maximum retry attempts, maximum record age and batch bisecting).
Every one of these paths can deliver the same event more than once, so handlers must be idempotent: record a key such as the S3 object key and version, or the SQS message id, and skip work you've already done.
The recipe, written in Java
In Java, your recipe is written down as one set of cooking steps for one dish. Anything you prepare before those steps happens once, when the station is set up; the steps themselves run for every ticket.
Every cook wears a badge, called an execution role, that lists the store rooms they may open. If the recipe says "fetch flour from the pantry", the badge must allow the pantry. A door the badge doesn't list stays shut, even if the recipe asks for it, so a mistake in the recipe can't wander into the wine cellar.
Java stations are slow to set up. One trick is to set a station up perfectly once, take a photo of it, and lay out every new station from the photo instead of from scratch.
A Java handler and its execution role
Implement RequestHandler<I, O> from aws-lambda-java-core; event types such as APIGatewayProxyRequestEvent come
from aws-lambda-java-events. The handler setting names the class, for example shop.OrderHandler::handleRequest.
1public class OrderHandler2implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {34// Init phase: built once per execution environment, reused on warm starts5private static final DynamoDbClient dynamo = DynamoDbClient.create();67@Override8public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {9String id = context.getAwsRequestId();10dynamo.putItem(PutItemRequest.builder()11.tableName("orders")12.item(Map.of("id", AttributeValue.fromS(id),13"body", AttributeValue.fromS(event.getBody())))14.build());15return new APIGatewayProxyResponseEvent().withStatusCode(201).withBody(id);16}17}
The function's execution role is an IAM role that Lambda assumes (its trust policy allows
lambda.amazonaws.com). The SDK picks up its temporary credentials automatically, so there are no keys in code. Grant
only what the function needs, here dynamodb:PutItem on the orders table, plus CloudWatch Logs access (the
AWSLambdaBasicExecutionRole managed policy) so it can write logs. Anything else fails with AccessDenied.
With Spring, Spring Cloud Function's AWS adapter can expose a java.util.function.Function bean as the handler, at
the price of a heavier init.
SnapStart for Java: with SnapStart enabled, Lambda runs your init code when you publish a function version,
snapshots the initialized environment, and restores new environments from that cached snapshot instead of
initializing from scratch. It works on Java 11 and later managed runtimes, only on published versions (and aliases
pointing at them, not $LATEST), and can't be combined with provisioned concurrency, Amazon EFS, or more than 512 MB of
ephemeral storage. Anything unique captured during
init, such as random seeds or open connections, is shared by every restored copy, so re-create those after restore
(the runtime hooks from Project CRaC exist for this).
Choosing the knobs: provisioned concurrency for strict latency on a known baseline, SnapStart for cheaper Java cold-start relief, and more memory when a function is CPU-bound, since a faster run can cost the same or less.