Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Shut down a Node HTTP server cleanly

Handle SIGTERM in Node, give in-flight HTTP responses time to finish and close connections that pass the deadline.

A deploy sends your Node server a SIGTERM, and with no handler Node exits on the signal and cuts off the requests in flight. I started a server with a 1.5 second route and sent SIGTERM mid-request. curl exited with 52 (empty reply) and the server exited with status 143.

Stop accepting, finish the rest

server.close() stops accepting new connections. In Node 19 and later, it also closes idle HTTP connections. Call it once from a SIGTERM handler and let Node exit after the remaining work finishes.

import { createServer } from 'node:http'

const server = createServer(async (req, res) => {
  if (req.url === '/slow') await new Promise((r) => setTimeout(r, 1500))
  if (req.url === '/stream') {
    res.write('tick\n') // never ends
    return
  }
  res.end('done\n')
})
server.listen(4130, '127.0.0.1')

process.once('SIGTERM', () => {
  const start = Date.now()
  server.close((error) => {
    clearTimeout(deadline)
    if (error) {
      console.error(error)
      process.exitCode = 1
      return
    }
    console.log(`closed after ${Date.now() - start} ms`)
  })
  const deadline = setTimeout(() => server.closeAllConnections(), 5000).unref()
})

On SIGTERM the server prints how long the shutdown took. A new request during shutdown got curl: (7), connection refused, because the listener was already closed.

Measure three clients

My client opens a keep-alive connection, sends /, and leaves the socket open. I sent SIGTERM one second later in three runs: with nothing else, with /slow in flight, and with /stream open.

# keep-alive socket open, nothing in flight
closed after 1 ms

# /slow in flight
/slow -> 200 after 1504 ms
closed after 593 ms

# /stream open, never ends
closed after 5004 ms
/stream closed by server

The idle keep-alive socket did not hold the shutdown open, because close() dropped it. The slow request finished with a normal 200 before the server exited.

Put a deadline on the rest

The stream shows what close() cannot fix. A response that never ends keeps its connection busy, so the callback never fires. Without the timer in the code above, my server stayed up until the client quit at 12 seconds.

server.closeAllConnections() is the hard stop. It destroys the remaining HTTP connections, including ones with unfinished responses. Track upgraded sockets, such as WebSockets, separately. The timer runs after close() has stopped accepting new connections.

server.closeIdleConnections() does not help here. I added it to the signal handler and took the timer out. The stream still held the shutdown open for 11 seconds, because a response that has started is not idle.

Keep the deadline below your deploy platform’s shutdown limit. If your app also opens database pools or starts background jobs, close those resources during shutdown.