Skip to content
Opsfolk
DevOps

Blue-Green Deployment Explained: Zero-Downtime Releases with Instant Rollback

Blue-green deployment runs two identical environments and moves all traffic to the new version in one switch, so a rollback takes seconds. Learn how it works, how to do it in Kubernetes, how it compares with canary and rolling updates, and how to handle databases.

admin18 min readUpdated

Blue-Green Deployment: zero-downtime releases with instant rollback. A router sends all traffic to green servers while blue stands by, above a shared database.
On this page

Every deploy is a small bet. You replace code that works with code you believe works, while users are still clicking. With an in-place deploy, that bet has an awkward shape: for a few minutes, old and new versions run side by side, and if the new one is broken, getting back means deploying the old one again, just as slowly.

Blue-green deployment changes the shape of the bet. You keep the version that works running, start the new one next to it, test it, and only then move traffic across in one step. If something goes wrong, you move traffic back. In this guide you'll learn how blue-green deployment works, where the switch lives, how it compares with rolling updates and canary releases, how to run it in Kubernetes, and how to handle the part most tutorials skip: databases and state.

What Is Blue-Green Deployment?

Definition: Blue-green deployment is a release strategy that runs two identical production environments, called blue and green. One serves all live traffic while the other receives the new version. After the new version passes its checks, a router sends all traffic to it in one switch, and the old environment stays ready for an instant rollback.

The colours are only names. What matters is that at any moment exactly one environment is live and the other is idle. Each environment is a complete copy of your application: the same servers or pods, the same configuration, the same network path. Only the version differs.

A good way to picture it is a theatre with two stages. The audience watches the show on one stage while the crew builds the next show on the other. When the new set is ready and checked, the audience simply turns their chairs. If the new show falls apart in the first scene, they turn back to a stage that still has the old show on it.

Three properties make the technique work:

  • A single switch. Some component, the router, decides which environment is live. Changing it is quick and doesn't touch the environments themselves.
  • Full-size environments. Green can take all of production's traffic the moment it goes live, because it was built to the same size as blue.
  • The old version stays up. Rolling back is the same switch in the other direction, not a new deploy.

The technique is older than containers. Martin Fowler described it in 2010 in his BlueGreenDeployment article, and it is covered in Jez Humble and David Farley's book Continuous Delivery. Fowler credits the name to Daniel Terhorst-North and Jez Humble.

Users reach a router that sends every request to blue, the live environment; green is idle and smoke-tested privately; both share one database.

How Blue-Green Deployment Works

A blue-green release is a loop. Each release ends with the environments trading roles, so the next release goes to the one that just became idle.

The Release Cycle, Step by Step

How to do a blue-green deployment:

  1. Blue serves production. All user traffic goes to blue, which runs the current version (say v1.4).
  2. Deploy the new version to green. Green gets v1.5 with production's configuration. Users can't reach it yet.
  3. Test green privately. Run health checks, smoke tests and, if you can, a short load test against green through a private address.
  4. Switch the router. The router now sends every new request to green. Requests already in progress on blue are allowed to finish.
  5. Watch. Compare error rates, latency and business metrics with what blue was doing a few minutes earlier.
  6. Keep or roll back. If green is healthy, it is the new production. If not, switch the router back to blue, which is still running v1.4.
  7. Recycle. After a rollback window, blue becomes the idle environment and receives the next release.

A blue-green release: deploy to green, test it privately, switch traffic, watch, then keep green or switch back to blue; the next release goes to blue.

Switching Without Dropping Requests

The switch changes where new requests go. It does nothing to requests that are already being handled. A request that arrived at blue one second before the switch still needs blue to answer it. If blue stops at the moment of the switch, that request fails, even though the release itself was perfect.

The fix is connection draining: after the switch, keep blue running until its in-flight requests have finished, and only then stop it. Load balancers usually call this a deregistration delay or draining timeout; Kubernetes pods get a grace period when they are terminated.

