At eight in the evening a food-delivery app serves far more menu reads than orders, and every order is money that must not be taken twice. This chapter builds the orders service behind such an app, one lesson at a time.
The service has four jobs. Customers read the menu. They place an order for the dishes and quantities they want. They follow the order as the kitchen and a rider move it through its stages. And once an order is placed they get a receipt, without waiting for it.
The non-functional requirements shape the design more than the features do. Each row below names a requirement, what it means for this service, and the part of the build that answers it.
Requirement
What it means here
Answered by
Cheap reads
The menu is read far more often than it changes, so most reads should not reach the database
the menu cache
Safe retries
A phone that loses its connection retries the POST, and two orders would mean two charges
the Idempotency-Key and one transaction
Visible failures
Bad input gets a clear 4xx, bad configuration stops the start, a failed receipt is retried
validation, config and the queue
Nothing lost on stop
A deploy must not drop a request or a pending receipt
graceful shutdown
Money is an integer number of paise everywhere: 19000 means 190 rupees. Floating point cannot hold 0.1 exactly, so prices never become decimals inside the service. The server prices every order from its own menu table, and the client never sends a price.
The endpoints
Five routes cover the jobs. Status codes follow the API design chapter: 400 when the body does not match the expected shape, 422 when the shape is fine but the content cannot be accepted, such as a dish that is not on the menu, and 409 when the request conflicts with the order's current state.
Method and path
Success
Refusals
GET /menu
200, or 304 when the ETag matches
none
POST /orders
201 with a Location header
400 bad input or key, 413 body over 10 kB, 422 unknown dish or reused key
GET /orders/:id
200
400 bad id, 404
PATCH /orders/:id/status
200
400, 404, 409 for an illegal move
GET /healthz and /readyz
200, and /readyz gives 503 while stopping
none
A repeated POST with the same key returns the same status and body as the first call, plus an Idempotent-Replayed header, so a client cannot tell the difference and does not need to. Errors use the problem details shape from the same chapter: a JSON body with title, status and detail.
Entities and relationships
Five tables hold everything. An order has many lines, one per dish. A receipt belongs to one order. The idempotency table is bookkeeping for retries, not part of the business model.
Two choices are worth a sentence each. A line copies unit_price_paise from the menu at the moment of sale, so changing a price tomorrow does not rewrite yesterday's orders. And the primary key of order_items is the pair of order and dish, so a dish appears once per order. The request validation mirrors that rule, and a later lesson shows what happens when a client breaks it.
The order lifecycle
An order is always in exactly one status, and only some moves are allowed. Cancelling is possible only while the kitchen has not started. Once an order is out for delivery it can only be delivered. A state machine is the clearest way to write this down, and the scene draws it. It follows the same story as the script below the rule: an order moves forward, and a cancel request after cooking has started is refused.
Animated sceneAn order moves forward, never back0:17
The kitchen accepts, then starts cooking
Read it as steps
A cancel request after cooking has started is refused.
The rule is stored as data, one list of allowed next statuses per status, and the route checks the list before it writes. The final update also carries the status the order had when it was read, so two requests racing to move the same order cannot both win.
This script places an order and tries seven moves in turn. The ones the table forbids come back as 409.
text
preparing 409 placed cannot become preparing
accepted 200 now accepted
preparing 200 now preparing
cancelled 409 preparing cannot become cancelled
out_for_delivery 200 now out_for_delivery
delivered 200 now delivered
cancelled 409 delivered cannot become cancelled
Node 24.18.0, against the running service. Each line is the requested status, the HTTP status and the outcome.
The schema, run
The schema lets PostgreSQL refuse what the rules forbid, so a bug in the code cannot store a nonsense row. These are the two core tables, as the service creates them at start.
sql
createtable if notexists orders (
id bigint generated always as identity primarykey,
customer text notnull,
status text notnull default 'placed' check (status in
('placed','accepted','preparing','out_for_delivery',
'delivered','cancelled')),
total_paise int notnull check (total_paise > 0),
created_at timestamptz notnull default now()
);
createtable if notexists order_items (
order_id bigint notnullreferences orders (id),
menu_item_id int notnullreferences menu_items (id),
qty int notnull check (qty between1and10),
unit_price_paise int notnull,
primarykey (order_id, menu_item_id)
);
db.mjs, orders and order_items
The next script creates the full schema in an in-memory PGlite database, which is PostgreSQL 18.6 compiled to WebAssembly, and then tries four rows the rules forbid. The error codes are PostgreSQL SQLSTATE values: 23514 is a failed check constraint and 23503 a missing foreign key.
text
idempotency_keys, menu_items, order_items, orders, receipts
order with a zero total: refused, code 23514
line for an order that is not there: refused, code 23503
quantity 11: refused, code 23514
status "shipped": refused, code 23514
Node 24.18.0, runs/l1-schema.mjs against a fresh PGlite 0.5.15.
All four were refused. The database is the last line of defence: the API validates first, so a client sees a clear 400, and a missing check in the API would still not corrupt the data.
Why does the service price an order from its own menu table and not accept a price from the client?
A client can send any number. Pricing on the server means the total always comes from the data the business controls.
It also lets a line keep unit_price_paise, the price at the moment of sale.
Why is the total stored as total_paise and not as a decimal number of rupees?
Integers are exact. Floating point cannot represent values such as 0.1, so sums of decimal prices drift.
An order is preparing and the customer asks to cancel. What does the API do, and why?
It answers 409. The allowed moves from preparing are only to out_for_delivery, and 409 means the request conflicts with the current state.
Part 2 · Layout, configuration and the composition root
Layers and files
A service stays easy to change when each file has one job and dependencies point one way. Here the code has three layers: routes, services and infrastructure, plus one file that wires them together.
text
src/
server.mjs reads config, calls start, handles signals
main.mjs the composition root: builds and wires everything
config.mjs environment to a validated, frozen object
app.mjs routes and error mapping (Express)
orders.mjs order rules and their SQL
menu.mjs the menu read and its cache
jobs.mjs a small retrying queue
receipts.mjs the receipt job
db.mjs schema, pool, transaction helper
context.mjs request id store and logger
the layout of the service
The route file only speaks HTTP: it reads the request, calls a service and turns the result or the error into a response. The service files hold the rules and the SQL. Infrastructure is the pool, the queue, the mailer and the logger. The route file imports none of them. It receives a menu and an orders object, so it cannot reach the database by accident.
One decision is worth stating. The SQL stays inside the service files, with no separate repository layer. With five tables a repository adds files without hiding anything. Split it out when two services need the same query, or when a test wants to fake the database, which the testing chapter did with plain functions.
The composition root
The composition root is the one place that creates every dependency and hands each one to whoever needs it. Everything else receives its dependencies as arguments, so nothing imports a global pool or a global logger. This is dependency injection with plain functions, the same design the testing chapter used.
start takes the configuration and, optionally, a mailer and a logger. Production passes neither and gets the defaults. A test passes a fake mailer, a port of 0 and a silent log level, and calls the same function. There is no second code path for tests, so what the tests exercise is what ships.
The queue gets a handler, not the pool. The orders service gets an onPlaced callback, not the queue, so it knows nothing about how receipts are sent. If a later requirement adds an audit log, it is one more callback here and no change inside the orders service.
Configuration that fails fast
The scaling chapter gave a rule for configuration: read the environment once at start-up, collect every problem, name the variable and never print its value, and exit with code 1 so that a deploy stops while someone is watching. This service follows it, with a zod schema doing the collecting.
z.coerce.number() turns the text of an environment variable into a number before checking its range. Optional settings have defaults, so a missing POOL_MAX is fine, and the result is frozen so that no later code can change the settings. Only the schema knows the names, the types and the limits.
Starting with bad configuration
A short script loads the configuration and prints what it got, or the message and exit code 1. These are three runs with different environments. The database URL in the second and third run contains a made-up password, to see whether it leaks.
text
$ (nothing set)
bad configuration
- PORT: Invalid input: expected number, received NaN
- DATABASE_URL: Invalid input: expected string, received undefined
exit code: 1
$ PORT=abc DATABASE_URL=postgres://u:hunter2@h/db \
POOL_MAX=500 SHUTDOWN_MS=50
bad configuration
- PORT: Invalid input: expected number, received NaN
- POOL_MAX: Too big: expected number to be <=50
- SHUTDOWN_MS: Too small: expected number to be >=1000
exit code: 1
$ PORT=55608 DATABASE_URL=postgres://u:hunter2@h/db
config ok: { port: 55608, pool: 10 }
exit code: 0
Node 24.18.0. The script is src/boot-check.mjs.
The first run reports both problems at once, so one deploy shows every mistake. The second run reports three bad values, and the password hunter2 appears nowhere. The third run starts. The exit code is what the platform sees: after exit code 1 it keeps the old version running.
One message is weaker than it should be. A missing PORT reads as received NaN, because coerce turns undefined into NaN before the check. The variable is named, so the operator can act, but a presence check before the number check would say it plainly. Probing a schema with missing input, not only wrong input, is how you find that.
What does the composition root give a test that a module-level pool would not?
The test calls the same start function with its own database, a fake mailer and port 0, so no code path exists only for tests.
Why does loadConfig report every problem instead of stopping at the first?
One failed deploy then shows all the mistakes, and nobody fixes one variable only to find the next on the following attempt.
Why is the exit code of a failed start important?
A platform treats a non-zero exit as a failed deploy and keeps the previous version serving. A service that starts with bad settings fails later, under live traffic.
Part 3 · Placing an order
What must happen together
Placing an order is the one write path that handles money, so it gets the most care. Several things must succeed together or not at all: record that this request key was seen, price the dishes from the menu table, insert the order, insert its lines, and save the response for a retry.
The service does all five inside one database transaction. The idempotency key is claimed first, with an insert that does nothing if the key already exists. A new key means this is the first attempt, so the work proceeds. An existing key means a retry. The service compares a hash of the request body with the stored one: the same hash replays the saved response, and a different hash is a client mistake, refused with 422. The hash covers the customer and the items sorted by dish, so a retry that lists the same dishes in another order is still a retry.
Claiming inside the same transaction has a useful side effect. If pricing fails, because a dish is not on the menu, the whole transaction rolls back and the key is not stored. The client can fix the order and retry with the same key. A key is spent only by an order that exists.
The receipt job is queued after the commit, never inside the transaction. A job queued before the commit could run for an order that then rolls back. The cost is a small window: if the process dies between the commit and the queueing, the order exists without a queued receipt. The background lesson closes that window.
The code
The first block claims the key and handles a retry. on conflict do nothing with returning gives a row only when this request inserted the key, so rowCount tells the two cases apart.
js
asyncfunction place(key, order) {
const hash = fingerprint(order);
const result = await withTransaction(pool, async (tx) => {
const claim = await tx.query(
`insert into idempotency_keys
(key, request_hash, status_code, response)
values ($1, $2, 0, '{}')
on conflict (key) do nothing returning key`,
[key, hash],
);
if (claim.rowCount === 0) {
const { rows } = await tx.query(
`select request_hash, status_code, response
from idempotency_keys where key = $1`,
[key],
);
if (rows[0].request_hash !== hash) {
thrownew AppError(422, 'Key reused',
'this Idempotency-Key was used with a different order');
}
return { replayed: true, body: rows[0].response };
}
orders.mjs, claim or replay
The second block prices the items and inserts the order and its lines. The pricing function (not shown) looks up every requested id in one query and throws a 422 error naming the dishes it did not find. The lines go in with one unnest statement, not one insert per line.
js
const lines = await price(tx, order.items);
const total = lines.reduce((s, l) => s + l.unit * l.qty, 0);
const o = await tx.query(
`insert into orders (customer, total_paise)
values ($1, $2) returning id::int as id`,
[order.customer, total],
);
const id = o.rows[0].id;
await tx.query(
`insert into order_items
(order_id, menu_item_id, qty, unit_price_paise)
select $1, * from unnest($2::int[], $3::int[], $4::int[])`,
[id, lines.map((l) => l.menuItemId), lines.map((l) => l.qty),
lines.map((l) => l.unit)],
orders.mjs, price and insert
The last block saves the response against the key, still inside the transaction, and then, after the commit, tells the rest of the system about the new order.
js
const body = { id, status: 'placed', totalPaise: total };
await tx.query(
`update idempotency_keys set status_code = 201, response = $2
where key = $1`,
[key, JSON.stringify(body)],
);
return { replayed: false, body };
});
if (!result.replayed) onPlaced?.(result.body);
return result;
}
orders.mjs, save, commit, notify
The PostgreSQL documentation for INSERT warns that inserts into a table with a unique index might block when another session has modified matching rows, and points to its page on unique index checks. That page says that when a conflicting row comes from a transaction that has not committed, the inserter must wait to see whether it commits. For two requests with the same key arriving together, the second should therefore wait for the first to finish and then find the saved response. The pages do not spell out the on conflict do nothing case, so that last step is an inference from them. The lab database cannot show this, since PGlite multiplexes its connections onto one backend, so it is documentation and not a run.
Two scenes
The first scene follows a successful order. Look for the order of events: the commit happens before the job is queued, and the customer gets the 201 without waiting for the receipt.
Animated sceneThe path of a placed order0:16
Watch for the order committing before any job is queued
Read it as steps
The order commits first; only then is a receipt job queued.
The second scene shows the failure the key exists for. The phone sends an order, the reply is lost, and the phone retries. The second request finds its key, reads the saved reply and returns it. No second order is created.
Animated sceneA retry gets the saved answer0:17
Watch for the retry getting the saved answer
Read it as steps
The second request finds its key and replays the first answer.
Running it, with bad input
A first order with curl shows the raw response: 201, a Location header and the priced body. The total is 6000 paise for one curd rice.
A script then sends the cases that matter. Read the labels first and guess the status before you read the output.
text
first order
201 Created
location: /orders/2
{"id":2,"status":"placed","totalPaise":19000}
same key again, a retry
201 Created
location: /orders/2
replayed
{"id":2,"status":"placed","totalPaise":19000}
same key, a different order
422 Unprocessable Entity
Key reused: this Idempotency-Key was used with a different order
no key
400 Bad Request
Bad key: use 8 to 64 letters, digits, - or _
quantity 0400 Bad Request
Invalid order: items.0.qty: Too small: expected number to be >=1
item listed twice
400 Bad Request
Invalid order: items: each menu item may appear once
item not on the menu
422 Unprocessable Entity
Unknown item: not on the menu: 99
body that is not JSON
400 Bad Request
Bad JSON: the body is not JSON
runs/l3-probe.mjs. The first order here is order 2 because the curl call came first.
The retry came back as the same order 2, marked as replayed. The same key with a different order was refused, so a client bug cannot quietly change an order. A missing key, a zero quantity, a dish listed twice and a body that is not JSON were all stopped at the edge with a 400, and a dish that is not on the menu got a 422 from the transaction. The last check is the database itself.
text
orders 2
order_items 3
idempotency_keys 2
Two orders, three lines, two keys: one order from curl, one from the script.
Eight requests, but only two orders, three lines and two keys. Every refused request left nothing behind, and the retry created nothing.
Breaking it on purpose
A second script, written to break the service, sent stranger input to a fresh database: an empty body, a body sent as text/plain, a body of 20 kB, a customer name of 61 characters, a quantity of 1.5 and of "2", a retry of a key whose first use failed on pricing, the same two dishes in a different order under one key, and ten requests with one key at the same moment. The hash sorts the items first, so a retry that lists the same dishes in another order is still a replay; hashing them in the order given would have refused it with 422.
text
malformed json 400 Bad JSON
empty body 400 Invalid order
text/plain body 400 Invalid order
oversized (20 kB) 413 Too large
customer 61 chars 400 Invalid order
qty 1.5400 Invalid order
qty string 400 Invalid order
unknown dish 999422 Unknown item
fixed order, key 8201 order 1
order with key 9201 order 2
key 9, other customer 422 Key reused
two items, key 10201 order 3
key 10, items swapped 201 (replayed) order 3
GET /orders/abc 400 Bad id
GET /orders/99999404 Not found
PATCH no body 400 Invalid body
PATCH unknown status 409 Illegal transition
10 concurrent, same key: { '201 first': 1, '201 replayed': 9 }
20 concurrent, distinct keys: { '201': 20 }
Node 24.18.0, runs/probe-errors.mjs against a fresh database. Each line shows the status and the problem title.
Every refusal is a problem details body with the right status, and the 413 comes from the body limit of 10 kB, set in the options of express.json(). The key whose first use failed on an unknown dish worked on the retry, because the failed transaction left no key behind. Ten simultaneous requests with one key gave one new order and nine replays. That result is weaker evidence than it looks: PGlite runs one query at a time, so it cannot show two real sessions racing. With PostgreSQL the second insert waits for the first to commit, as the documentation describes above, and the outcome should be the same.
Why is the idempotency key claimed in the same transaction as the order?
The key and the order then exist together or not at all. A failed order leaves no key, so a corrected retry with the same key works.
A retry arrives with the same key but a different body. What happens, and why?
The stored hash does not match the new body, so the service answers 422. Replaying the old order would hide a client bug.
Why is the receipt job queued after the commit?
A job queued earlier could run for an order that rolls back. After the commit the order is certain to exist.
Part 4 · Reading the menu fast
A cache with single flight
The menu is read on every screen of the app and changes a few times a week. That ratio is the case for a cache. The service keeps the rendered menu in memory with a time to live, a TTL, of 30 seconds by default, and rebuilds it from the database when it expires.
Staleness is acceptable here for a reason worth writing down: the menu is only for display. An order is priced from the database inside the transaction, so a customer who sees a price that is 30 seconds old is never charged it. If the displayed price were also the charged price, a cache of this kind would be wrong.
The service needs the caching chapter's single flight here: when the entry expires under load, the first miss starts the load and stores the promise, and every other caller waits on that same promise instead of starting a stampede of its own.
inflight ??= assigns only when nothing is loading. finally clears it whether the load worked or failed, so a failed load is not cached and the next call tries again. It is the promise-map idea from the caching chapter, kept for a single key.
Counting queries, not guessing
The caching chapter showed single flight on its own; this run checks it inside the service. A script fires 100 callers at a cold cache, once against a naive cache without single flight and once against the real one. The count of database queries is exact and repeats on every run.
text
100 callers, cold cache
without single flight: 100 queries
with single flight: 1 query
100 more callers, warm cache: 1 total
Node 24.18.0, runs/l4-stampede.mjs, a pool of 10 connections.
The naive cache ran 100 identical queries. The single-flight cache ran one. Then a load test sends traffic to the whole service for five seconds with 10 connections, three runs per setting. A TTL of 0 makes every request a miss, and a TTL of 30 seconds makes nearly all of them hits.
Node 24.18.0 on this machine, autocannon 9.0.0, 10 connections for 5 seconds.
Even with a TTL of 0, single flight collapsed about ten concurrent misses into each query: roughly 4,100 to 5,000 queries for 40,000 to 50,000 requests. With the 30-second TTL there was one query in total. The throughput ranges here are 8,200 to 10,000 against 10,500 to 10,900 requests per second. An earlier session of the same test gave 6,400 to 8,200 against 6,800 to 10,900, which overlap, so throughput moves too much between sessions to say which setting is faster. The lab database is in the same process as the service and answers from memory. A database across a network would make each saved query cost more, but that was not measured here. The query count is the evidence; the speed is not.
ETag and 304
A cache in the service saves the database. An ETag saves the network. The service sends a fingerprint of the menu, a hash of its body, as the ETag header. A client that already has the menu sends the tag back in If-None-Match. If the menu has not changed, the service answers 304 Not Modified with no body.
req.fresh is Express's check of the request's conditional headers against the response's ETag, so the route does not parse If-None-Match itself. must-revalidate with max-age=0 lets a client keep a copy but makes it ask first. Three requests show it: a plain read, a conditional read with the same tag, and one with a stale tag.
text
== first read
HTTP/1.1200 OK
etag: "xTKl5_bvqG2dESWF"
== revalidate with the same tag
HTTP/1.1304 Not Modified
etag: "xTKl5_bvqG2dESWF"
== revalidate with a stale tag
HTTP/1.1200 OK
etag: "xTKl5_bvqG2dESWF"
Content-Length: 208
curl against the running service, headers trimmed.
The matching tag got 304 and the stale one got a full 200 with 208 bytes. This menu is tiny, so the saving is small here, and it grows with the size of the menu.
When the menu changes
A cache must also forget. After an update to a price, the cached copy is stale until the TTL ends. The service exposes invalidate(), which drops the entry so that the next read rebuilds it. This script reads the tag, changes a price and reads again, then invalidates and reads a third time.
text
before the change: "xTKl5_bvqG2dESWF"
changed, not invalidated: "xTKl5_bvqG2dESWF"
after invalidate: "nkPB5MMhwRuaCRfR"
Node 24.18.0, runs/l4-change.mjs. The price is restored afterwards.
Without invalidation the tag stayed the same for as long as the entry lived. After invalidate() the next read produced a new tag. The write path of the caching chapter applies: update the database first, then delete the cached entry, so a reader never rebuilds the old value after the delete.
One limit is real. Each instance of the service has its own cache, so with several instances each can be stale for up to the TTL after a change. For a menu that is fine, and a shorter TTL narrows it. If it were not fine, the cache would move to a shared store such as Redis, as the caching chapter showed, and invalidation would work for all instances.
Why is a 30-second-old menu safe to show, when a 30-second-old price at checkout would not be?
The order is priced from the database inside the transaction, so the displayed price is never the charged price.
What does single flight change when the cache expires under load?
Only the first miss runs the query. Other callers wait on its promise, so 100 callers cause one query, not 100.
What does a 304 response save, and what does it not save?
It saves sending the body. The server still checks the cache or database to compute the current tag.
Part 5 · Receipts in the background
Why the receipt is a job
Sending a receipt means calling an email or SMS provider, which is slow and sometimes fails. If the order request waited for it, a provider outage would turn into failed orders. So the order commits, the customer gets the 201, and the receipt is sent by a background job.
A job system promises at-least-once delivery: a job runs one or more times, never zero while the system is healthy. Retries make that work, and retries make duplicates possible, so the handler must be idempotent. Running it twice must have the effect of running it once. The retries wait with exponential backoff and jitter, as the caching chapter explained, so that many failing jobs do not all retry together. After a fixed number of attempts a job goes to a dead-letter list for a person to look at.
js
asyncfunction runJob(job) {
for (let n = 1; ; n++) {
try {
await handler(job, n);
return;
} catch (err) {
if (n >= attempts) {
dead.push({ job, error: err.message });
log.error({ job, attempts: n }, 'job dead-lettered');
return;
}
const cap = baseMs * 2 ** (n - 1);
const wait = Math.round(Math.random() * cap);
log.warn({ job, attempt: n, wait }, `retry: ${err.message}`);
await sleep(wait);
}
}
}
function add(job) {
if (closed) thrownew Error('queue is closed');
const p = runJob(job).finally(() => running.delete(p));
running.add(p);
}
asyncfunction drain() {
closed = true;
await Promise.all(running);
}
jobs.mjs, retries and draining
The queue is a few lines because it lives in the service process. add starts the job and remembers its promise. drain stops accepting new jobs and waits for the running ones, which the shutdown lesson uses. A real deployment with several instances needs a shared queue such as BullMQ, and the handler below would not change.
An idempotent handler
The handler first checks whether a receipt already exists and returns if so. Otherwise it sends the message and records the receipt with on conflict do nothing. Two protections work at two levels. The check makes a duplicate job a no-op. The message id, receipt- plus the order id, is passed to the mailer so that a provider that supports message ids can ignore a second send if the first send worked but the record failed.
js
exportfunction createReceiptHandler({ pool, mailer, log }) {
returnasyncfunction sendReceipt({ orderId, requestId }, attempt) {
return als.run({ requestId }, async () => {
const done = await pool.query(
'select 1 from receipts where order_id = $1', [orderId]);
if (done.rowCount > 0) {
log.info({ orderId }, 'receipt already sent, skipping');
return;
}
const { rows } = await pool.query(
`select customer, total_paise from orders where id = $1`,
[orderId],
);
const body = `Order ${orderId}: Rs ${rows[0].total_paise / 100}`;
await mailer.send(`receipt-${orderId}`, rows[0].customer, body);
await pool.query(
`insert into receipts (order_id, body) values ($1, $2)
on conflict (order_id) do nothing`,
[orderId, body],
);
log.info({ orderId, attempt }, 'receipt sent');
});
};
}
receipts.mjs
The mailer in the lab is a fake that fails its first few calls and remembers the message ids it has accepted. No real email is sent. The handler cannot be exactly once, because a crash between sending and recording leaves a send without a record. That is why the message id matters: at-least-once delivery plus an idempotent step downstream behaves like exactly once.
Request ids through the job
When a receipt fails, you want to find the request that caused it. The observability chapter used AsyncLocalStorage to carry a request id through awaits. The same store works here. A middleware starts a store with a new id for each request, and the logger's mixin reads the id on every log line.
The job payload also carries the id, and the handler starts a store from it. In this process the store would flow into the job by itself, because the job starts inside the request. The payload copy matters when a job is read from a table after a restart, or runs in another process, where nothing flows in. The restart sweep below does exactly that.
Running the failures
One script runs four situations against the real service with the fake mailer, and prints one short line per log record. The lines start with the request id, or a dash for system messages.
In situation A the provider fails twice and then works. In B the same job is queued again by hand. In C the provider is down for every attempt, so the job is dead-lettered. In D the service restarts with a working provider, and finds the order that has no receipt.
text
-- A: the mail provider fails twice, then works
077dbad9 info request done method=POST url=/orders status=201
077dbad9 warn retry: mail provider timed out job=3 attempt=1 wait=34
077dbad9 warn retry: mail provider timed out job=3 attempt=2 wait=176
077dbad9 info receipt sent orderId=3 attempt=3
mails accepted: receipt-3
-- B: the same job is queued again
manual info receipt already sent, skipping orderId=3
-- C: the provider is down for every attempt
- info shutting down reason=restart
- info clean exit
36933672 info request done method=POST url=/orders status=20136933672 warn retry: mail provider timed out job=4 attempt=1 wait=3036933672 warn retry: mail provider timed out job=4 attempt=2 wait=16436933672 warn retry: mail provider timed out job=4 attempt=3 wait=26736933672 error job dead-lettered job=4 attempts=4
dead letters: 1
- info shutting down reason=restart
- info clean exit
-- D: a restart finds the order without a receipt
startup info receipt sent orderId=4 attempt=1
order 4 receipt now: true
- info shutting down reason=done
- info clean exit
Node 24.18.0, runs/l5-receipts.mjs. The waits are random, so they differ on every run.
In A, the request line and the three job lines share one id, so one search finds the whole story. The waits are a random number up to the cap of 100, 200 and 400 milliseconds. In B the duplicate was skipped. In C the fourth failure logged an error and put the job in the dead-letter list, and the order still exists. In D the startup sweep found the order with no receipt row, queued it, and the receipt went out.
The sweep is a single query, orders without a receipt, run at start. It is how the service recovers from the window between commit and queueing, and from a restart that lost the in-memory queue. If two instances start together, both queue the same order, and the check in the handler makes the second one a no-op.
Why must a job handler be idempotent when the queue retries?
A retry can run a job that partly or fully worked. If running it twice has the effect of running it once, retries are safe.
What is lost if the process crashes with jobs in this in-memory queue, and what recovers it?
The waiting jobs are lost. The start-up sweep finds orders with no receipt and queues them again.
Why does the job payload carry the request id when the logger already reads it from AsyncLocalStorage?
Inside one process the store flows into the job. After a restart, or in another process, the id exists only if it was saved in the payload.
Part 6 · Testing and shipping
Integration tests
The tests call the real service over HTTP, backed by a real PostgreSQL engine. Each test file starts its own PGlite database behind a socket server and its own service on port 0, as the testing chapter described. Nothing is shared between files, and nothing is mocked except the mailer.
Six tests follow the lessons: pricing and Location, the retry, bad input that stores nothing, the lifecycle, the 304 and the receipt after a failed send. Here is one of them in full.
js
test('a retry with the same key returns the same order', async () => {
const first = await (await place(dosa, 'retry-key-0001')).json();
const again = await place(dosa, 'retry-key-0001');
assert.equal(again.headers.get('idempotent-replayed'), 'true');
assert.equal((await again.json()).id, first.id);
const { rows } = await svc.pool.query(
'select count(*)::int n from idempotency_keys where key = $1',
['retry-key-0001']);
assert.equal(rows[0].n, 1);
});
one of the six tests
text
✔ an order is priced and has a Location (1246.1245ms)
✔ a retry with the same key returns the same order (32.831ms)
✔ bad input is refused and stores nothing (40.2493ms)
✔ the lifecycle only moves forward (57.0608ms)
✔ the menu answers 304 to a matching tag (5.9148ms)
✔ a receipt is mailed once, after one failed send (37.1134ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1856.3043
node --test, Node 24.18.0. Times vary on every run.
A test that was wrong
The first version of the 304 test failed with 200. The service was right and the test was wrong. The fetch function in Node adds Cache-Control: no-cache and Pragma: no-cache to a request that carries If-None-Match. That follows the Fetch standard: a request with the default cache mode and a conditional header is sent as no-store, and no-store adds both headers when the caller did not set them. The source of undici, the library behind the fetch in Node, has exactly those two steps. Express treats a request with no-cache as asking for a fresh copy, so req.fresh is false. A small server shows what fetch sends.
text
-- fetch with If-None-Match
cache-control: no-cache
pragma: no-cache
-- fetch without it
cache-control: undefined
pragma: undefined
runs/l6-fetch-headers.mjs. The first request has If-None-Match, the second has not.
The fix was to make the conditional request with node:http, which sends only the headers it is given. Express treats no-cache as a demand for a fresh copy but not max-age=0, which is what a revalidating browser usually sends. Two curl requests with the same tag show the difference. The lesson is to read the response a test got before changing the service, and to check what a client library adds on its own.
curl with a matching If-None-Match and the named Cache-Control header.
Stopping without dropping work
The shutdown function follows the scaling chapter's order. It marks the service as draining, so /readyz answers 503. It closes the listener, and sweeps idle connections every 50 ms until the server has closed. Responses sent while draining carry Connection: close. It waits for the queue to finish its running jobs. It closes the pool. The scaling chapter also paused for a second with readiness failing so that a load balancer could notice; adding that here is one line before server.close. A timer, unreferenced so it does not keep the process alive, forces an exit if the deadline passes.
server.mjs installs the signal handlers and calls shutdown. On Windows a SIGTERM terminates a process without running handlers, as the scaling chapter showed, so this run is on Linux. A script places an order whose receipt will fail twice, then sends the process a real SIGTERM at once.
text
b50e2781 info request done method=POST url=/orders status=201
- info shutting down reason=SIGTERM
b50e2781 warn retry: mail provider timed out job=1 attempt=1 wait=82
b50e2781 warn retry: mail provider timed out job=1 attempt=2 wait=43
b50e2781 info receipt sent orderId=1 attempt=3
- info clean exit
exit code: 0
Node 24.18.0 on Linux (WSL), runs/l6-shutdown.mjs.
The signal arrived while the receipt was still retrying. Shutdown waited: the two retries and the successful send happened after the shutting down line, then the process logged clean exit and returned code 0. A process that exited on the signal would have lost the receipt.
That run has no request in flight when the signal comes, so a second probe made one. It opens an idle keep-alive connection, starts a POST and sends half its body, begins the shutdown, tries a new connection, and then sends the rest of the body.
text
an idle keep-alive connection is open
a POST has sent half its body
0 ms shutdown starts
- info shutting down reason=SIGTERM-probe
310 ms a new connection -> ECONNREFUSED ; the POST now sends the rest
37c08703 info request done method=POST url=/orders status=201340 ms the POST connection is closed
37c08703 info receipt sent orderId=1 attempt=1
- info clean exit
344 ms shutdown finished
reply: HTTP/1.1201 Created | connection: close
Node 24.18.0 on Linux (WSL), runs/probe-shutdown.mjs. The 300 ms is the probe waiting before it sends the rest.
The new connection was refused, the order in flight was saved and answered with Connection: close, and shutdown finished 3 ms after the reply. A shutdown that called closeIdleConnections() only once, right after server.close(), would not do that. In two runs of that version the POST was not idle at that moment, so its connection stayed open after the reply and the shutdown waited 6.3 s each time, which is the keep-alive timeout of the server of 5 s plus its 1 s buffer. A platform with a 5 s deadline would have killed the process mid-shutdown. Sweeping repeatedly, and telling clients to close, removed the wait.
A container, a checklist and what comes next
The Dockerfile is the one from the scaling chapter: two stages with npm ci --omit=dev in the first, the non-root node user, and the exec form of CMD so that Node receives the signal. It differs only by leaving out the EXPOSE line, which is documentation and nothing more. It was not built or run here, because the lab has no container tool.
Before launch
Status in this service
Configuration validated at start, secrets never printed
done, with a weak message for a missing PORT
Input validated, one error shape
done
Retried writes cannot duplicate
done for orders; receipts are idempotent
Health and readiness endpoints
done; readiness fails while stopping
Graceful shutdown inside the platform deadline
done, run on Linux with a request in flight
Shared cache and queue for many instances
not done: the cache and queue are per process
Authentication and who may read an order
not done: any caller can read any order id
The last two rows are the honest limits. Before this service meets real customers, the auth chapter's ownership checks must protect GET /orders/:id, since an unchecked id is an insecure direct object reference. A second instance needs the shared cache and a shared queue or an outbox table written in the order's transaction. Payments, a customer-facing order list with keyset paging and a rate limit on POST /orders are the next extensions.
Why does shutdown wait for the queue to drain before closing the pool?
Running jobs still use the pool. Closing it first would fail the receipt that is mid-retry.
The 304 test failed with 200 although the service was correct. What was wrong?
fetch adds Cache-Control: no-cache to a conditional request, so Express treats the tag as stale. The test needed a client that sends only its own headers.
Which row of the checklist is most urgent before real customers use the service, and why?
Authentication and ownership checks. Without them any caller can read any order by guessing its id.