⏰ Koa Timeout
A Koa middleware to handle timeouts correctly
How it works
to race a
setTimeout against your Koa middlewares/response.
Middlewares A 1s B 2s C 3s D 4s ╭─────┴────────┴─────╳╌╌╌╌┴╌╌╌╌╌╌╌╌╌┴╌╌╌╌╌ Req ─────┤ ╰────────────────────┬──→ 408 - 2500ms Timeout 2.5s
In this example, a request has come in and the timeout is racing
D. However, the timeout is triggered
408 response after
╳ signifys a short circuit and prevents middlewares
D from running.
Middlewares A 1s B 2s C 3s D 4s ╭─────┴────────┴─────────┴─────────┴──────╮ │ │ Req ─────┤ ╰──→ 200 - 4500ms │ ╰─────────────────────────────────────────╳╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╮ Timeout 5s
In this example, all 4 middlewares -
D - have
finished, resulting in a
200 response after ~
4500ms. The timeout
is then cleared, signified by the
The middleware can be configured with a custom timeout time and status code.
const app =app // 1s timeoutapp // 1s timeout with 499 status
N.B. By default,
koa-timeout does not short circuit the
other middlewares. This means that the in-flight request will continue to be
processed even though a response has already been sent.
This behaviour can be useful in development to see where the slow parts of the request are, however, in production you probably want to kill the request as soon as possible.
To enable short circuiting
This will prevent the next middleware after a timeout from triggering.
N.B. when calling with multiple middlewares, make sure
to spread the result!
...shortCircuit(a, b, c)