In the figure below, each line is one request, from when it arrives to when it is answered, drawn in the lane of the environment that serves it. Watch the lines that cross the switch: in a good release they finish on blue; switch without draining and they are cut off. Then try the bad release, where the switch back to blue is what saves the day.

Sixteen seconds of requests, sped up, each a line from when it arrives to when it is answered, in the lane of the environment that serves it. At 6 s the router sends new requests to green. In a good release the 8 requests already on blue finish there, and none is lost. Without draining, blue stops at the switch and those 8 are cut off. In a bad release, 6 of the 11 requests green takes fail; the alert fires at the third failure, at 8.9 s, the router switches back to blue, still running, and every request after that succeeds.

Switching traffic from blue to green

Rollback Is Just Another Switch

In the bad release, green started failing requests as soon as it went live. The alert fired at the third failure, less than three seconds after the switch, and the router sent everything back to blue. Every request after that succeeded, because blue never stopped running v1.4. Nothing had to be rebuilt, pulled or started.

That is the main thing blue-green buys you: a rollback that takes as long as the switch. Compare that with an in-place deploy, where rolling back means deploying the old version again, with all the time and risk of a deploy, while your users wait.

Two caveats keep this honest. First, the rollback only works while blue is still there: once you scale it down, you are back to redeploying. Most teams keep blue running for a rollback window, from a few minutes to a few hours. Second, a rollback moves traffic, not data. Anything green wrote to a shared database stays written, which is why the database section below matters.

Where the Switch Lives

The router can be any component that decides where requests go. Where you put it decides how fast and how cleanly you can switch.

Switch How you flip it Speed Watch out for
DNS record Point the name at green's address Minutes to hours Resolvers and clients cache answers for the record's TTL, and some keep them longer, so rollback is slow and uneven
Load balancer Move the listener to green's target group, or set the weights to 0 and 100 Seconds Set a draining timeout so blue's in-flight requests finish
Kubernetes Service Change the Service's label selector from blue pods to green pods Seconds Open connections stay on blue pods until they close
Ingress, Gateway or service mesh Change the route's backend or weights Seconds Each tool has its own syntax; weights also let you shift gradually

For most teams the load balancer or the Kubernetes Service is the right place. DNS looks simple, but you can't make every client in the world forget an old answer, so a DNS rollback is never instant.

Cloud providers also package the whole flow. AWS CodeDeploy, for example, runs blue/green deployments for Amazon ECS and EC2, and an Application Load Balancer can split traffic between two target groups by weight.

Blue-Green vs Rolling Update vs Canary

Blue-green is one of three common ways to replace a running version. They differ in how traffic moves and what a rollback costs.

Rolling update Blue-green Canary
How traffic moves Old instances are replaced a few at a time All at once, from one full environment to another A small share first, raised in steps while metrics look healthy
Who meets the new version first A growing share of users Everyone A few percent of users
Rollback Another rolling update, as slow as the first Switch back: seconds Set the new version's share to zero: seconds
Extra capacity A few instances at a time A whole second environment while both run A few instances
Old and new serve users together For the whole rollout Only while blue drains For the whole canary
What it needs Nothing beyond Kubernetes' default Deployment A switch you control, and room for two environments Weighted routing and metrics you trust

Who Meets a Bad Release

The table makes blue-green sound strictly better than a rolling update. It isn't. Because everyone moves at once, every request meets a bug that your tests missed, until someone notices it. The figure below puts numbers on that: a service handling 1,000 requests a minute, a release with a bug at minute 10, and a time to notice that you control. The shaded area is the requests that met the bug.

Forty minutes of a service answering 1,000 requests a minute. At minute 10 a release with a bug starts; the line is the share of requests sent to it until the bug is noticed and rolled back. A rolling update swaps ten pods one a minute and rolls back the same way; blue-green moves everyone at once and back in seconds; a canary sends 5% for ten minutes, then 25%, 50% and all, and drops to none in seconds. Noticed after 5 minutes, 3,000 requests meet the bug in a rolling update, 5,083 in blue-green, 254 in a canary. After 15, rolling is worst: 16,000.

