request-drain
v1.2.0
Published
Gracefully drain HTTP requests before shutting down a Node.js service.
Maintainers
Readme
request-drain
Gracefully drain HTTP requests before shutting down a Node.js service.
request-drain tracks active HTTP requests and allows services to wait until all requests are finished before shutting down.
It is designed for graceful deployments where a process should stop accepting new requests, finish ongoing ones, and then exit cleanly.
What problem does this solve?
When deploying a new version of a service, existing HTTP requests should be allowed to finish before the process exits.
request-drain tracks active requests and allows services to wait until they are completed.
Features
- ✅ Graceful request draining for Node.js services
- ✅ Works with Express, Fastify, Koa or any Node.js HTTP framework
- ✅ No runtime dependencies
- ✅ Multiple middleware layers can track the same request safely
- ✅ Predictable shutdown behavior with optional timeout
- ✅ Track arbitrary async tasks alongside HTTP requests
Installation
npm install request-drainUsage
The recommended pattern is to encapsulate shutdown behavior inside each middleware. The middleware registers itself with the ShutdownRegistry, tracks incoming requests, and decides how long to wait for them to finish.
The request object must be a Node.js IncomingMessage. This is compatible with Express, Fastify, Koa and native HTTP servers.
import {ShutdownRegistry} from "request-drain"
const registry = new ShutdownRegistry()
const createMiddleware = (registry: ShutdownRegistry) => {
const handle = registry.register()
handle.onAbort(async () => {
const drained = await handle.waitUntilIdle(5_000)
if (!drained) {
console.warn(`shutdown timed out with ${handle.pendingCount} requests still pending`)
}
})
return (req, res, next) => {
if (handle.isShutdown) {
res.status(503).end("Server shutting down")
return
}
/**
* Registers the request with the handle.
* The request is automatically released when it closes.
*/
handle.request(req)
next()
}
}
app.use(createMiddleware(registry))
const onShutdown = async () => {
await registry.shutdown()
process.exit(0)
}
process.on("SIGTERM", onShutdown)
process.on("SIGINT", onShutdown)In this example the middleware:
- tracks incoming requests
- stops accepting new requests during shutdown
- waits up to 5 seconds for active requests to finish
registry.shutdown() calls onAbort on all registered handles and waits for them to complete.
Tracking Async Tasks
In addition to HTTP requests, startTask() lets you track arbitrary async work — such as background jobs, queue processing, or cleanup routines — within the same shutdown coordination.
const handle = registry.register()
handle.onAbort(async () => {
const drained = await handle.waitUntilIdle(5_000)
if (!drained) {
console.warn(`shutdown timed out with ${handle.pendingCount} tasks still pending`)
}
})
// Start a task before doing async work
const task = handle.startTask()
doSomethingAsync().finally(() => {
// Signal that the task is complete
task.done()
})startTask() returns a Task object with a single done() method. Call done() when the work is finished so the handle can reach idle state and shutdown can proceed.
This is useful when your middleware or service component kicks off work that is not tied to an HTTP request lifecycle.
Multiple Middlewares
Each middleware registers its own handle. The registry ensures that a request passing through multiple middlewares is tracked independently per handle without double-counting within a handle.
const registry = new ShutdownRegistry()
app.use(createMiddleware(registry))
app.use(createSessionMiddleware(registry))
const onShutdown = async () => {
await registry.shutdown()
process.exit(0)
}
process.on("SIGTERM", onShutdown)
process.on("SIGINT", onShutdown)Optional: Global Shutdown Timeout
request-drain does not enforce a global shutdown timeout. Each middleware decides how long it waits via waitUntilIdle().
If you want to enforce a maximum shutdown time for the entire process, add a safety timeout in your signal handler:
import {setTimeout as sleep} from "node:timers/promises"
const onShutdown = async () => {
await Promise.race([
registry.shutdown(),
sleep(30_000)
])
process.exit(0)
}
process.on("SIGTERM", onShutdown)
process.on("SIGINT", onShutdown)This ensures the process exits even if a component fails to shut down in time.
Design Goals
- Minimal API surface
- Predictable shutdown behavior
- No framework coupling
- No global state
- No runtime dependencies
License
MIT
