npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

request-drain

v1.2.0

Published

Gracefully drain HTTP requests before shutting down a Node.js service.

Readme

request-drain

Gracefully drain HTTP requests before shutting down a Node.js service.

npm version TypeScript License: MIT Node.js codecov

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-drain

Usage

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