Who meets a bad release

Which Strategy Should You Pick?

With five minutes to notice, blue-green exposes about 5,100 requests, a rolling update 3,000 and a canary about 250. Blue-green loses on exposure because it sends everyone at once. But look at the other number in the status line: blue-green is back in five seconds, while the rolling update takes five minutes to roll back. Push the time to notice up to 15 minutes and the rolling update becomes the worst of the three, at 16,000 requests, because rolling back takes as long as rolling out.

The figure gives every strategy the same time to notice, which flatters the canary a little. In practice, a canary is checked by comparing its metrics with the stable version's, which is what lets a few percent of traffic reveal a bug at all.

So each strategy protects you at a different moment:

  • Blue-green protects you before the switch, by testing a full copy of production, and after it, with an instant rollback. It suits releases you can test well before users see them, and services where old and new versions must not serve users at the same time.
  • Canary protects you during the release, by limiting how many users meet a new version. It suits high-traffic services with good metrics, where a few percent of traffic is enough to spot a problem.
  • Rolling update is the simple default. It needs no extra infrastructure and works well for small, backward-compatible changes.

The two ideas also combine. If your router supports weights, you can shift traffic from blue to green in steps (5%, 25%, 100%) and still keep blue fully up for an instant rollback. Many teams call this a blue-green deployment with a canary-style shift.

Blue-Green Deployment in Kubernetes

Kubernetes has no blue-green setting. Its Deployment object does rolling updates. But its building blocks make blue-green straightforward: a Service sends traffic to whichever pods match its label selector, so changing the selector is the switch.

Two Deployments and One Service

Run each colour as its own Deployment, with a version label that says which colour it is:

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-green
spec:
  replicas: 4
  selector:
    matchLabels:
      app: web
      version: green
  template:
    metadata:
      labels:
        app: web
        version: green
    spec:
      containers:
      - name: web
        image: registry.example.com/web:1.5.0
        ports:
        - containerPort: 8080
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8080

web-blue is the same file with blue in the name and labels and the image web:1.4.0. Give green the same replica count as blue, so it can take all the traffic at once.

Then add two Services. web is the one users reach, through your Ingress or Gateway, and it selects the live colour. web-preview selects the idle colour, for testing:

yaml
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
    version: blue   # the live colour
  ports:
  - port: 80
    targetPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: web-preview
spec:
  selector:
    app: web
    version: green  # the colour being tested
  ports:
  - port: 80
    targetPort: 8080

The web Service selects pods labelled version: blue; kubectl patch changes its selector to green, while web-preview reaches green for smoke tests.

Switching and Rolling Back with kubectl

With green deployed, wait for it to be ready and test it through the preview Service:

bash
kubectl rollout status deployment/web-green
kubectl port-forward service/web-preview 8080:80
curl -fsS http://localhost:8080/healthz   # in another terminal

When green passes, switch the live Service. A strategic merge patch changes only the version key and keeps app: web:

bash
kubectl patch service web -p '{"spec":{"selector":{"version":"green"}}}'

That patch is an ordinary write to the cluster, checked and stored like any other; Kubernetes API Server Explained follows such a request all the way to etcd. Within seconds, the Service's EndpointSlices list only green's pods, and new connections go to green. Confirm it:

bash
kubectl get endpointslices -l kubernetes.io/service-name=web

To roll back, run the same patch with blue. Once you are confident in green, and the rollback window has passed, scale blue down. It becomes the target for the next release:

bash
kubectl scale deployment web-blue --replicas=0

Tip

Put the version label in the Deployment's selector, as above, not only in the pod template. A Deployment's selector can't be changed after it is created, and two Deployments whose selectors overlap would fight over the same pods.

Open Connections Outlive the Switch

Changing a Service's selector decides where new connections go. A connection that is already open, such as an HTTP keep-alive connection in a client's pool, a gRPC channel or a WebSocket, stays with the pod it was opened to. So blue can keep serving some clients for a while after the switch, and those clients see the old version.

