TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท serverless ยท cloud ยท java

AWS Lambda and serverless

AWS Lambda runs your function in managed execution environments in response to events, scales by adding environments per concurrent request, and bills per request and per millisecond of duration at the memory you configure.

14 min5 animations

๐Ÿ“š Builds on๐Ÿ”˜ Idempotency๐Ÿชช AWS IAM: users, roles and policies

๐Ÿ–จ๏ธ Cheat sheet

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:

SourceHow it invokes
API Gateway, function URLSynchronously, one invocation per HTTP request
S3 object createdAsynchronously, one event per notification
EventBridge scheduleAsynchronously, on a cron or rate expression
SQS, Kinesis, KafkaLambda 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.

Functions run on events5 steps
The bill01234๐Ÿ™‹Customer at the counter๐Ÿ“ฆDelivery at the back doorโฐKitchen clock๐Ÿง‘โ€๐ŸณCooking station
Press play and watch it happen!

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.

Cold and warm starts5 steps
๐Ÿ™‹Customer at the counter๐Ÿฅซ Pantry
Press play and watch it happen!

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.

Concurrency and throttling4 steps
๐Ÿ‘ฅLunch crowd๐Ÿ‘ฉโ€๐ŸณHead chef๐Ÿง‘โ€๐ŸณStation 1
Press play and watch it happen!

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 SDK Invoke calls 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 returns 202. 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.

Synchronous, asynchronous and retries5 steps
Ticket tray0123Failed box0123๐Ÿ™‹Customer at the counter๐ŸššDelivery driver๐Ÿง‘โ€๐ŸณCooking station
Press play and watch it happen!

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 OrderHandler2        implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {3 4    // Init phase: built once per execution environment, reused on warm starts5    private static final DynamoDbClient dynamo = DynamoDbClient.create();6 7    @Override8    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {9        String id = context.getAwsRequestId();10        dynamo.putItem(PutItemRequest.builder()11                .tableName("orders")12                .item(Map.of("id", AttributeValue.fromS(id),13                             "body", AttributeValue.fromS(event.getBody())))14                .build());15        return 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.

๐Ÿ”ง Going deeper

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.

A Java handler and its role3 steps
๐Ÿ™‹Customer at the counter๐Ÿง‘โ€๐ŸณCooking station๐Ÿฅซ Pantry๐Ÿท Wine cellar
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • โšกServerless APIThe smallest useful backend: API Gateway, Lambda and DynamoDB.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about AWS Lambda and serverless, told the same way as the story.
  1. The recipe says to light the stove at the start of every dish. Why is that a poor recipe?
  2. The cook keeps a tally of orders written on the station's counter. What goes wrong?
  3. Your recipe may use three stations at most, and all three are busy. What happens to a fourth customer at the counter?
  4. A ticket from the tray keeps failing because the timer rings. Why should the recipe check the ticket number before cooking?
Answer every question to check.Passing marks AWS Lambda and serverless as done.
Got the hang of AWS Lambda and serverless? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 6 of 12

โ† Previous on the path๐Ÿชฃ Amazon S3Next on the path โ†’๐Ÿงบ Amazon SQS and SNS

๐Ÿ‘‰ Read next

  • ๐ŸƒAWS Step FunctionsA relay race through town, run by an official with a course map who records every handover.