Zero-Downtime Deployment Strategies
Deploy without downtime using rolling updates, blue-green switches, canary releases, and feature flags, all gated by health checks and instant rollback.
On this page
Introduction
A deployment is the moment a change meets production, and a zero-downtime deployment is one where the users never notice. The naive deployment — stop the old version, start the new version — is downtime by definition, and it is the deployment that fails when the new version will not start, because the old version is already gone. The strategies in this article — rolling updates, blue-green, canary, and feature flags — decouple the release of new code from the exposure of it, so a bad version is caught before it affects every user and rolled back in seconds rather than restored from backup in hours. The common thread is a health check that gates traffic and an instant rollback that is always available.
The Health Check Is the Gate
Every zero-downtime strategy depends on the orchestrator knowing whether a version is healthy. The health check — an HTTP endpoint that returns 200 when the process is ready to serve traffic and 503 when it is not — is the gate that keeps traffic from a version that has started but is not ready, and the signal that triggers a rollback when a version is broken. Without a health check, the orchestrator routes traffic to a process the moment it starts, including the moment it starts and immediately crashes on a missing dependency.
let ready = false;
app.get("/health", (req, res) => res.status(ready ? 200 : 503).end());
// Mark ready only after dependencies are connected and migrations are checked.
async function start() {
await db.connect();
await redis.connect();
await runMigrationsIfSafe();
ready = true;
app.listen(3000);
}
The readiness check is distinct from the liveness check: readiness fails when the process cannot serve traffic (a dependency is down, the process is draining); liveness fails when the process is wedged and should be restarted. The load balancer uses readiness to route; the orchestrator uses liveness to restart. Get both right, and the orchestrator makes the right decision at every transition.
Rolling Updates
A rolling update replaces instances of the old version with the new version one at a time (or in small batches), waiting for each new instance to pass its health check before moving to the next and before stopping the corresponding old instance. At every point, some instances serve the old version and some serve the new, and traffic is split between them. If a new instance fails its health check, the rollout pauses and the old instances keep serving — the users see no downtime, and the operator sees a failed rollout they can roll back.
# A rolling update with a health gate (Docker Compose / Swarm style).
deploy:
replicas: 6
update_config:
parallelism: 2 # update 2 at a time
delay: 10s # wait between batches
order: start-first # start new before stopping old
failure_action: rollback
Rolling updates require that the old and new versions run side by side, which means they must be compatible — both must read the same database schema, both must handle the same requests. This is the backward compatibility the migration article covers: a rolling deploy of an incompatible version serves errors from the new instances while the old instances still work, and the rollout degrades rather than fails cleanly. The expand-and-contract migration pattern exists to make rolling deploys safe.
Blue-Green Deployment
Blue-green deployment runs two complete environments — blue (current) and green (next) — and switches traffic between them with a single router change. The green environment is built and started without receiving traffic; the health checks pass; the router is flipped to send all traffic to green; blue becomes the standby. If green is broken, the router flips back to blue in seconds, because blue is still running and still healthy.
// The router switch is a single atomic update.
function switchTraffic(target: "blue" | "green") {
router.update({ default: { service: target, weight: 100 } });
}
// Deploy: build green, wait for healthy, switch, keep blue as rollback.
The advantage over rolling is the instant, all-at-once switch and the trivial rollback — flip the router and you are back on blue, with no instances to recreate. The cost is the double infrastructure (two full environments running) and the need for the database to be shared or replicated between them, which complicates schema changes. Blue-green is ideal for stateless services where the double cost is acceptable and the instant switch is valuable; it is harder for stateful services where the data must move with the version.
Canary Releases
A canary release exposes the new version to a small fraction of users first, observes the error rate and latency, and expands the exposure only if the metrics are good. The canary is the strategy that catches the bug the health check cannot — the version that is healthy but returns the wrong answers, or that has a 1% error rate the health check does not detect. Start with 1% of traffic, watch the error rate for a window, ramp to 10%, 50%, 100% if the metrics hold, and roll back if they do not.
// Weighted routing for a canary.
router.update({
default: { service: "blue", weight: 99 },
canary: { service: "green", weight: 1 },
});
// Automated promotion gate: expand only if the canary's error rate is below threshold.
async function promoteCanary() {
const errorRate = await metrics.errorRate({ service: "green", window: "5m" });
const p99 = await metrics.p99Latency({ service: "green", window: "5m" });
if (errorRate > 0.01 || p99 > 2000) return rollback();
await rampTraffic("green", [10, 50, 100]); // expand in steps
}
The canary turns deployment into an experiment: you measure the new version in production before you commit to it. The metrics that gate the promotion are the same observability metrics from the monitoring article — error rate, latency, saturation — and the comparison is against the old version’s baseline, not an absolute threshold, so a canary in a noisy production environment still detects a regression relative to the current state.
Feature Flags: Decoupling Deploy from Release
A feature flag decouples the deployment of code from the exposure of the feature. The code is deployed to all users but inert, gated by a flag that is off; the flag is turned on for a subset, then expanded, then made default, and finally the flag is removed. This means a deploy can never break a feature the users see, because the feature is not on until the flag is on, and the flag can be turned off without a deploy.
if (flags.isEnabled("new-checkout", user.id)) {
return newCheckout(user);
}
return oldCheckout(user);
Feature flags are the most flexible strategy: they enable canary by user cohort, A/B testing, instant kill switches, and progressive rollout, all without a redeploy. The cost is the flag debt — flags accumulate, and every flag is a branch in the code that must be tested and eventually removed. Discipline the lifecycle: every flag has an owner and an expiry, and stale flags are removed in a scheduled cleanup. A codebase with a hundred permanent flags is a codebase nobody can reason about; a codebase with flags that come and go is a codebase that releases safely.
Rollback: Always Available, Always Practiced
Every strategy in this article is only as good as its rollback, because the rollback is what you do when the new version is bad. The rollback must be instant (flip the router, revert the flag, scale the old version back up), it must be available at every moment of the rollout, and it must be practiced. A rollback you have never run is a rollback that fails when you need it, because the database state has moved on or the old version is no longer available. Practice the rollback in staging on every release, so the production rollback is a known, rehearsed operation rather than a panicked improvisation.
Database Changes During Zero-Downtime and Stateful Session Affinity
The hardest part of a zero-downtime deploy is not the code swap but the database change that accompanies it, because the old and new versions must both work against the same database during the overlap. A deploy that adds a NOT NULL column without a default fails: the old version does not know the column exists and inserts rows without it, which the database rejects. A deploy that removes a column the old version still reads fails: the old version queries the column and the database no longer has it. The expand-and-contract pattern is the method that makes a database change safe across a rolling deploy, and it is a sequence of deploys, not a single one.
The expand phase adds the new column as nullable (or with a default), so the old version’s inserts — which do not include the column — succeed with a null. Deploy the new version, which writes the column and backfills the existing rows. Once every row has a value, add the NOT NULL constraint as a separate migration — by then, no row is null, and the constraint is safe. The contract phase, after the old version is fully retired, removes the column the old version read, in a final migration. Each step is a deploy that is independently reversible, and at no point do the two versions disagree with the database.
1. Expand: ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT false; -- nullable, old code unaffected
2. Deploy: new version writes email_verified, backfills existing rows to false
3. Constrain: ALTER TABLE users ALTER COLUMN email_verified SET NOT NULL; -- safe, no nulls remain
4. Contract: (after old version retired) remove the old column the new code does not use
For a column rename, the expand phase adds the new column, the deploy writes to both the old and new columns (dual-write), a backfill copies old to new, the deploy switches to reading the new column, and the contract phase drops the old column. The dual-write is the overlap that keeps the two columns in sync during the transition, so a rollback to the old version — which reads the old column — sees the correct data. Skip the dual-write and a rollback reads stale data from the old column; include it and the rollback is safe. The pattern is verbose because it is safe, and the verbosity is the cost of changing a live database without a maintenance window.
Stateful services complicate the rolling deploy because a request in flight may be bound to a specific instance’s state. A WebSocket connection lives on one server; a session stored in the server’s memory is bound to that server; a long-running upload is in progress on one instance. A rolling deploy that terminates the instance drops the connection, loses the session, and interrupts the upload. The mitigations are to drain the instance (stop sending new requests, wait for in-flight requests to complete, then terminate), to externalize the state (store the session in Redis, not in memory, so any instance can serve it), and to use connection draining for long-lived connections (notify the client to reconnect to a new instance, with a grace period).
# Kubernetes: a rolling update with a grace period for connection draining.
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0 # never below the desired count -> always serving
terminationGracePeriodSeconds: 30 # 30s to finish in-flight requests before SIGKILL
Session affinity (sticky sessions) is the alternative to externalized state: the load balancer routes requests from the same session to the same instance, so the in-memory state is consistent. But session affinity is a trap during a deploy: the instance the session is bound to is being replaced, and the affinity routes the user to a terminating instance. Prefer externalized state (a session store, a shared cache) so any instance can serve any request, and the rolling deploy is transparent to the user. If affinity is unavoidable (a legacy stateful service), combine it with connection draining and a reconnection protocol, so the user is moved to a new instance rather than dropped. The goal is a deploy the user does not notice, and stateful services are the part that makes that goal hard — externalize the state, and the rest is straightforward.
Conclusion
Zero-downtime deployment is a health check that gates traffic, a strategy that exposes the new version gradually — rolling for compatibility, blue-green for an instant switch, canary for measurement, feature flags for control — and an instant, practiced rollback that is always available. The principle through all of them is to decouple the release of code from the exposure of change, so a bad version is caught by health and metrics before it reaches every user and reversed in seconds when it is not. Deploy gradually, measure continuously, and keep the rollback rehearsed, and the deployment becomes a non-event the users never notice.
Report a problem with this articleOpens a pre-filled issue on GitHub.