Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Part 1
One small request can fail in four different places. A client sends POST /orders with a JSON body, sku A1, quantity 2, and it arrives at the router. Before the client hears anything back, that request has to pass four checkpoints, and each one can end it early.
Step 1: routing picks the handler
The Client sends POST /orders, and the Router goes first. It matches the method and the path, then runs middleware like JSON parsing, so the raw body becomes an object with sku A1 and qty 2. A miss returns 404 or 405. Otherwise, it dispatches to the Validator.
Step 2: validation fails fast
With qty 2, the router dispatches the body to the validator, which passes it on to the handler. With qty 0, the validator refuses to pass it along and answers 400 Bad Request. The handler never runs, so we skip a wasted database round trip. Cheap checks belong before expensive I/O.
Each checkpoint can send it back
A request is a parcel on a conveyor belt, passing four checkpoints in order: the Router, the Validator, the Handler, and Postgres. Any checkpoint can send it back to the sender with a response. A request doesn't have to reach the end to finish. It only has to stop somewhere.
routes/orders.js
The route and express.json handle matching and parsing. Next comes the early return: bad input gets a 400 before any database work. Then the awaited, parameterized INSERT, where the await frees the event loop while Postgres works. Finally, the 201 carries the new id back.
app.post('/orders', express.json(), async (req, res) => {
const { sku, qty } = req.body;
if (!sku || !Number.isInteger(qty) || qty < 1) {
return res.status(400).json({ error: 'invalid order' });
}
const { rows } = await pool.query(
'INSERT INTO orders (sku, qty) VALUES ($1, $2) RETURNING id',
[sku, qty]
);
res.status(201).json({ id: rows[0].id });
});Step 3: the database round trip
Now the handler calls Postgres. It checks a connection out of the pool, sends the INSERT with sku A1 and quantity 2, and waits while the database commits and returns id 42. This network round trip is usually where latency lives, and pool exhaustion or constraint errors surface here.
Step 4: 201 Created goes back
Postgres hands back id 42, and the handler serializes it into the JSON body {id: 42}. It sends that to the client with status 201 Created. If the database had thrown an error nobody caught, error middleware would turn it into a 500 response instead, unless you map it to a more specific status.
Requests ride a checkpoint conveyor; any checkpoint can send them back.
Requests ride a checkpoint conveyor, and any checkpoint can send them back. So put cheap checks early. A bad body like qty zero should get its 400 at the validator, before it ever pays for the database trip.
