FAHADBIN SHAKIR

Loading essential experience000%

Node.js Operations

Zero-Downtime Node.js Deployments Behind Reverse Proxies

A release design for Node.js readiness, graceful shutdown, proxy switching, database compatibility, rollback, and public-domain verification.

Author: Fahad Bin Shakir · Published: · Updated: · 6 min read

Traffic switching between two Node.js service pools during a controlled deployment

Introduction

A process manager can restart Node.js quickly, but quick is not the same as uninterrupted. During a release, the old process may still hold keep-alive connections while a new process is compiling templates, connecting to the database, or warming required state. If the reverse proxy sends traffic as soon as the port opens, real requests become the readiness test. If the old process is killed immediately, in-flight uploads and API writes are cut in half.

A zero-downtime design coordinates immutable releases, health states, proxy membership, graceful drain, compatible database changes, and a fast rollback. It also verifies the canonical public domain rather than only localhost. The target is not a promise that no request can ever fail; it is a controlled transition with bounded failure modes, measurable gates, and no period in which every healthy instance disappears.

Define liveness, readiness, and startup separately

Liveness answers whether the process event loop can respond and should rarely depend on every downstream service. Readiness answers whether this instance may receive normal traffic: required configuration loaded, critical connections established, migrations compatible, and startup work complete. A startup probe or state prevents an orchestrator from killing a slow but progressing initialization. Combining all three into one endpoint creates restart loops during dependency incidents.

Return only minimal status and an appropriate status code. Do not expose environment values, filesystem paths, dependency credentials, stack traces, or internal headers. Readiness should fail when the instance is draining so the proxy stops assigning new work. Exercise the endpoint through the actual proxy configuration, because a correct application route is useless if rewrite rules or Passenger mapping bypass it.

Build an immutable, reproducible release

Create the production artifact from a reviewed commit with the locked dependency graph, fixed runtime version, and production environment flags. Run type checks, lint, tests, dependency audit, and build before the switch. Record the commit and artifact identity in deployment metadata that can be verified without exposing sensitive configuration. Do not run an uncommitted package update directly on the host.

Place each release in its own directory or image and keep configuration outside the artifact. The active pointer changes only after the new release passes startup and readiness. Static assets should be content-hashed so old HTML can finish while caches or clients still request the previous files. Retain at least one known-good artifact and the exact rollback command.

Keep database migrations compatible across the switch

Old and new processes overlap during a safe deployment, so both must understand the database at the same time. Use expand-and-contract migrations: add nullable columns or new tables first, deploy code that writes and reads compatibly, backfill in bounded batches, then remove the legacy shape in a later release. Renaming or dropping a required column during the first switch breaks whichever version is still serving.

Migration execution needs an exclusive owner and explicit observability. Test duration against production-sized data, understand locks, and set a rollback or roll-forward policy before starting. A migration that cannot be reversed may require restoring a snapshot, which is much slower than switching an application symlink. The release gate should distinguish application rollback from database recovery.

Drain connections and bounded background work

On the termination signal, mark the instance unready, stop accepting new work, close the HTTP listener, and allow active requests to finish within a defined grace period. Track sockets so idle keep-alive connections can be closed deliberately. After the deadline, terminate remaining work and record how many requests were interrupted. Without a deadline, one hung connection can prevent the release from completing.

WebSockets, server-sent events, file uploads, and background consumers need specific policies. Long-lived clients may reconnect through the proxy to a new instance; uploads may need a longer drain window or resumable design. Queue workers should stop claiming items, finish one bounded unit, and release leases safely. Do not assume the HTTP server close callback covers every timer, database pool, or external client.

Switch traffic with capacity to spare

Start the new version alongside healthy old capacity. Wait for readiness over several checks, send a synthetic request set, and then add it to proxy rotation. A rolling strategy should never remove so many old instances that the remainder cannot handle peak load. In a single-account Passenger environment, use the platform's documented restart behavior and keep the application boot path fast and deterministic.

Measure status codes, tail latency, event-loop delay, memory, restarts, database errors, and proxy upstream failures during the switch. Compare the new release rather than trusting aggregate fleet health. If a threshold is crossed, stop the rollout and route back to the known-good artifact. A rollback that requires rebuilding dependencies is not a fast rollback.

Verify the public path and rollback evidence

After the switch, request the canonical HTTPS host through DNS, CDN, Apache or Nginx, Passenger, and the application. Check homepage, direct client routes, critical hashed assets, APIs, form validation without sending duplicate real messages, robots, sitemap, canonical tags, security headers, redirects, and an unknown route. Localhost success cannot detect stale edge HTML or broken host normalization.

Record the live commit and asset fingerprint, then watch an observation window long enough to include normal traffic and at least one scheduled task. Roll back when the agreed threshold fails, not after extended improvisation. Complete the incident record with the exact symptom, first bad release, recovery time, and a regression test that exercises the failed boundary.

Test the races that happen only during a release

Run a deployment rehearsal while continuously requesting a mix of short pages, slow API calls, streamed responses, and a safe write with an idempotency key. Open keep-alive connections before the switch and verify whether they finish on the old process or reconnect cleanly. Start a bounded queue item, begin the drain, and confirm that no second worker repeats its side effect. This test should include a failed readiness check and a new process that exits after briefly opening its port, because port availability alone is a weak traffic gate.

Inspect proxy logs and application correlation identifiers to count any reset, duplicate, or misrouted request. Verify that old HTML continues to load its hashed assets after the new release is active and that rollback restores the previous application without reversing a compatible database expansion. Repeat the exercise when proxy, process-manager, Node, or framework versions change. Zero-downtime behavior is an interaction among layers; it cannot be permanently proven by one successful restart on an otherwise idle host.

Deployment checklist

  • Separate minimal liveness, traffic readiness, and startup state.
  • Build an immutable artifact from the locked dependency graph and reviewed commit.
  • Use expand-and-contract database migrations across overlapping versions.
  • Mark an instance unready before draining HTTP, sockets, and queue workers.
  • Keep enough healthy old capacity until the new release proves ready.
  • Set measurable rollout thresholds and retain a known-good artifact.
  • Verify the canonical public domain, redirects, assets, APIs, and security headers.
  • Record the live commit and observe scheduled plus user traffic before closure.

Related portfolio and context

Primary references

Related Engineering Notes

View all Engineering Notes