Plan for it:

  • Keep blue running for a drain window after the switch, rather than deleting it at once.
  • Close idle connections on shutdown. When blue's pods are eventually stopped, the application should finish in-flight requests and close keep-alive connections, so clients reconnect, and land on green.
  • Set a sensible terminationGracePeriodSeconds (30 seconds by default) so Kubernetes gives each pod time to drain before it is killed.

Automating It with Argo Rollouts

Patching selectors by hand is fine to learn with. For real releases, a controller makes the steps repeatable. Argo Rollouts replaces the Deployment with a Rollout that has a blueGreen strategy:

yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: web
spec:
  replicas: 4
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: registry.example.com/web:1.5.0
  strategy:
    blueGreen:
      activeService: web            # receives users' traffic
      previewService: web-preview   # reaches the new version before promotion
      autoPromotionEnabled: false   # wait for a person to promote
      scaleDownDelaySeconds: 600    # keep the old version up for 10 minutes

When you change the image, Argo Rollouts creates a new ReplicaSet, points web-preview at it, and waits until its pods are available. It switches traffic by adding a hash of the ReplicaSet to each Service's selector, the same switch you made by hand. With autoPromotionEnabled: false it pauses until someone runs kubectl argo rollouts promote web. After promotion it keeps the old ReplicaSet for scaleDownDelaySeconds (30 seconds by default) before scaling it down.

It can also check the release for you: prePromotionAnalysis runs queries against your metrics before the switch, and a failed postPromotionAnalysis after the switch aborts the rollout and sends traffic back to the old version. That turns the "Watch" and "Roll back" steps into code.

The Hard Part: Databases and State

Blue and green are two copies of your application, but they usually share one database. That is where most blue-green releases go wrong: for a while, both versions read and write the same tables, and after a rollback, the old version has to work with whatever the new one wrote.

Change the Schema in Three Releases

The rule is simple to say: every schema must work with both the version before it and the version after it. In practice that means splitting a breaking change, like renaming a column, into steps that are each backward compatible. This pattern is called expand and contract, or parallel change.

Say v1.4 stores a user's name in name, and you want full_name:

  1. Expand. Add full_name alongside name. v1.4 ignores it. Ship this schema change on its own.
  2. Migrate. Release v1.5 through blue-green. It writes both columns and reads full_name, falling back to name. Backfill old rows. If you roll back, v1.4 still finds name filled in.
  3. Contract. Only after v1.4 is gone for good, and nothing reads name anymore, drop it in a later release.

Fowler gives the same advice: separate schema changes from application releases, so each one can be rolled back on its own.

Renaming a column in three releases: expand adds full_name, migrate switches to v1.5 writing both columns, contract drops name once v1.4 is gone.

Sessions, Queues and Scheduled Jobs

The database isn't the only shared state. Check these before your first switch:

  • Sessions. If sessions live in the memory of blue's instances, the switch signs everyone out. Keep them in a shared store such as Redis, or use stateless tokens.
  • Queue consumers. If both colours run workers, both consume from the same queues during the release, and an old worker may meet a message in a new format. Either make messages backward compatible or run workers in only one colour at a time.
  • Scheduled jobs. A cron job that exists in both environments runs twice. Run scheduled work from one place, or make it safe to run twice.
  • Caches. A cold green can be slow for its first minutes. Warm its caches, or expect a short latency bump after the switch.

Warning

A rollback restores the old code, not the old data. If v1.5 wrote rows that v1.4 can't read, switching back can cause errors of its own. Test the rollback path, not just the release.

Pros and Cons of Blue-Green Deployment

Advantages:

  • Instant rollback while the old environment is still running.
  • Testing in production conditions before any user sees the new version.
  • No mixing of versions for users, apart from the short drain window.
  • Rehearsed releases. Every release exercises the same switch, which also proves you can fail over to a standby environment.

