JS-260 · Lesson 5 of 12 · 26 min
Serverless functions
▶ Video coming soon A video version of this lesson is on the way.
On Tuesday, October 17, Mira starts with a job that does not fit anywhere yet. The payment widget on the Donate page, from the outside provider GiveRight, sends a webhook for every donation: an HTTP POST to an address the Food Hub chooses, describing the gift. Today that address is a mailbox, and Dev copies each email into a spreadsheet so the office can send receipts. In December, when most of the year's donations arrive and Theo is away, that is a lot of copying. The job is small, it runs only when someone donates, and it must keep working if Theo's server is down for maintenance. Gareth suggests trying a serverless function.
What serverless means
Serverless does not mean there are no servers. It means the team does not manage them. A function as a service platform runs a piece of code, a function, in response to an event such as an HTTP request, a message on a queue or a schedule. The platform starts copies of the function when events arrive, runs as many in parallel as are needed, stops them when they are idle, and charges for the time and memory actually used. There is no server to patch, no process to keep running and no capacity to plan.
| Long-running service (partner service) | Serverless function (donation webhook) | |
|---|---|---|
| Runs | All the time, waiting for requests | Only when an event arrives |
| Scales | One process; more needs planning | The platform runs more copies automatically |
| State in memory | Kept between requests | May be lost at any time; copies share nothing |
| Start-up cost | Once, at deployment | On each cold start |
| Limits | Whatever the server allows | A maximum run time, memory and payload size per invocation |
| Paid for | The server, whether busy or idle | Each invocation and its duration |
| Operated by | The team (Theo) | The platform provider |
Serverless suits work that is event-driven, short and bursty: webhooks, image resizing when a file is uploaded, scheduled clean-ups, small APIs with uneven traffic. It suits long-lived connections, such as the order board's server-sent events stream from JS-240, poorly, and it is awkward for code that needs many database connections, because hundreds of copies starting at once can exhaust a database's connection limit. The partner service will stay a long-running service; the donation webhook is a good first function.
Platforms and handler shapes
Every platform has its own way of calling a function, but there are two main styles. AWS Lambda, the oldest large platform, calls an exported handler with an event object and expects an object back; for an HTTP request, the event holds the method, headers and body, and the result holds a statusCode, headers and body. Lambda's managed Node.js runtimes follow Node's LTS releases: in October 2026 its supported runtimes were nodejs22.x and nodejs24.x, with Node.js 26 in preview and due for general release in November 2026. Under Lambda's policy, a runtime is deprecated soon after its Node.js line reaches end of life.
Cloudflare Workers and several other edge platforms instead use the web's own Request and Response objects: the function exports a fetch method that receives a Request and returns a Response, exactly like a service worker from JS-250. Workers run in lightweight V8 isolates rather than separate containers, so they start in a few milliseconds and run in many locations, at the cost of offering a browser-like set of APIs rather than all of Node's. Netlify, Vercel, Google Cloud and Azure offer functions in one or both styles.
// Two shapes for the same tiny function.
// AWS Lambda style: an event object in, a plain object out.
export const handler = async (event) => {
const name = event.queryStringParameters?.name ?? 'volunteer';
return { statusCode: 200, headers: { 'content-type': 'text/plain' }, body: `Hello, ${name}` };
};
// Web-standard style (Cloudflare Workers and others): a Request in, a Response out.
export default {
async fetch(request, env, ctx) {
const name = new URL(request.url).searchParams.get('name') ?? 'volunteer';
return new Response(`Hello, ${name}`, { headers: { 'content-type': 'text/plain' } });
},
};What this code does
Both functions read a name from the query string and return a short text response. The Lambda handler receives the parts of the request already separated in an event object and returns the response as a plain object. The fetch handler uses the same Request, URL and Response classes as browsers, which makes it portable between platforms that follow web standards.
Because the web-standard style is portable, Mira writes the webhook's logic as a function from a Request to a Response and adds a few lines of adapter for whichever platform runs it. The adapter turns the platform's event into a Request and the Response back into the platform's result. If the studio changes provider, only the adapter changes.
// The webhook's logic as Request -> Response, with an adapter for Lambda-style events.
async function app(request) {
if (request.method !== 'POST') return new Response('method not allowed', { status: 405 });
const donation = await request.json();
return new Response(JSON.stringify({ recorded: donation.id }), { status: 200, headers: { 'content-type': 'application/json' } });
}
async function lambdaAdapter(event) {
const request = new Request(`https://hooks.example${event.rawPath}`, {
method: event.requestContext.http.method, headers: event.headers,
body: event.requestContext.http.method === 'GET' ? undefined : event.body,
});
const response = await app(request);
return { statusCode: response.status, headers: Object.fromEntries(response.headers), body: await response.text() };
}
const post = { rawPath: '/giveright', headers: { 'content-type': 'application/json' }, body: '{"id":"evt_7Q2K9","amount":5000}', requestContext: { http: { method: 'POST' } } };
const get = { rawPath: '/giveright', headers: {}, requestContext: { http: { method: 'GET' } } };
console.log(await lambdaAdapter(post));
console.log(await lambdaAdapter(get));{ statusCode: 200, headers: { "content-type": "application/json" }, body: "{\"recorded\":\"evt_7Q2K9\"}" }
{ statusCode: 405, headers: { "content-type": "text/plain;charset=UTF-8" }, body: "method not allowed" }What this code does
The app function knows nothing about Lambda: it reads a Request and returns a Response. The adapter builds a Request from the event's path, method, headers and body, calls the app, and turns the Response's status, headers and text into the object Lambda expects. Running both through the same code shows the POST being recorded and the GET refused with 405.
Cold starts
When an event arrives and no copy of the function is ready, the platform must create an execution environment: start a container or isolate, load the runtime, load the code and run everything at the top level of the module. This is a cold start, and on container-based platforms it typically adds a few hundred milliseconds or more, depending on the runtime and the size of the code. Afterwards, the environment is kept for a while and reused for later events, which are warm and skip all of that. Code at the top level of the module runs once per cold start, so that is where expensive set-up, such as reading configuration or creating an HTTP client, belongs.
// Simulate cold and warm starts with a fake clock (times in milliseconds).
const INIT_MS = 420, HANDLER_MS = 35, IDLE_LIMIT_MS = 10 * 60 * 1000;
let envReadyUntil = -1, busyUntil = -1;
function invoke(at) {
if (at < busyUntil) return { at, latency: INIT_MS + HANDLER_MS, kind: 'cold (env busy)' }; // a second copy is needed
const warm = at <= envReadyUntil;
const latency = (warm ? 0 : INIT_MS) + HANDLER_MS;
busyUntil = at + latency;
envReadyUntil = busyUntil + IDLE_LIMIT_MS;
return { at, latency, kind: warm ? 'warm' : 'cold' };
}
const minute = 60 * 1000;
const arrivals = [0, 2 * minute, 2 * minute + 10, 5 * minute, 40 * minute, 41 * minute];
for (const r of arrivals.map(invoke)) {
console.log(`t=${(r.at / 1000).toFixed(2).padStart(8)} s ${r.kind.padEnd(15)} ${r.latency} ms`);
}t= 0.00 s cold 455 ms t= 120.00 s warm 35 ms t= 120.01 s cold (env busy) 455 ms t= 300.00 s warm 35 ms t= 2400.00 s cold 455 ms t= 2460.00 s warm 35 ms
What this code does
The first event finds no environment and pays the start-up cost; later events within ten minutes of the last one are warm. An event that arrives while the only environment is still busy needs a second copy, which is also cold. After a quiet half hour the environment has been recycled and the next donation starts cold again.
For a webhook, a cold start of half a second does not matter: GiveRight waits several seconds for an answer. For a page a person is waiting for, it might. Platforms offer ways to keep environments warm for a price, and edge platforms built on isolates mostly avoid the problem. The more important consequence of reuse is the opposite one: because an environment may be reused, anything left in module-level variables can leak from one invocation to the next, and because it may be discarded at any moment, nothing in memory or on local disk can be relied on to persist.
Writing functions that can run many times
Webhook providers deliver at least once. If GiveRight does not get a 2xx response quickly, or the response is lost, it sends the same event again, possibly minutes later and possibly to a different copy of the function. The function must therefore be idempotent: processing the same event twice must have the same effect as processing it once. The usual way is the one Mira used for check-ins in JS-250: every event has a unique id, and the record is stored under that id, so a second attempt finds it already there. Theo's API accepts an Idempotency-Key header for exactly this, so the function passes the event id as the key.
Checking that a webhook is genuine
Anyone can send a POST to the webhook's address. To prove a request really comes from GiveRight, the provider signs each one: it computes an HMAC with SHA-256 over a timestamp and the exact body, using a secret that only GiveRight and the Food Hub know, and puts the timestamp and the signature in a header. The function recomputes the HMAC and compares. Checking the timestamp too, and refusing anything more than five minutes old, stops an attacker who has captured one genuine request from replaying it later.
// Verify a webhook signature with HMAC-SHA256 using the Web Crypto API.
const enc = new TextEncoder();
const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
const key = await crypto.subtle.importKey('raw', enc.encode('whsec_example_only_7f3c1e9a'), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
async function sign(t, body) { return hex(await crypto.subtle.sign('HMAC', key, enc.encode(`${t}.${body}`))); }
async function verify(header, body, nowS) {
const { t, v1 } = Object.fromEntries(header.split(',').map((p) => p.split('=')));
if (Math.abs(nowS - Number(t)) > 300) return 'rejected: too old';
const sig = new Uint8Array(v1.match(/../g).map((h) => parseInt(h, 16)));
return (await crypto.subtle.verify('HMAC', key, sig, enc.encode(`${t}.${body}`))) ? 'accepted' : 'rejected: bad signature';
}
const now = 1855000000;
const body = '{"id":"evt_7Q2K9","amount":5000}';
const header = `t=${now},v1=${await sign(now, body)}`;
console.log('genuine ', await verify(header, body, now + 2));
console.log('tampered ', await verify(header, body.replace('5000', '500000'), now + 2));
console.log('replayed ', await verify(header, body, now + 3600));genuine accepted tampered rejected: bad signature replayed rejected: too old
What this code does
The signing key is imported once for HMAC with SHA-256, and the signature covers the timestamp and the body together, so neither can be changed without detection. crypto.subtle.verify compares the signatures in constant time, which avoids leaking how many characters matched. The same genuine request is refused an hour later because its timestamp is outside the five-minute window.
The same checks, written for Node.js with node:crypto, form the webhook's real handler. Mira tests it locally by calling the handler with events shaped like the platform's, signed with a test secret: a genuine delivery, the same delivery retried, a tampered body and an hour-old replay.
// src/donation-webhook.mjs: a Lambda-style handler, tested locally with Node.js
import { createHmac, timingSafeEqual } from 'node:crypto';
const SECRET = process.env.GIVERIGHT_WEBHOOK_SECRET; // read once, at cold start
const TOLERANCE_S = 300;
const seen = new Set(); // only for this local test; the real function asks Theo's API
function validSignature(header, body, nowS) {
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
const t = Number(parts.t);
if (!Number.isInteger(t) || Math.abs(nowS - t) > TOLERANCE_S) return false;
const expected = createHmac('sha256', SECRET).update(`${t}.${body}`).digest('hex');
const given = Buffer.from(parts.v1 ?? '', 'hex');
const want = Buffer.from(expected, 'hex');
return given.length === want.length && timingSafeEqual(given, want);
}
export async function handler(event) {
const nowS = Math.floor(Date.now() / 1000);
if (!validSignature(event.headers['giveright-signature'] ?? '', event.body, nowS)) {
return { statusCode: 401, body: 'bad signature' };
}
const donation = JSON.parse(event.body);
if (seen.has(donation.id)) return { statusCode: 200, body: 'already recorded' };
seen.add(donation.id);
// The real function sends the record to Theo's API here, with the event id as its Idempotency-Key.
return { statusCode: 200, body: `recorded ${donation.id}` };
}What this code does
The secret is read once at module level, so it is loaded on each cold start rather than each invocation. The handler checks the timestamp window and then the HMAC with timingSafeEqual, after confirming the lengths match, because timingSafeEqual throws on buffers of different lengths. A delivery whose id has been seen before is acknowledged without being recorded again, which is what makes retries safe.
// try-webhook.mjs: call the handler the way the platform would
import { createHmac } from 'node:crypto';
import { handler } from './src/donation-webhook.mjs';
const body = JSON.stringify({ id: 'evt_7Q2K9', amount: 5000, donor: 'D. Okafor' });
const sign = (t, b) => `t=${t},v1=${createHmac('sha256', process.env.GIVERIGHT_WEBHOOK_SECRET).update(`${t}.${b}`).digest('hex')}`;
const now = Math.floor(Date.now() / 1000);
const tries = [
['genuine', { headers: { 'giveright-signature': sign(now, body) }, body }],
['retried', { headers: { 'giveright-signature': sign(now, body) }, body }],
['tampered', { headers: { 'giveright-signature': sign(now, body) }, body: body.replace('5000', '500000') }],
['replayed', { headers: { 'giveright-signature': sign(now - 3600, body) }, body }],
];
for (const [name, event] of tries) {
const res = await handler(event);
console.log(name.padEnd(9), res.statusCode, res.body);
}What this code does
The harness builds four events the way the platform would and signs them with the test secret from the environment. It calls the handler directly, so the function can be tested on a laptop or in CI without deploying it. The output shows the retry acknowledged but not recorded twice, and the tampered and replayed requests refused.
$ GIVERIGHT_WEBHOOK_SECRET=whsec_test_only_1a2b3c node try-webhook.mjs
genuine 200 recorded evt_7Q2K9
retried 200 already recorded
tampered 401 bad signature
replayed 401 bad signatureLimits, costs and when not to use a function
Functions have limits that a server does not. Each invocation has a maximum run time, typically from a few seconds to fifteen minutes depending on the platform and the plan; a maximum memory, which on some platforms also sets the CPU share; and a maximum request and response size. Work that might run longer belongs in a queue processed by something else. Costs scale with use, which is excellent for a webhook that runs a few thousand times a year and can be poor for steady, heavy traffic, where a server running all the time is cheaper.
There are softer costs too. Each platform has its own configuration, logs, deployment tools and limits, so moving between them takes work, which is the lock-in that the web-standard style and the adapter reduce. Debugging is harder when the code only runs on someone else's machines, which is why Mira's handler is tested locally first. And a function is one more thing to monitor: lesson 9 adds it to the studio's checks.
The studio's decision: the donation webhook runs as a function on a serverless platform, written in the web-standard style with a small adapter, with GIVERIGHT_WEBHOOK_SECRET stored in the platform's secret settings (lesson 8). It records each donation through Theo's API with the event id as its idempotency key. If Theo's API is unavailable, the function returns an error and GiveRight retries later with backoff, so nothing is lost. The office will issue receipts from the records instead of from Dev's spreadsheet.
Worked problem
How many copies run on December 31?
Last year the Food Hub received about 2,600 online donations, 640 of them on December 31, with a peak of 180 in the hour before midnight. Each invocation takes about 400 ms including the call to Theo's API. Assuming the peak hour's donations arrive evenly, how many invocations are running at the same moment on average, and how many invocations does the year need, if each donation is delivered 1.1 times on average because of retries?
Show solution
- Peak rate: 180 per hour = 180 / 3,600 = 0.05 per second.
- Average concurrency: 0.05 per second × 0.4 seconds = 0.02 copies running.
- Even with bursts ten times the average, that is well under one copy most of the time.
- Invocations for the year: 2,600 × 1.1 = 2,860.
Answer: On average far less than one copy is busy, even at the peak, and the year needs about 2,860 invocations. The function is idle almost all the time, which is the pattern serverless pricing rewards.
Common mistakes
MistakeKeeping state in memory between invocations.
InsteadAssume each invocation may run in a fresh environment; store state in a database or call an API.
MistakeProcessing a retried webhook twice.
InsteadMake the handler idempotent using the event's unique id.
MistakeTrusting a webhook because of its address.
InsteadVerify the provider's signature and reject old timestamps.
MistakeDoing expensive set-up inside the handler.
InsteadDo it at module level so it runs once per cold start.
MistakeMoving a long-running or connection-heavy service to functions.
InsteadKeep services with long connections or many database connections on servers.
Summary and key terms
- A serverless function is code the platform runs in response to events, starting copies as needed and stopping them when idle, with no servers for the team to manage.
- It suits short, event-driven, bursty work such as webhooks, and suits long connections and heavy database use poorly.
- AWS Lambda calls a handler with an event object, and its Node.js runtimes follow Node's LTS lines; Cloudflare Workers and others use web-standard Request and Response objects, which an adapter can map to any platform.
- Cold starts add start-up time, and module-level code runs once per environment.
- Webhooks are delivered at least once, so handlers must be idempotent, and signatures with timestamps prove they are genuine and fresh.
- Functions have limits on time, memory and size, and lock-in is reduced by portable code.
- Serverless function
- Code run by a platform in response to events, with servers and scaling managed by the provider.
- Webhook
- An HTTP request one system sends to another to report an event.
- Execution environment
- The container or isolate a platform creates to run copies of a function.
- Cold start
- An invocation that must first create and initialize an execution environment.
- Adapter
- Code that converts between a platform's event format and a portable handler's Request and Response.
- At-least-once delivery
- A guarantee that an event is delivered one or more times, so duplicates can occur.
- Idempotent
- Having the same effect whether performed once or several times.
- Replay attack
- Resending a captured genuine request later; prevented by checking signed timestamps.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does the donation webhook suit a serverless function?
Show answer
It is short, runs only when someone donates, comes in bursts and must keep working when Theo's server is down.
Where should the webhook read its secret, and why?
Show answer
At module level, so it is read once per cold start rather than on every invocation.
What stops a captured webhook from being replayed an hour later?
Show answer
The signature covers the timestamp, and the handler rejects timestamps more than five minutes old.
Why does the function pass the event id as an Idempotency-Key to Theo's API?
Show answer
So a retried delivery does not create a second donation record.
Try it yourself
Fresh enough?
Complete checkTimestamp(t, now, tolerance). It returns ok if the timestamp is within tolerance seconds of now in either direction, too old if it is further in the past, and in the future if it is further ahead.
All values are whole numbers of seconds.
function checkTimestamp(t, now, tolerance) {
return 'ok';
}
const now = 1855000000;
for (const t of [now, now - 300, now - 301, now + 30, now + 600]) console.log(now - t, checkTimestamp(t, now, 300));Try it yourself
Process each event once
Webhook deliveries can repeat. Complete processAll(deliveries) so that it returns the total amount of the distinct donations, counting each event id only once, and the number of duplicates skipped.
Return an object { total, skipped }.
function processAll(deliveries) {
let total = 0;
for (const d of deliveries) total += d.amount;
return { total, skipped: 0 };
}
const deliveries = [
{ id: 'evt_1', amount: 2500 }, { id: 'evt_2', amount: 10000 }, { id: 'evt_1', amount: 2500 },
{ id: 'evt_3', amount: 5000 }, { id: 'evt_2', amount: 10000 }, { id: 'evt_2', amount: 10000 },
];
console.log(processAll(deliveries));Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.