AWS Lambda Deep Dive — DevOps

Lambda (AWS's function service) calls handler(event, context) once per request, and charges per request plus GB × seconds (memory × duration), with no cost…

Every working hour, the PDF export feature pushes web-1's CPU to its limit, and the ordinary note pages slow down with it. At night that same CPU sits idle. Renting a bigger server just for a few busy hours is wasteful.

AWS Lambda offers another way. It is Amazon's FaaS service: you hand over one function. AWS starts the servers, runs the function whenever an event arrives (something that calls it, such as an incoming request), and adds copies of it when traffic grows. You pay per request and per millisecond while the function runs, so quiet hours cost nothing for idle time. Remember the on-call cook from the Cloud Computing Basics lesson. Here a cook is a running copy of the function, and an order is a request. On arrival, the cook first has to prepare the table, sharpen the knives and light the stove (a cold start). After that, each order is cooked right away. Cooking one order is the job of the handler, the function that is called for each request. If the cook is still in the kitchen when the next order comes in, the setup isn't repeated (a warm start). When orders arrive at the same time, the agency (here AWS) sends extra cooks, but only up to the limit in the contract. The number of cooks working at the same time is the concurrency. Every cook holds a stopwatch with a time limit per order (the timeout). The size of the table is the memory: a bigger table costs more per minute, but the cooking is faster.

The handler: an event comes in, a response goes out

The Serverless Functions lesson already introduced the handler's shape. Now we use it for real. notes-api's PDF export uses a lot of CPU, and it is busy only during working hours. So the route POST /notes/{id}/export moves from web-1 to a Lambda named notes-export. It runs Node.js 22 in the region eu-west-2 (London), the same region as the notes-attachments bucket from the Object Storage (S3/R2/GCS) lesson. This is its code:

// index.mjs (handler: index.handler)
import pg from "pg";
import { makePdf } from "./pdf.mjs";

// INIT: runs once per execution environment
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });

export const handler = async (event, context) => {
  const id = Number(event.pathParameters?.id);
  if (!Number.isInteger(id)) {
    return { statusCode: 400, body: JSON.stringify({ error: "id must be a number" }) };
  }
  const { rows } = await pool.query("SELECT title, content FROM notes WHERE id = $1", [id]);
  if (rows.length === 0) {
    return { statusCode: 404, body: JSON.stringify({ error: "note not found" }) };
  }
  console.log(`export ${id}, time left ${context.getRemainingTimeInMillis()} ms`);
  const pdf = await makePdf(rows[0]); // the heaviest CPU work
  return {
    statusCode: 200,
    headers: { "Content-Type": "application/pdf" },
    isBase64Encoded: true,
    body: pdf.toString("base64"),
  };
};

The event from API Gateway