Disadvantages:

  • Double capacity while both environments run, and more if you keep blue up for a long rollback window.
  • Shared state means schema and message changes must work with both versions.
  • Everyone moves at once, so a bug that testing missed reaches every user until it is noticed.
  • More moving parts to own: a switch, a preview route, draining, and someone watching the dashboards.

When to Use Blue-Green (and When Not To)

Blue-green is a good fit when:

  • Downtime or a slow rollback costs real money or trust.
  • Old and new versions shouldn't serve users at the same time, for example when an API or a front end changes in a way that doesn't mix.
  • You can build a realistic copy of production and test it before the switch.
  • You can afford a second environment for the length of the release.

Look elsewhere when:

  • Capacity is tight and you can't run two full environments: use a rolling update.
  • You want to limit how many users meet a new version: use a canary, or shift traffic between blue and green in steps.
  • The thing you are releasing is the state, such as a database server: blue-green suits stateless services in front of it.
  • Your schema changes can't be made backward compatible.

A Blue-Green Release Checklist

Before you rely on blue-green in production, make sure you can tick every line:

  • Green runs the same artifact and configuration as production, apart from the version.
  • Readiness and health checks must pass before the switch.
  • Smoke tests run against green through a private route, such as a preview Service.
  • The schema works with both versions; breaking changes use expand and contract.
  • Dashboards and alerts show error rate and latency per colour, and someone watches them after the switch.
  • Blue keeps running for a drain window, and the application closes connections cleanly on shutdown.
  • The rollback is one command or one click, and the team has practised it.
  • Queue consumers and scheduled jobs run safely while both colours are up.
  • Blue is scaled down or recycled after the rollback window, so you don't pay for two environments forever.

Key Takeaways

  • Blue-green deployment runs two identical environments and moves all traffic from one to the other with a single switch.
  • The old environment stays up, so a rollback is the same switch in reverse and takes seconds.
  • The switch only redirects new requests: drain in-flight requests and open connections before stopping blue.
  • Put the switch in a load balancer, a Kubernetes Service or a gateway; DNS is too slow to roll back reliably.
  • Blue-green sends everyone to the new version at once, so test green well; a canary limits how many users meet a bad release.
  • In Kubernetes, run two Deployments and switch a Service's selector, or let Argo Rollouts do it.
  • Shared databases are the hard part: change schemas in backward-compatible steps with expand and contract.

FAQ

What is blue-green deployment in simple terms?

You run two copies of your application. One serves users while you put the new version on the other and test it. Then you point all traffic at the new copy. If anything goes wrong, you point it back.

Is blue-green deployment really zero downtime?

It can be. The switch itself takes seconds and needs no restart. Requests are only lost if the old environment stops before its in-flight requests finish, or if shared state such as sessions or the database schema doesn't work with both versions.

What is the difference between blue-green and canary deployment?

Blue-green moves all traffic to the new version at once and keeps the old version ready for an instant rollback. A canary sends a small share of traffic to the new version first and increases it while metrics look healthy, so fewer users meet a bad release. You can combine them by shifting traffic between blue and green in steps.

Does blue-green deployment double infrastructure costs?

Only while both environments run. Many teams start green just before a release and scale blue down after a rollback window, so the extra cost lasts minutes or hours rather than the whole month. In the cloud or on Kubernetes, that is often cheap compared with the cost of a slow rollback.

How do you handle database migrations in blue-green deployment?

Make every schema change backward compatible, so both the old and new versions work with it. Split breaking changes into expand, migrate and contract steps, and ship schema changes separately from application releases.

Does Kubernetes support blue-green deployment natively?

Not as a setting: Deployments use rolling updates. But you can build blue-green from two Deployments and a Service whose selector you change, or use a controller such as Argo Rollouts, which has a blueGreen strategy with preview Services, manual promotion and automated analysis.

What happens to in-flight requests during the switch?

They finish on the environment that started them, as long as it is still running. That is why you keep blue up for a drain window after the switch, and why long-lived connections, which keep going to blue until they close, need a graceful shutdown.

Further Reading

On the roadmap


Comments

No comments yet.