Serverless Functions — DevOps

Serverless = the provider manages the servers, and you only write a function handler(event) that returns { statusCode, body }. The provider starts an instance…

notes-api's VPS is billed by the hour, all day long. From midnight until dawn only a few requests come in, but the bill keeps running. When it gets busy, that same one server has to carry everything.

Serverless reverses that. The name doesn't mean there's no server: the server is still there, but the provider manages all of it. You only write a function, and the provider runs it on every request, adds copies when it's busy, and shuts them down when it's quiet. Remember the on-call cook from the Cloud Computing Basics lesson, who only comes when there's an order. Here the cook is an instance (a running copy of the function), and an order is a request. The first order after a quiet period has to wait for the cook to arrive and light the stove (a cold start). If they're still in the kitchen from the previous order, they start cooking right away (a warm start). They're paid per plate and per minute of cooking (per request and per duration), don't remember yesterday's order (stateless), and have a time limit per order (a timeout). When there are suddenly many orders, many cooks arrive at once, but only a limited number of people can be in your pantry (the database) at the same time (the database's connection limit).

From a route to a function

The GET /notes/:id route of notes-api moves into a function on AWS Lambda, Amazon's serverless service. In this model there's no app.listen: the provider calls handler for every request.

// get-note.mjs (AWS Lambda, Node 24)
import pg from "pg";

// Runs once per instance, on a cold start
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });
let calls = 0;

export const handler = async (event) => {
  calls += 1;
  const { rows } = await pool.query("SELECT id, title, content FROM notes WHERE id = $1", [event.pathParameters.id]);
  if (rows.length === 0) {
    return { statusCode: 404, body: JSON.stringify({ error: "Note not found" }) };
  }
  return { statusCode: 200, body: JSON.stringify(rows[0]) };
};

Before you go on, guess. Every request to get-note adds 1 to calls, and five requests arrive one after another, a few seconds apart. What is calls on the fifth request? If a sixth request only arrives after 15 quiet minutes, what is it then? The answer is in the Stateless section below.

Cold starts and warm starts

In the Lab, the times follow an example model (not exact measurements from any provider): starting the Node runtime 250 ms, opening the Postgres connection 50 ms, the query 20 ms, the rest of the handler's work 5 ms. So the handler's work on an instance that is already running is 20 + 5 = 25 ms:

Request What happens Time
1st cold: a new instance, the runtime starts, the connection opens, then the handler 250 + 50 + 25 = 325 ms
2nd to 5th warm: the same instance, straight to the handler 25 ms
6th, after 15 quiet minutes the provider has thrown the instance away, cold again 325 ms
5 requests at once, when 1 warm instance already exists one Lambda instance serves only one request at a time, so 4 new instances 1 × 25 ms, 4 × 325 ms

