Advanced

Middleware is a chain

Compression, logging, and limits are not part of the handler. They are a chain around it, and the order of the chain is a decision with a consequence.

What you will see

One line with a reason. An order without a reason is an order that will be changed.

About 1 min of reading

Try It

Write the chain order

1

Write the chain

printf 'limit\nauth\ncompress\nlog\n' > /tmp/c.txt; cat -n /tmp/c.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Four numbered lines. The order is the contract of the chain.
2

Swap two links and name the change

printf 'compress\nlimit\nauth\nlog\n' > /tmp/c2.txt; diff /tmp/c.txt /tmp/c2.txt | head -4

Before you run it, say out loud what it will print. Then open the answer.

What it prints
A diff. The diff is the change, and the change is a bound that moved.
3

Write the reason for the order

printf 'order=limit-first reason=bound raw bytes\n' > /tmp/o.txt; cat /tmp/o.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
One line with a reason. An order without a reason is an order that will be changed.

Data Flow

A request through a chain
1 The chain is built at start
↓
2 The request enters the first link
↓
3 A link may write and stop the chain
↓
4 The handler runs at the end
Why this works
Why the chain is built once

Building per request is work per request. A chain built at start is a chain that cannot drift per request.

The cost of a link

Each link is work on every response. The work is measured per link, which is why the links are named.

Examples

Order changes the result

A limit before compression bounds the compressed bytes. A limit after bounds the original ones.

The chain is written down

The order is a list. A list in a file is a list that can be reviewed before it is deployed.

One link can stop the chain

A link that writes a response ends the request. The end is why the chain has an order at all.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Connections are a pool
Previous Lesson
Connections are a pool
Next Lesson
Streaming a large response
Streaming a large response →