Every morning, the first click on notes-api's export button takes almost a second before anything happens. The clicks after it are fast. Then one day someone presses "Export all" for 40 notes, and out come 42 PDFs: two notes came out twice.
Both problems belong to serverless patterns: ways of arranging many small event-triggered functions so that together they do a big job. They cover: splitting work through a queue, staying safe when an event is delivered twice, and managing cold starts. Remember the on-call cook from the AWS Lambda Deep Dive lesson: a cook is a running copy of the function (an environment). Now picture a day with a big order. 40 order slips arrive at once in a box, and several cooks take slips from that box and cook at the same time (fan-out). The box is the queue, and each slip is one message. A cook who has just arrived first has to set up their table (cold start). How long that takes depends on how heavy their tool bag is (package size, the function's code with its dependencies), the kind of stove (runtime) and the preparation they do before cooking (init code). Sometimes the same slip lands in the box twice. So a tidy cook checks the stamp book (the list of orders already cooked) first, to avoid cooking the same order twice (an idempotent handler). In the code later, the stamp book is the DynamoDB table export-items.
A cold start on a virtual clock
In the AWS Lambda Deep Dive lesson, you saw a cold start in the Init Duration of the REPORT line. A cold start's time has several parts, and each part has its own cause. These are example numbers from the Lab:
| Part of the cold start | Cause | Example in the Lab |
|---|---|---|
| Loading the package | the size of the code and its dependencies | 1 MB package: 30 ms, 60 MB package: 450 ms |
| Starting the runtime | the language and its engine | Node.js 22: 120 ms, Python 3.13: 100 ms, Java 21: 900 ms |
| VPC | used to create a network interface during the cold start | 0 ms (since 2019 it is created at deploy time) |
| Init code | the code outside the handler | create a client: 20 ms, fetch a secret + open a DB connection: 380 ms |
So Node.js with a 60 MB node_modules and heavy init needs 450 + 120 + 380 = 950 ms. A package bundled down to 1 MB with light init needs only 30 + 120 + 20 = 170 ms. Java with a 60 MB package and heavy init needs 1,730 ms.
A VPC (a private network in the cloud) could once add more than 10 seconds to a cold start. The reason was that the network interface (a virtual network card that connects the function to the VPC) was created during the cold start. Since 2019, AWS creates that network interface when the function is created or updated. So today a VPC barely matters.
Shrinking the cold start
- Make the package smaller. Bundle with esbuild (a tool that combines the code and its dependencies into one small file). From AWS SDK v3, import only the client you use:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb", not the oldaws-sdkpackage (v2). A client is an object for calling one AWS service, here DynamoDB. SDK v2 is no longer in the Node.js 18 and later runtimes, and it reached end of support in September 2025. - Pick a runtime that starts fast for latency-sensitive endpoints. Java can be helped by SnapStart: Lambda saves a snapshot (a saved copy of the state) of the environment after init, and later cold starts just restore that snapshot (also available for Python and .NET).
- Create clients once, outside the handler.
const db = new DynamoDBClient({})outside the handler runs once at init and is then reused on every warm start. If it is moved into the handler, the client is created again on every invocation (every time the function is called) and never reused. - Defer what is rarely used. A big library used by only one route is loaded with
import()inside that route, not at init.
Provisioned concurrency vs keep-warm
Provisioned concurrency prepares a number of environments that have already run their init before requests arrive. With 5 environments at 1 GB it costs about $54 a month (example price), and you pay even when there are no requests at all. In the Lab, 5 environments that are all provisioned run the export without a single cold start.
Keep-warm is an old trick: EventBridge calls the function every 5 minutes so its environment isn't removed. It's cheap, but one ping (that wake-up call) keeps only one environment. When 20 messages arrive at once, 1 environment is already warm and the other 19 still get a cold start. If latency must stay steady and the team is ready to pay, use provisioned concurrency.
Fan-out through a queue
notes-api's "Export all" button doesn't make 40 PDFs in one request. The API puts one message per note on the SQS queue export-notes, and the Lambda notes-export-worker takes those messages. Maximum concurrency on the SQS trigger decides how many environments work at the same time. That limit also protects the database from a flood of connections (the Connection Pooling lesson, Database track). These are the results in the Lab for 42 deliveries (see the next section), 400 ms per PDF and a 950 ms cold start:
| Maximum concurrency | Cold starts | Done in |
|---|---|---|
| 2 | 2 | 9.35 seconds |
| 5 | 5 | 4.55 seconds |
| 20 | 20 | 2.15 seconds |
| 5 + provisioned 5 | 0 | 3.6 seconds |
This pattern is called fan-out: one event is split into many small jobs that run in parallel. Its partner is fan-in: waiting for all of them to finish, and then combining the results. An example is counting finished items in a table and then building a ZIP. The classic example of fan-out and fan-in is a freshly uploaded video. Three Lambdas run in parallel for the thumbnail, the transcode to HLS (turning the video into a format for streaming) and the metadata. Once all three are done, the database is updated. There are other patterns too:
- pipeline: each step waits for the one before, for example S3 → validate → SQS → process.
- API composition: each HTTP route is one function.
Retries and idempotent handlers
An SQS standard queue guarantees at-least-once delivery: at least once, sometimes twice. A message is also delivered again if processing it fails, or if the work on it takes longer than its visibility timeout (how long a message stays hidden from other readers). Async events, such as those from S3, are retried by Lambda up to 2 times when the function errors. In the Lab, messages #7 and #23 arrive twice (attributes.ApproximateReceiveCount = "2" on the second delivery), so there are 42 deliveries for 40 notes.
An idempotent handler gives the same end result even when the same event is processed twice. The idea is the same as the Idempotency-Key in the Idempotency lesson (API track). This is the idempotent version of the notes-export-worker handler. event.Records holds the messages from SQS, here one per call because the batch size is 1:
// notes-export-worker, triggered by SQS export-notes (batch size 1)
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
import { makePdf, savePdf } from "./pdf.mjs";
// INIT: once per environment, reused on warm starts
const db = new DynamoDBClient({});
export const handler = async (event) => {
for (const record of event.Records) {
const { exportId, noteId } = JSON.parse(record.body);
const key = `exports/${exportId}/${noteId}.pdf`; // a fixed name: overwritten, never doubled
await savePdf(key, await makePdf(noteId));
try {
await db.send(new PutItemCommand({
TableName: "export-items",
Item: { pk: { S: `${exportId}#${noteId}` }, file: { S: key } },
ConditionExpression: "attribute_not_exists(pk)",
}));
} catch (err) {
if (err.name !== "ConditionalCheckFailedException") throw err;
console.log(`duplicate skipped: ${record.messageId}`);
}
}
};
- The PDF key is built from
exportIdandnoteId. So the second delivery overwrites the same file instead of making a new one. ConditionExpression: "attribute_not_exists(pk)"means "write only if thispk(row key) doesn't exist yet". So DynamoDB refuses the second item (row) withConditionalCheckFailedException. That error is caught and skipped, and any other error is thrown again so SQS retries.- The non-idempotent version gives the file and the item random names (
crypto.randomUUID()). In the Lab the result is 42 PDFs and 42 rows for 40 notes. The version above stays at 40. - DynamoDB is used here because it communicates over HTTP per request, so it holds no open connection the way Postgres does.
When not to go serverless
- Long processes: Lambda stops after 30 minutes (1,800 seconds) at most. Encoding video for hours fits a container better.
- Connections that stay open and state in memory: for example a multiplayer game server holding WebSockets (connections that stay open between the browser and the server), or other stateful applications (ones that keep state in memory).
- High, steady traffic all day: paying per request can cost more than a server that is always on.
- Latency that must always be low, when the team doesn't want to pay for provisioned concurrency.
⚠️ Duplicate PDFs, exhausted connections, and cold starts that still come
- Creating the client inside the handler. The client and its connection are created again on every invocation. Create it once outside the handler.
- Relying on keep-warm for a spike. One ping keeps only one environment, so a spike still gets cold starts.
- A non-idempotent handler behind SQS. A message delivered twice becomes a duplicate PDF, a duplicate row or a duplicate email.
- Fan-out without a limit. A concurrency of 1,000 in front of Postgres uses up its connections. Set maximum concurrency.
TL;DR: A cold start is the wait for a new copy of the function to start. Its time = loading the package (the code and its dependencies) + starting the runtime (Node.js and Python start fast, Java is slow without SnapStart, which restores a copy saved after init) + the init code (the code outside the handler). Since 2019 a VPC (a private network in the cloud) adds almost nothing. In the Lab, 950 ms becomes 170 ms with a 1 MB package and light init. Import only the clients you use from AWS SDK v3 (v2 has reached end of support), and create clients (objects that call AWS services) such as new DynamoDBClient({}) once outside the handler. Inside the handler, the client is created again on every invocation (every time the function is called). Provisioned concurrency prepares environments (copies of the function) that are already started, for a fixed cost. Keep-warm (a regular ping) keeps only one environment, so a spike of 20 messages still means 19 cold starts. Fan-out through SQS (AWS's message queue) with maximum concurrency splits work in parallel without flooding the database. Fan-in combines the results, for example a video's thumbnail, HLS and metadata made in parallel. SQS and async events can deliver the same event twice, so handlers must be idempotent (same end result when run twice): fixed result names and conditional writes (write only if the data isn't there yet). Serverless doesn't fit processes over 30 minutes, stateful WebSocket and game servers (ones that keep state in memory), or high steady traffic.
⚡ A cold start has three parts
Meaning: A cold start is the wait while a new copy of the function (a new environment) starts. A cold start = loading the package (the code and its dependencies) + starting the runtime + the init code (the code outside the handler). In the Lab, a 60 MB package with heavy init needs 950 ms, while a 1 MB package with light init needs only 170 ms. Create clients (objects for calling AWS services) once outside the handler, so every warm start (a started copy used again) reuses them.
⚡ Fan-out through a queue
Guess first: a video has just been uploaded and needs a thumbnail, an HLS transcode (a format for streaming) and its metadata. None of the three depends on the others. Choose: fan-out (the work is split and runs in parallel) or a pipeline (each step waits for the one before)?
Fan-out: three Lambdas run in parallel, and the database is updated once all three are done (fan-in). A pipeline fits when each step waits for the one before.
Meaning: In notes-api, each note becomes one message on the SQS queue. Maximum concurrency on the SQS trigger decides how many environments work on those messages at the same time, and also protects the database from a flood of connections.
⚡ An idempotent handler
Write:
const key = `exports/${exportId}/${noteId}.pdf`; // a fixed name: overwritten, never doubled
await savePdf(key, await makePdf(noteId));
try {
await db.send(new PutItemCommand({
TableName: "export-items",
Item: { pk: { S: `${exportId}#${noteId}` }, file: { S: key } },
ConditionExpression: "attribute_not_exists(pk)",
}));
} catch (err) {
if (err.name !== "ConditionalCheckFailedException") throw err;
console.log(`duplicate skipped: ${record.messageId}`);
}
Meaning: SQS delivers each message at-least-once: at least once, sometimes twice. This handler gives the PDF a fixed name from exportId and noteId. ConditionExpression makes DynamoDB (db is its client) refuse a row in the export-items table whose pk (row key) already exists. So a message that arrives twice makes no duplicate PDF or row: in the Lab, 40 notes still give 40 PDFs, not 42.