The provider throws away instances that sit idle for a long time (in the Lab after 10 minutes; real providers promise no exact number). Ways to reduce cold starts are covered in the lesson Serverless Patterns & Cold Start. The table above is about the handler model (no app.listen), which AWS now calls Lambda Event Functions. Lambda Web Functions (as of November 2026) are different: you deploy a normal HTTP server with app.listen. One environment (AWS's word for an instance) serves several requests at once: at most 64 by default, and this limit can be raised to 128.

Stateless: instance memory can't be relied on

Five requests in a row land on the same instance, so calls on the fifth request is 5. The sixth request, after 15 quiet minutes, gets a new instance, so the value is back to 1. If five requests arrive at the same time, they spread over several instances, and each instance has its own calls.

So variables in memory, caches in memory and files in /tmp (the instance's temporary folder) are only a bonus that can vanish at any time. Data that must last goes in a database, Redis or object storage.

Timeouts

Every function has a time limit. On AWS Lambda the default is 3 seconds, the maximum 30 minutes. Past that, the run is stopped, and the log prints Task timed out after 3.00 seconds. In the Lab, a 4 second slow query always hits this limit. Long work, such as building a monthly report or processing a video, is split into parts, or sent to a queue and handled by a worker.

Functions and the database

The connection is opened outside the handler, so warm requests reuse the same connection. If it's opened inside the handler, every request pays another 50 ms for the handshake (the steps that open a connection): 75 ms instead of 25 ms.

The next problem is the number of connections. Each instance holds its own connection, and the provider can start hundreds of instances at once. In the Lab, 120 requests at once mean 120 instances and 120 connections. But Postgres only accepts 100 connections (max_connections), so 20 requests fail with FATAL: sorry, too many clients already. The fix is a pooler between the functions and the database, such as RDS Proxy or PgBouncer. A pooler shares a few real connections among many instances. The details are in the lesson Connection Pooling (Database track).

Paying for what you use

Serverless uses a pay-per-use model: you pay for the number of executions (requests) and their duration. The duration is multiplied by the memory you picked, and counted in GB-seconds (1 GB of memory for 1 second). With no requests, the bill is close to zero, because idle instances are thrown away. That's unlike a VPS, which is billed by the hour even when it's quiet.

A good fit for: API endpoints with traffic that rises and falls, webhooks (automatic requests from another service when something happens, such as a payment coming in), cron jobs, and processing uploaded images. A poor fit for: work longer than the timeout, connections that must stay open such as WebSockets, and high, steady traffic all day, which is usually cheaper on a normal server. The lessons AWS Lambda Deep Dive, Cloudflare Workers & Edge Computing, and Vercel Edge Functions & Middleware cover Lambda, Cloudflare Workers and Vercel in more depth.

A miniature Lambda runtime

In the exercise, simulateLambda(handler, event) imitates the runtime: call handler(event), then return { statusCode, body, executionTime: "<1ms" }. If the handler throws an error, catch it with try...catch and return { statusCode: 500, body: error.message, executionTime: "<1ms" }, just as a runtime answers 500 when your function crashes.

⚠️ What makes a function fail or run slowly

TL;DR: Serverless = the provider manages the servers, and you only write a function handler(event) that returns { statusCode, body }. The provider starts an instance (a running copy of the function) when a request comes in. The first request pays a cold start (waiting for a new instance to start, 325 ms in the Lab), and later requests on the same instance are warm (25 ms). Instances that sit idle are thrown away, so the next request is cold again. In the handler model, one instance serves one request at a time, so simultaneous requests start many instances. A function is stateless: memory and /tmp can vanish at any time. There's a timeout (a time limit; AWS Lambda's default is 3 seconds, the maximum 30 minutes). Open the database connection outside the handler, and use a pooler (a middleman that shares a few connections among many instances) so max_connections (Postgres's connection limit) isn't used up. Billing is pay-per-use: the number of executions and their duration.

⚡ From a route to a function

Write:

export const handler = async (event) => {
  const { rows } = await pool.query("SELECT id, title, content FROM notes WHERE id = $1", [event.pathParameters.id]);
  return { statusCode: 200, body: JSON.stringify(rows[0]) };
};

Meaning: With serverless, the server is still there, but the provider (here AWS Lambda) manages it. You only write a function: there's no app.listen, because the provider calls handler for every request. event holds the request, and event.pathParameters.id is the :id in the URL, the id of the note asked for. pool is the database connection, made outside this function. The result is an object { statusCode, body }, and body must be a string, hence JSON.stringify.

⚡ Cold starts and warm starts

Write:

let calls = 0;

export const handler = async (event) => {
  calls += 1;
};
Guess first: let calls = 0 outside the handler runs once per instance (a running copy of the function). The provider reuses the same instance while requests keep coming, and throws it away after a long quiet period (10 minutes in the Lab). Five requests arrive one after another: what is calls on the fifth? And on a sixth that arrives after 15 quiet minutes?

On the fifth it's 5, because all five land on the same instance. The sixth gets a new instance, so it's back to 1.

Meaning: The first request on a new instance pays a cold start, the time it takes to start the instance (325 ms in the Lab). Later requests on the same instance are warm: straight to the handler (25 ms). Instance memory can vanish at any time, so data that must last goes in a database or Redis.

⚡ There's a time limit

Write:

Task timed out after 3.00 seconds

Meaning: This is the log message when a function passes its timeout (its time limit). Lambda's default is 3 seconds, the maximum 30 minutes. Long work is split into parts, or sent to a queue and handled by a worker (a program that runs tasks in the background).

⚡ The connection outside the handler

Write:

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });

Meaning: This line is written outside the handler, so it runs once per instance, and its connection is reused by warm requests. Each instance holds its own connection. So when many instances start, use a pooler (a middleman that shares a few real connections among many instances) so max_connections (Postgres's connection limit) isn't used up. Serverless billing is per execution (request) and its duration.

What you will learn