API Gateway is the AWS service that takes HTTP requests from the internet and passes them to Lambda as a JSON event. API Gateway comes in several kinds. In the HTTP API kind, the event uses payload format (the shape of the event's contents) 2.0. The event for POST /notes/42/export looks roughly like this (trimmed):

{
  "version": "2.0",
  "routeKey": "POST /notes/{id}/export",
  "rawPath": "/notes/42/export",
  "headers": { "content-type": "application/json", "authorization": "Bearer eyJhbGciOi..." },
  "pathParameters": { "id": "42" },
  "requestContext": {
    "http": { "method": "POST", "path": "/notes/42/export", "sourceIp": "198.51.100.7" },
    "requestId": "Ab3xQjYzSQ0EJXw="
  },
  "body": "{\"size\":\"A4\"}",
  "isBase64Encoded": false
}

The method sits in event.requestContext.http.method, and the {id} from the route lands in event.pathParameters.id as a string. body is a string too, so it needs JSON.parse(event.body). The REST API, an older kind of API Gateway, uses format 1.0, with event.httpMethod and event.path. So check which format you get before you read its fields.

There are other options for an HTTP endpoint. This table follows the section "Select a method to invoke" in the Lambda documentation:

Approach When to pick it
API Gateway HTTP API used in this lesson: many routes, a custom domain (your own domain name), authorizers (token checks), and throttling (limiting the number of requests) per route
Function URL one function needs just one endpoint, for example a webhook. The URL is built into Lambda (https://<url-id>.lambda-url.<region>.on.aws), has no extra cost, and its event uses format 2.0. Its auth (how the caller is checked) is only AWS_IAM (the request must be signed with AWS credentials) or NONE (open to anyone)

Init once, the handler many times

Lambda runs your function inside an execution environment (what the Serverless Functions lesson called an instance): a small sandbox (a separate space) with the Node.js runtime, your code and its own memory. In this handler model (AWS now calls it Lambda Event Functions), one environment works on one request at a time. Lambda Web Functions, which run a normal HTTP server, serve several requests at once per environment (64 by default, at most 128).

What happens What runs Example in the Lab (512 MB)
Cold start: no environment is free init (start the runtime, import, new pg.Pool), then the handler Init Duration 412.08 ms, then Duration 926.36 ms
Warm start: an environment is free the handler only Duration 862.71 ms

The first request in a new environment also opens a connection to Postgres (64 ms). Because pool is created outside the handler, the next requests in the same environment reuse that connection. If you move new pg.Pool() into the handler, every request opens a new connection, while the old ones stay open, unused, until their old pool closes them by itself. AWS removes an environment that sits idle for long. How long, AWS doesn't promise; in the Lab, 15 minutes. If you change the code or a setting such as memory, AWS also creates new environments, so the next request is a cold start.

For an endpoint that must never hit a cold start, Provisioned Concurrency prepares a number of environments that have already run init before requests arrive. It costs extra, and it is billed for as long as it is turned on, even with no requests. The causes of cold starts and how to reduce them are in the Serverless Patterns & Cold Start lesson.

Concurrency and throttling

Concurrency is the number of environments working on a request at the same moment. The rough sum: requests per second × average duration in seconds. For example, 20 requests per second × 0.5 seconds = about 10 environments at once.

The default concurrency quota is usually 1,000 per region, shared by all functions in your account (new accounts may get less). Reserved concurrency gives one function its own limit. Above that limit, Lambda rejects the request with a TooManyRequestsException error (status 429, Rate Exceeded.). This rejection is called throttling. So with a limit of 2 and five requests at once, two are worked on (two cold starts) and three are rejected with 429. A rejected request never runs your code, so it leaves no logs. A synchronous caller such as API Gateway gets that error. Async events (whose answer nobody waits for), for example from S3 or EventBridge, are kept and retried by Lambda for up to 6 hours.

Why limit it on purpose? Every environment holds its own Postgres connection. 1,000 environments means 1,000 connections, while Postgres's default max_connections is only 100. A concurrency limit plus max: 1 in the pool keeps the database alive. The basics are in the Connection Pooling lesson (Database track). For heavy traffic, AWS has RDS Proxy, which acts as the pool between Lambda and the database.

Memory, CPU and timeout

Memory can be set from 128 MB to 10,240 MB, and CPU grows in proportion to memory (about 1,769 MB = one full vCPU, one virtual processor core). The timeout defaults to 3 seconds, at most 1,800 seconds (30 minutes). Past the timeout, the request is stopped with a message such as Task timed out after 3.00 seconds (for a 3-second timeout). These are example numbers from the Lab for a warm start of notes-export:

Memory Time it needs Result with a 3-second timeout Cost per 1 million requests
128 MB 3,412.71 ms stopped at 3,000 ms (fails)
512 MB 862.71 ms 200 $7.39
1,024 MB 437.71 ms 200 $7.50

Going from 512 MB to 1,024 MB makes the PDF twice as fast, yet it costs almost the same. The reason: the price is counted in GB × seconds, so twice the memory and half the duration. At 128 MB, raising the timeout to 10 seconds does remove the error, but the user waits 3.4 seconds. So the right fix here is more memory.

Reading the REPORT line in CloudWatch

Every console.log and every log from Lambda goes to CloudWatch Logs (AWS's log service), in the log group /aws/lambda/notes-export. Each request is wrapped in three lines from Lambda itself: START before it, then END and REPORT after it. On a cold start, there is also INIT_START at the very top. This is a cold start at 512 MB (example numbers):

INIT_START Runtime Version: nodejs:22.v51	Runtime Version ARN: arn:aws:lambda:eu-west-2::runtime:7c1e4b0d9a3f52e8c6b1d0a9f8e7d6c5b4a39281706f5e4d3c2b1a0f9e8d7c6b
START RequestId: 8f5a1c2e-4b7d-4e19-9c3a-000000000001 Version: $LATEST
2026-10-09T02:00:00.488Z	8f5a1c2e-4b7d-4e19-9c3a-000000000001	INFO	export 42, time left 2924 ms
END RequestId: 8f5a1c2e-4b7d-4e19-9c3a-000000000001
REPORT RequestId: 8f5a1c2e-4b7d-4e19-9c3a-000000000001	Duration: 926.36 ms	Billed Duration: 1339 ms	Memory Size: 512 MB	Max Memory Used: 97 MB	Init Duration: 412.08 ms

Cost = number of requests × $0.20 per million + GB × seconds × $0.0000166667 (example prices from the us-east-1 region, for x86 processors; check the pricing page for your region). A warm start at 512 MB is billed 863 ms: 0.5 GB × 0.863 seconds × $0.0000166667 ≈ $0.0000072 per request, plus $0.0000002 for the request itself. A million requests come to about $7.39.

Triggers other than HTTP

API Gateway is just one of many triggers, the event sources that call a Lambda:

Code size is limited too. A zip uploaded directly can be at most 50 MB, and 250 MB once unzipped, layers included (a layer is a package of libraries that several functions can share). Code packaged as a container image can be up to 10 GB.

⚠️ Mistakes that only show up in production

TL;DR: Lambda (AWS's function service) calls handler(event, context) once per request, and charges per request plus GB × seconds (memory × duration), with no cost while idle. Code outside the handler (init) runs once per execution environment (a running copy of the function) on a cold start, and its result is reused on warm starts. So create database connections there, with a small pool. In Event Functions (the handler model), one environment works on one request at a time, while Web Functions (which run a normal HTTP server) serve several at once. Concurrency (the number of environments working at the same time) ≈ requests per second × duration. The default quota is usually 1,000 per region, and above the limit, Lambda rejects with 429 TooManyRequestsException (throttling). Memory from 128 MB to 10,240 MB decides the CPU. The timeout (the time limit per request) defaults to 3 seconds and is at most 30 minutes. The REPORT line (the summary of each request) in CloudWatch (AWS's log service) holds Duration, Billed Duration, Memory Size, Max Memory Used, and Init Duration, which only appears on a cold start. Triggers besides API Gateway (the way in for HTTP requests): S3 Event, SQS, EventBridge, DynamoDB Streams. Provisioned Concurrency keeps environments warm at an extra cost.

⚡ Init once, the handler many times

Write:

// INIT: runs once per execution environment
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });

export const handler = async (event, context) => {
  const { rows } = await pool.query("SELECT title, content FROM notes WHERE id = $1", [id]);
  // ...
};
Guess first: new pg.Pool() creates the connection to Postgres. You move this line into the handler, the function Lambda calls for each request. What happens?

Every request opens a new connection to Postgres, and the old ones stay open, unused, until their old pool closes them by itself. Outside the handler, the connection is reused by the next requests in the same environment (a running copy of the function), on warm starts.

Meaning: Code outside the handler (init) runs once per execution environment, on a cold start (when a new environment starts). In this handler model, one environment works on one request at a time.

⚡ The concurrency limit and 429

Meaning: Reserved concurrency gives one function a limit on how many environments may work at the same time. Above that limit, Lambda rejects the request with TooManyRequestsException (429), which is called throttling. With a limit of 2 and five requests at once, two are worked on and three are rejected. A rejected request never runs your code, so it leaves no logs.

⚡ Memory decides the CPU

Meaning: In Lambda, CPU grows in proportion to the memory you set. So if the work is heavy on CPU, raise the memory, not the timeout (the time limit per request). For example, this lesson's PDF export function is twice as fast at 1,024 MB as at 512 MB, for almost the same cost, because you pay for GB × seconds (memory × duration). On the REPORT line (the summary of each request in the CloudWatch log), Init Duration only appears on a cold start.

⚡ Triggers other than HTTP

Guess first: every time a profile photo is uploaded, its thumbnail must be made automatically. What triggers the Lambda?

An S3 Event: a new object lands in the bucket, and a Lambda makes its thumbnail. SQS is for queues, EventBridge for cron schedules, DynamoDB Streams for table data that changes.

Meaning: API Gateway (the service that passes HTTP requests to Lambda) is just one of many triggers, the event sources that call a Lambda.

What you will learn