Lesson 254 of 296
Lambda and API Gateway
What you will learn
- What serverless means
- How Lambda works: handlers, events, execution environments
- Cold starts, timeouts, concurrency and limits
- API Gateway in front of Lambda
- A complete TypeScript handler
- When Lambda is and is not a good fit
On this page
Serverless
Serverless means you run code without managing servers: the platform provisions, scales (including to zero) and patches, and you pay per request and execution time. Servers still exist; they are just not your job.
AWS Lambda
Lambda runs a function in response to an event: an HTTP request through API Gateway, a file uploaded to S3, a message in SQS, a schedule, a DynamoDB stream record, and many more.
- You write a handler function; Lambda calls it with the event and a context object.
- Runtimes: at the time of writing the supported Node.js runtimes were
nodejs22.xandnodejs24.x, withnodejs26.xlisted as launching in November 2026 (check the AWS runtime page; old runtimes are deprecated on a schedule). - Memory is configurable from 128 MB to 10,240 MB, and CPU scales with memory.
- Timeout: up to 15 minutes per invocation.
- Concurrency: each concurrent request uses a separate execution environment; Lambda adds environments as traffic grows, up to account and function limits. Reserved concurrency caps a function (protecting a database behind it); provisioned concurrency keeps environments warm.
- Pricing: per request and per GB-second of execution, plus a free tier.
Execution environments and cold starts
- Cold start: for a new environment, Lambda downloads your code, starts the runtime and runs your initialisation code (everything outside the handler). This adds latency, from roughly a hundred milliseconds to over a second depending on package size and initialisation work.
- Warm invocations: the environment is reused for later requests; module-level variables (database clients, SDK clients, configuration) persist between invocations.
So: create clients outside the handler (reused while warm), keep bundles small (bundle and tree-shake with esbuild, import only the SDK clients you need), avoid heavy start-up work, and use provisioned concurrency or SnapStart where cold starts matter.
A TypeScript handler for API Gateway
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { z } from "zod";
const CreateNoteSchema = z.object({ title: z.string().trim().min(1).max(200) });
const notes = new Map<string, { id: string; title: string }>();
function json(statusCode: number, body: unknown): APIGatewayProxyResultV2 {
return { statusCode, headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
}
export async function handler(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const method = event.requestContext.http.method;
if (method === "POST" && event.rawPath === "/notes") {
let raw: unknown;
try {
raw = JSON.parse(event.isBase64Encoded ? Buffer.from(event.body ?? "", "base64").toString("utf8") : event.body ?? "");
} catch {
return json(400, { error: "Body must be JSON" });
}
const parsed = CreateNoteSchema.safeParse(raw);
if (!parsed.success) return json(422, { error: "Title is required (max 200 characters)" });
const note = { id: crypto.randomUUID(), title: parsed.data.title };
notes.set(note.id, note);
return json(201, note);
}
if (method === "GET" && event.rawPath.startsWith("/notes/")) {
const note = notes.get(event.rawPath.slice("/notes/".length));
return note ? json(200, note) : json(404, { error: "Not found" });
}
return json(404, { error: "Route not found" });
}APIGatewayProxyEventV2is the event shape for HTTP APIs (payload format 2.0); types come from the@types/aws-lambdapackage.- The in-memory
Mapis only for the example: it lives in one execution environment and disappears when it is recycled. Lambda functions must be stateless; real data goes in DynamoDB or RDS. - Frameworks such as Middy add middleware (validation, error handling) to handlers; you can also run Express or Fastify inside Lambda with an adapter, at some cost in cold start.
API Gateway
Amazon API Gateway is a managed front door for APIs:
| Type | Notes |
|---|---|
| HTTP API | Simpler, cheaper, lower latency; JWT authorisers, CORS. The usual choice for Lambda-backed REST-style APIs |
| REST API | More features: API keys and usage plans, request validation, caching, AWS WAF integration, transformations |
| WebSocket API | Persistent connections routed to Lambda (chat, notifications) |
It provides routing to Lambda or other back ends, authorisation (JWT from Cognito or any OIDC provider, or custom Lambda authorisers), throttling, CORS, custom domains with TLS certificates, and logging. Lambda function URLs are a simpler alternative (an HTTPS endpoint directly on a function) when you do not need API Gateway's features.
Other common triggers
- SQS: Lambda polls the queue and invokes your function with batches of messages (Lesson 255).
- S3 events: process uploads (Lesson 242).
- EventBridge Scheduler / rules: scheduled jobs and event routing.
- DynamoDB Streams: react to data changes (Lesson 229).
When Lambda fits
| Good fit | Poor fit |
|---|---|
| Spiky or unpredictable traffic, scaling to zero | Steady high traffic (containers are usually cheaper) |
| Event processing: uploads, queues, webhooks, schedules | Jobs longer than 15 minutes |
| Small APIs and glue code | Long-lived connections held by your code, heavy in-memory state |
| Teams wanting minimal operations | Very latency-sensitive paths that cannot tolerate cold starts |
Watch out for database connections: thousands of concurrent Lambdas can exhaust PostgreSQL connections; use RDS Proxy, DynamoDB, or reserved concurrency.
How to say it in an interview
"Lambda runs stateless functions in response to events such as API Gateway requests, S3 uploads, SQS messages and schedules, scaling automatically and charging per request and duration, with up to 15 minutes per run and CPU proportional to memory. A cold start initialises a new execution environment, so I create SDK and database clients outside the handler, keep bundles small and use provisioned concurrency when latency matters. API Gateway HTTP APIs route requests to Lambda with JWT authorisation, throttling and CORS. Lambda suits spiky and event-driven work; for steady heavy traffic or long-running processes I prefer containers, and I protect databases with RDS Proxy or reserved concurrency."
Key words
| Word | Meaning |
|---|---|
| Serverless | Running code without managing servers |
| Handler | The function Lambda calls with each event |
| Execution environment | The isolated runtime instance running your function |
| Cold start | Extra latency when a new environment starts |
| Concurrency | Number of invocations running at the same time |
| Reserved / provisioned concurrency | A cap / pre-warmed environments |
| API Gateway | AWS's managed API front door |
| HTTP API vs REST API | Simpler and cheaper vs more features |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.