irfan@backend:~/portfolio
Email me
← cd ../blog

Deployment / DevOps / Kubernetes / Beginner

Ship Without Fear: deploy strategies from recreate to feature flags

A beginner guide to deploy strategies in one post: recreate, rolling, blue/green, canary, shadow traffic, feature flags and safe database changes.

On this page
  1. Deploy words
  2. Recreate
  3. When recreate is the right pick
  4. Rolling update
  5. The two settings and their defaults
  6. When a new pod fails its health check
  7. What zero downtime needs
  8. Blue/green
  9. When to use blue/green
  10. Switch at the load balancer, not in DNS
  11. The database is shared
  12. Red/black is the same thing
  13. Canary
  14. When to use canary
  15. Shadow traffic
  16. When to use shadow traffic
  17. The danger: the shadow does real work
  18. Feature flags
  19. When to use feature flags
  20. OpenFeature: one API for every flag tool
  21. A/B test or canary
  22. Expand and contract
  23. When to use expand and contract
  24. Picking a strategy
  25. Blue/green, canary and shadow side by side
  26. The decision tree
  27. Your platform may already pick for you
  28. Recap

You push a new version, restart the server, and for ten seconds every user gets an error page. Or the new version has a bug, and you have no quick way back. How you deploy decides both of these things, and most teams pick a strategy by accident.

This post follows one small online shop. Its version 2 is ready, and each chapter ships one piece of v2 in a different way:

api runs as 4 pods (4 running copies of the app, more in the Recreate chapter). The load balancer sends each request to one of them. The job queue holds work for report-worker.

Piece of the shopWhat v2 changesChapter
report-workernew report codeRecreate
api, 4 podsa new version, and users must not see errorsRolling update, Blue/green, Canary: three ways to ship the same api
searchrewritten from zeroShadow traffic
checkout pagea new design, launched on a day marketing picksFeature flags, A/B test or canary
users tablename becomes full_nameExpand and contract

After this post you can:

  • pick between a recreate deploy and a rolling update, and know what zero downtime needs
  • roll back in one command with blue/green, test on a few users with a canary, and use shadow traffic safely
  • ship code switched off with a feature flag, change a database while two versions run, and pick a strategy for your own app

Deploy words#

Start with the simplest deploy there is, the one the shop used before Kubernetes. One server runs the app. You copy the new code and restart it:

scp app.tar.gz server:/srv/app/
ssh server "cd /srv/app && tar xzf app.tar.gz && systemctl restart app"

scp copies the file to the server. ssh runs the unpack and the restart there. Watch what one user sees during that restart:

restart-deploy
  1. A user opens the shop.
  2. The app restarts. It can't answer.
  3. The proxy sends back an error.
  4. Worse: the new code crashes on start.
  5. The errors keep coming.
  6. They stop only when you copy the old code back.
step 1 / 6
Two problems in one deploy: users get errors, and the way back is by hand.

The error is often a 502 or 503. Those are HTTP codes the proxy sends back when the app behind it fails or can't answer. A proxy is a server like Nginx that sits in front of your app and passes requests to it.

That small example already has most of the words in this post:

  • Deploy: putting a new version of your code on the servers.
  • Release: letting users see a new feature. The Feature flags chapter shows why these two are different.
  • Downtime: time when users get errors or no answer because of the deploy.
  • Zero downtime: a deploy where no user request fails.
  • Rollback: going back to the old version when the new one is broken.
  • Load balancer: the piece in front of your servers that sends each request to one of them. Like a proxy, but it spreads requests over many servers.
  • Health check: an automatic test, like a request to /healthz, that says if a server is ready for traffic.
  • Blast radius: how many users a bad deploy can hurt.
  • Staging: a copy of your app for testing, with no real users.

Each strategy in this post gives you some of these and costs you others. A strategy that gives zero downtime and a fast rollback usually costs more servers or more setup. A cheap and simple strategy usually has more downtime or a bigger blast radius.

quick-check

Your new version crashes on start. You copy the old code back and restart. What did you just do?

quick-check

A bad deploy only reaches 5% of users. What is small?

Recreate#

The first piece of v2 is report-worker, a background worker: it takes jobs from a queue and builds reports. The shop runs it on Kubernetes.

What do you think happens to users if you stop all servers before the new ones start?

Words you need:

  • Container image: a package of your app and everything it needs to run, like report-worker:2.0.0.
  • Container: one running copy of an image.
  • Kubernetes: a system that runs your containers on many machines. You talk to it with the kubectl command.
  • Pod: one running instance of your app in Kubernetes (one or more containers).

A Kubernetes Deployment keeps a number of pods of your app running, and its strategy field says how it replaces old pods with new ones. Here it is Recreate:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: report-worker
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: report-worker
  template:
    metadata:
      labels:
        app: report-worker
    spec:
      containers:
        - name: worker
          image: registry.example.com/report-worker:2.0.0
  • replicas: how many pods to keep running.
  • Labels are name tags. The selector picks pods by those tags. That is how the Deployment knows which pods belong to it.
  • template: the recipe for each pod, like which image to run.

When you change the image, Kubernetes first stops every old pod. It waits until they are gone. Only then does it start the new pods:

recreate-deploy
  1. The v1 worker pod is running jobs.
  2. You change the image to v2.
  3. Kubernetes stops v1 and waits until it is gone.
  4. No pod is running. No jobs get done: downtime.
  5. Only now the v2 pod starts.
  6. The v2 pod runs jobs again.
step 1 / 6
The gap between stop and start is your downtime. For an app that serves users, those are failed requests.

When recreate is the right pick#

The downtime is the cost. You get two things back. It is the simplest strategy. And during a deploy, old and new versions never run at the same time.

Use recreate when:

  • Downtime does not matter: a dev or staging environment, or an internal tool where a short gap is fine.
  • Two versions must not run together: for example, a worker that runs a scheduled job. Two copies would run the job twice.
  • It is an early product with almost no users. A few seconds of downtime at a quiet hour is a fair price for a simple setup.

The "never two at once" promise holds only during a deploy. If someone deletes the pod by hand, Kubernetes starts a replacement at once, so for a moment two pods can run.

Need a strict "never more than one" rule? The Kubernetes docs point to a StatefulSet for that. It is a Kubernetes object for pods that need a stable name and identity. It gives an "at most one" guarantee per pod.

Many guides say "never use recreate in production". That is too strong. The better rule: use recreate when downtime is acceptable or when two versions running at once would break something. For a public app where users expect it to always work, pick a rolling update instead (next chapter).

quick-check

You run one pod that sends a daily email to all users. Two copies would send it twice. Which strategy fits?

Rolling update#

The shop's api is that public app. It runs 4 pods, and users call it all day. Kubernetes uses a rolling update by default, but this example sets the two settings by hand so you can see them:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 4
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: registry.example.com/api:2.0.0
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
            periodSeconds: 5

Three parts do the work:

  • maxSurge: 1: Kubernetes may run 1 extra pod above the 4 you asked for.
  • maxUnavailable: 0: Kubernetes may never have fewer than 4 ready pods.
  • readinessProbe: the health check. A pod gets traffic only after /healthz answers with success.

The rollout is the whole process of moving from v1 to v2. Follow the pods during it:

rolling-update
  1. Start: 4 pods on v1, all ready.
  2. Kubernetes starts 1 v2 pod: 5 pods (maxSurge 1).
  3. The v2 pod passes its readiness probe and gets traffic.
  4. Only now 1 v1 pod stops. Back to 4 ready.
  5. Repeat: start v2, wait for ready, stop v1.
  6. Done: 4 pods on v2. Never fewer than 4 ready.
step 1 / 6
New pod first, old pod second. That order is what keeps the service up.

A common mistake is to think Kubernetes takes an old pod offline first, then puts the new one in its place. With maxUnavailable: 0, it is the other way around. The new pod must be ready before an old pod goes away.

The two settings and their defaults#

If you leave the settings out, both default to 25% of replicas. Kubernetes rounds maxSurge up and maxUnavailable down. That matters when 25% is not a whole pod. With 3 replicas, 25% is 0.75, so maxSurge becomes 1 and maxUnavailable becomes 0.

SettingWhat it limitsDefaultWith 4 replicas
maxSurgeextra pods above replicas25%, rounded upup to 5 pods
maxUnavailablepods allowed to be down25%, rounded downat least 3 ready

So with the defaults and 4 replicas, Kubernetes may stop one old pod right away, before any new pod is ready. For a small app that means 25% less capacity during the deploy.

If your pods are busy, set maxUnavailable: 0. The deploy takes longer, but you never drop below full size. You can't set both settings to 0, because then Kubernetes could never move.

quick-check

replicas: 4, maxSurge: 1, maxUnavailable: 0. How many ready or starting pods can there be at one time?

When a new pod fails its health check#

Say v2 has a bug, and /healthz never answers with success. What happens?

stuck-rollout
  1. The first v2 pod never becomes ready.
  2. It gets no traffic. Users keep using v1.
  3. maxUnavailable 0: Kubernetes never stops a v1 pod.
  4. The rollout is stuck. No pause, no rollback by itself.
  5. After the deadline: ProgressDeadlineExceeded. Only a status.
  6. You roll back yourself.
step 1 / 6
A failed probe stops the bad version from spreading. Rolling back is still your job.

The deadline is progressDeadlineSeconds (default 600, so 10 minutes). After it, Kubernetes marks the Deployment with the reason ProgressDeadlineExceeded. That is only a status. It still does not roll back, so you do:

kubectl rollout status deployment/api   # watch the rollout, it fails after the deadline
kubectl rollout undo deployment/api     # go back to the previous version

A CI/CD pipeline (the automatic build, test and deploy steps) can watch that status. It can run the undo for you. Kubernetes alone does not.

Rollback is slow, because undo is another rolling update. Blue/green is the faster way back.

quick-check

Your v2 pods fail their readiness probe. With maxUnavailable: 0, what do users see?

What zero downtime needs#

A rolling update alone does not give you zero downtime. Three things must be true.

1. A real health check. The readiness probe must only pass when the app can serve requests (for example, after it connected to the database). Without a probe, Kubernetes counts a pod as ready the moment its container starts.

2. A clean shutdown. When Kubernetes stops a pod, it sends the signal SIGTERM (a message from the system that means "please stop now"). It waits up to 30 seconds by default (terminationGracePeriodSeconds), then kills the pod. Your app should stop taking new connections, finish the requests it has, then exit. In Node.js:

const server = app.listen(8080);

process.on('SIGTERM', () => {
  // stop new connections, finish open requests, then exit
  server.close(() => process.exit(0));
});

This handler only runs if Node gets the signal. Start Node directly (node server.js), not through npm start or a shell, because they may not pass the signal on to Node.

There is one catch. Kubernetes removes the pod from the load balancer at the same time as it starts the shutdown. So a few new requests can still arrive just after SIGTERM. A short preStop hook fixes this. Kubernetes runs it before it sends SIGTERM:

lifecycle:
  preStop:
    exec:
      command: ['/bin/sh', '-c', 'sleep 5']   # needs a shell in the image

The 30 seconds begin when Kubernetes starts to stop the pod. So sleep 5 uses 5 of them, and the app has 25 left.

clean-shutdown
  1. Kubernetes starts to stop the pod. Two things happen at once.
  2. One: the load balancer drops the pod.
  3. Two: the pod runs preStop, sleep 5.
  4. The drop takes a moment to spread, so a few requests still arrive. The pod serves them.
  5. After 5 seconds, SIGTERM arrives.
  6. The app finishes open requests, then exits.
  7. Still running 30 seconds after the stop began? Kubernetes kills it.
step 1 / 7
preStop keeps the pod serving while traffic moves away. Then SIGTERM closes it cleanly.

3. Old and new versions work side by side. During the rollout, some requests hit v1 and some hit v2. If v2 changes the API or the database in a way v1 can't handle, users get errors. Expand and contract shows how to change a database safely for this.

One more trap, on top of the three: a stateful app keeps user data in memory, like a login session. When the pod stops, its memory is lost, and that user is logged out. A stateless app keeps that data in a database or cache (a fast store for data you read often), so any pod can answer any request.

Each rule closes one gap. The probe guards the start of a pod. The shutdown guards the end. Compatibility guards the time in between.

Quick check: your rolling update shows no failed pods, but users still see a few errors during every deploy. Name two likely causes.

Show answer

The app may not handle SIGTERM, so it drops the requests it was serving. There may be no preStop delay, so requests arrive after the shutdown started. The readiness probe may pass too early, so new pods get traffic before they can answer. Or v1 and v2 are not compatible, so some requests fail while both run.

quick-check

Your app keeps each user's login session in the pod's memory. What happens during a rolling update?

Blue/green#

A rolling update keeps the api up, but two things still hurt. Its rollback is slow, and every user gets the new version by the end. The api also takes the shop's payments, so every minute of a broken version means failed payments.

Words you need:

  • Environment: a full set of servers (or pods) that can run the whole app.
  • Service: in Kubernetes, the stable address in front of pods. It sends each request to a pod that matches its selector (a label filter).
  • Cutover: the moment traffic moves from the old version to the new one.

You run two Deployments of the same app. One has the label version: blue and runs v1. The other has version: green and runs v2. One Service sits in front:

apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  selector:
    app: api
    version: blue
  ports:
    - port: 80
      targetPort: 8080

Right now the selector says blue, so every request goes to v1. Green is already running v2, fully started, with zero users. You test green directly, through a second Service only your team can reach. When it looks good, you change one label with kubectl patch (a command that edits one field of a live object):

kubectl patch service api -p '{"spec":{"selector":{"app":"api","version":"green"}}}'
blue-green-switch
  1. Blue runs v1 and gets all the traffic.
  2. You deploy v2 to green. Green gets no traffic.
  3. You test green directly and it passes.
  4. Cutover: you switch the Service selector to green.
  5. Green gets the traffic. Blue stays running.
  6. Bug found? Switch the selector back to blue.
step 1 / 6
Both environments are production. Only one gets traffic at a time.

New connections now go to green. A connection that is already open (HTTP keep-alive or gRPC, which reuse one connection for many requests) may stay on blue until it closes.

If v2 is broken, the rollback is the same command with blue. No pods need to start, so rollback is one command.

When to use blue/green#

Use it when a bad release is expensive and you need to go back fast. A payment API, like the shop's api, is the classic case.

Two things trip people up:

  • Green is production, not staging. It runs on production servers with production config and the production database. It just has no users yet. That is why testing it tells you something real.
  • You pay for two of everything during the deploy. You can shut blue down once green has been fine for a while.

Switch at the load balancer, not in DNS#

Some guides say "flip the DNS record to green". DNS is the system that turns a name like api.example.com into an IP address. It is a slow switch.

Clients and DNS servers keep the old answer for the record's TTL (time to live, how long an answer may be cached). Some keep it even longer. So some users stay on blue long after you "switched". A rollback has the same delay.

dns-switch
  1. You point the DNS record at green.
  2. A user asks for the address of api.example.com.
  3. The cache still holds the old answer: blue.
  4. So this user still lands on blue.
  5. Only after the TTL does the cache ask the DNS server again.
  6. Now the user reaches green. A rollback waits the same way.
step 1 / 6
A DNS switch reaches each user only when their cached answer runs out.

AWS's own blue/green guide names this caching as the main risk of DNS switching. Switch where the traffic is routed instead: the load balancer, the Kubernetes Service, or your platform's traffic setting.

The database is shared#

Blue and green normally use the same database. So when green goes live and you switch back to blue, blue must still work with whatever green wrote. A schema change that breaks v1 also breaks your rollback. Expand and contract shows the safe way to change a database for this.

Red/black is the same thing#

Netflix called this pattern red/black. Spinnaker, the deploy tool Netflix built, renamed its red/black strategy to blue/green in version 1.30. If you see "red/black", read it as blue/green.1

quick-check

You switch from blue to green by changing a DNS record. Ten minutes later, some users still hit blue. Why?

quick-check

Green has been live for an hour. It wrote new rows in a new format. You switch back to blue. What can go wrong?

Canary#

The shop's api v2 also has a new query on a busy table. Staging can't fully test that. Only real users and real load can.

What do you think is safer: 100% of users on a new version for 1 minute, or 5% of users for 1 hour?

Words you need:

  • Metric: a number you measure all the time, like the share of requests that fail.
  • Metric gate: an automatic check on a metric that decides if the rollout may go on.

Plain Kubernetes Deployments can't send "5% of traffic" to a new version. Tools like Argo Rollouts add that. For an exact share, Argo Rollouts steers a traffic router (explained below). Here are the steps of an Argo Rollouts Rollout (the rest of the file looks like a Deployment):

strategy:
  canary:
    steps:
      - setWeight: 5
      - pause: { duration: 30m }
      - analysis:
          templates:
            - templateName: success-rate
      - setWeight: 25
      - pause: { duration: 30m }
      - analysis:
          templates:
            - templateName: success-rate
      - setWeight: 50
      - pause: { duration: 30m }
StepWhat it does
setWeightsets the share of traffic for the new version
pausewaits, so the metrics can collect data
analysisruns the metric gate, here a template named success-rate
end of the listthe new version gets 100%
canary-rollout
  1. 5% of traffic goes to v2. 95% stays on v1.
  2. Wait 30 minutes. Success rate at least 95%?
  3. Pass: grow to 25%, wait, check again.
  4. Pass: grow to 50%, wait, check again.
  5. Pass: v2 gets 100%. Done.
  6. Fail at any check: all traffic goes back to v1.
step 1 / 6
The metric gate decides each step. A human does not have to watch the graphs.

The success-rate template is a separate file you write once. It asks your metrics system (for example, Prometheus) a question like "is the share of successful requests at least 95%?". Writing that query is out of scope here. The Argo Rollouts analysis docs show a full example.

If the check fails, Argo Rollouts aborts. All traffic goes back to the old version.

An exact share like 5% needs a traffic router: a piece that can send an exact share of requests to each version. Two common kinds:

  • Service mesh: a layer, like Istio, that controls all traffic between your services.
  • Ingress controller: the entry point that takes outside traffic into the Kubernetes cluster (your group of Kubernetes machines).

Without a traffic router, Argo Rollouts sets the share by changing how many pods run each version. With 10 pods, 10% means 1 new pod and 9 old ones.

Back to the question at the start: usually the 5% is safer. A bad version on 100% hits everyone, even if only for a minute. On 5% it hits few users, and the hour gives you enough data to see the problem.

When to use canary#

Use canary for a change you can't fully test before release, like a big performance change or a new query on a busy table. Real users find what staging missed, and only a few of them see it.

Canary needs two things:

  • Enough traffic to measure. If 5% of your traffic is 3 requests an hour, an error rate means nothing. Small apps can start with a bigger first step or use blue/green instead.
  • Metrics you trust. Error rate and latency (how long a request takes) per version.
quick-check

Your canary is at 25%. The success rate check fails. What happens next?

quick-check

Your app gets 200 requests a day. Is a 5% canary a good first step?

Shadow traffic#

The shop's search v2 is a full rewrite. Before any user depends on it, you want to see it under real load.

Words you need:

  • Endpoint: one URL and method of your API, like GET /search.
  • VirtualService: an Istio config that says where requests for a service go.
  • Subset: a named group of pods of one service, like "the v2 pods". A separate Istio config, the DestinationRule, defines it with labels.

Istio can copy every request to a second version. This config sends users to v1 and a copy of each request to v2:

apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: search
spec:
  hosts:
    - search
  http:
    - route:
        - destination:
            host: search
            subset: v1
          weight: 100
      mirror:
        host: search
        subset: v2
      mirrorPercentage:
        value: 100.0
shadow-traffic
  1. A user searches for shoes.
  2. The proxy sends the request to v1.
  3. At the same time, it sends a copy to v2.
  4. The user gets v1's answer.
  5. v2's answer is thrown away. Only logs and metrics stay.
step 1 / 5
Nobody sees v2's answers. You only compare its numbers against v1.

Istio calls the copy "fire and forget": it sends the copy and never waits for the answer. v2's responses are thrown away. The user only ever sees v1's answer. You compare v2's logs, errors and latency against v1.

When to use shadow traffic#

Use it when you rewrite a service and want to see it under real load before any user depends on it. For example, a new search service in a new language, or a new ranking model. You check that v2 gives the same answers as v1, and that it is fast enough.

The danger: the shadow does real work#

Many guides call shadow traffic "zero risk". It is not. The user never sees v2's answer, but v2 still runs the request. Whatever the code does, it does for real:

  • A POST /orders copy writes a second order to the database.
  • A sign-up copy sends the welcome email a second time.
  • A checkout copy calls the payment provider and charges the card twice.

So before you mirror anything, cut off every side effect in the shadow:

  • Point v2 at its own database, or a copy, never the production one.
  • Replace the email, payment and other outside calls with fakes that only log.
  • Start with read-only endpoints (search, GET requests). They are the safest to mirror.

Shadow traffic also doubles the load on everything v2 touches. Plan for that before you set mirrorPercentage to 100.

Quick check: you mirror the payment route of the shop's api to a new version. The new version has the real API key for Stripe (a payment provider), so it can take real payments. What happens when a user buys something?

Show answer

The user is charged twice: once by v1 (the real answer) and once by v2 (the shadow). The user only sees v1's answer, but v2's call to Stripe is real. Give the shadow a fake payment client before you mirror payments.

quick-check

Which endpoint is the safest to start shadowing?

Feature flags#

Every strategy so far moves a whole new version of the app. Often you want something smaller: turn off one broken feature, or launch one feature on a set day.

The shop's new checkout page is done. Marketing wants to launch it in two weeks. You don't want that code waiting on a branch for two weeks, so you merge and deploy it today, switched off.

Words you need:

  • Feature flag (or feature toggle): an on/off switch in your code that you change without a deploy.
  • Flag tool: the service where you turn flags on and off, and choose who gets them.
  • Provider: the small adapter that connects your code to one flag tool.
  • Kill switch: a flag whose job is to turn a feature off fast when it breaks.
import { OpenFeature } from '@openfeature/server-sdk';

// once at startup: plug in the provider for your flag tool
try {
  await OpenFeature.setProviderAndWait(new YourProviderOfChoice());
} catch (err) {
  console.error('flag provider failed to start, flags use their defaults', err);
}
const flags = OpenFeature.getClient();

// inside your request handler
async function checkout(user) {
  const useNewCheckout = await flags.getBooleanValue('new-checkout', false, {
    targetingKey: user.id, // who is asking, so the flag tool can pick per user
  });
  return useNewCheckout ? renderNewCheckout(user) : renderOldCheckout(user);
}

The new code is on every server, but nobody sees it:

  • setProviderAndWait connects your code to the flag tool once, at startup.
  • getBooleanValue('new-checkout', false, ...) asks: new checkout for this user? The flag tool decides who gets true.
  • false is the default. If the flag tool can't answer, users get false, so the old checkout. The same happens when the provider failed at startup. That is the safe side.
  • targetingKey says who is asking, so the flag tool can pick per user.

Here is the life of that flag:

flag-lifecycle
  1. Deploy: the new checkout is on every server, flag off.
  2. Turn it on for your team. Test in production.
  3. Turn it on for a few beta customers.
  4. Launch day: on for everyone. No deploy needed.
  5. A bug shows up? Turn it off. Old checkout in seconds.
  6. Fixed and stable: delete the flag and the old code.
step 1 / 6
Deploy happens once, at step 1. Every other step is a switch.

When to use feature flags#

Flags are how you split deploy from release. Deploy is a technical step: the code goes on the servers. Release is a business step: users see the feature. Use flags when:

  • The launch date is set by the business, not by the deploy.
  • You want to test a feature on your own team or a few customers first.
  • You want a kill switch for a risky feature. Turning a flag off is faster than any rollback or hotfix (a quick, small deploy that fixes a bug in production). It also only touches that one feature.

Flags have a cost. Every flag is an if with two paths to test. Old flags that nobody removes pile up into code nobody understands. Delete each flag once its feature is fully on and stable (the last step above).

OpenFeature: one API for every flag tool#

There are many flag tools. Some you buy, some you host yourself. Each has its own SDK (the library you call from code).

OpenFeature is an open standard for that API. You write getBooleanValue once and plug in the provider for your tool. Changing tools later means changing the provider, not every if in your code.

OpenFeature is a CNCF project. CNCF is the foundation behind Kubernetes. OpenFeature has been at the "incubating" level (past the early stage, not yet fully mature) since November 2023.

quick-check

The new checkout has a bug in production. The flag is on for everyone. What is the fastest fix for users?

quick-check

The flag tool is down. What does getBooleanValue('new-checkout', false, ...) return?

A/B test or canary#

Marketing has one more ask for the new checkout. Does "Buy now" sell more than "Add to cart"?

Each button text is a variant (one version in the test). You put each user in group A or group B, 50/50, and keep them in that group on every visit. After enough orders, you compare the share of visits that end in a purchase (the conversion rate) for each group.

ab-test-groups
  1. User 7 opens the checkout.
  2. The flag tool puts user 7 in group A.
  3. Next day, user 7 comes back.
  4. Same user, same group: A again.
  5. User 8 lands in group B, and stays there.
  6. After enough orders, compare the conversion rate of A and B.
step 1 / 6
Each user always sees the same button, so each group's numbers stay clean.

That is an A/B test. Both versions work fine. You want to learn which one is better. A canary asks something else: is the new version broken? You start small (5%) to keep the blast radius small, and you watch errors and latency. Both send some users to one version and the rest to another, but they answer different questions:

CanaryA/B test
Questionis the new version stable?which version works better for users?
Splitsmall share first, then growfixed split, often 50/50
Same user, same group?not neededyes, every visit
Metricerrors, latencyconversion, clicks, time on page

An A/B test needs enough users in each group, or the difference between A and B is just noise. The flag tool puts each user in a group by targetingKey. The user stays in that group.

quick-check

You want to know if a new pricing page brings more sign-ups. Which one do you run?

Expand and contract#

The last piece of v2 is the database. The shop wants to rename users.name to users.full_name. Every strategy above breaks if the new version changes the database in a way the old one can't read.

What do you think happens to the old pods during a rolling update if the new version renames a column?

Words you need:

  • Schema: the shape of your database: tables, columns and their types.
  • Migration: a script that changes the schema, like adding a column.
  • Nullable: a column that may be empty (NULL).
  • Lock: the database blocks other work on a table while it changes it.

The obvious way is one migration:

ALTER TABLE users RENAME COLUMN name TO full_name;
one-step-rename
  1. The migration renames name to full_name.
  2. New pods read full_name. Fine.
  3. Old pods are still running. They still read name.
  4. name no longer exists, so the old pods fail.
  5. You roll back: every pod runs the old code again. Still no name, still failing.
step 1 / 5
During a rolling update both versions run, so one rename breaks the old one.

The safe way is to split the change into steps. In this chapter, v1 is the api running today, and v2, v3 and v4 are the three small deploys that follow. After each step, both the running version and the one before it still work:

-- Step 1, expand: add the new column. v1 ignores it.
ALTER TABLE users ADD COLUMN full_name text;

-- Step 2: deploy v2. It writes to name AND full_name, still reads name.

-- Step 3, backfill: copy old rows in small batches.
-- IS DISTINCT FROM (not equal, and NULL counts as a value)
-- also catches rows v1 changed during the v2 rollout.
UPDATE users SET full_name = name
WHERE full_name IS DISTINCT FROM name AND id BETWEEN 1 AND 10000;
-- repeat for the next id range until no rows are left

-- Step 4: deploy v3. It reads full_name, still writes both.

-- Step 5: deploy v4. It only uses full_name.

-- Step 6, contract: nothing uses name any more. Remove it.
ALTER TABLE users DROP COLUMN name;

The backfill compares with IS DISTINCT FROM. A plain != would skip rows where full_name is still empty (NULL), because any compare with NULL gives no answer. IS DISTINCT FROM counts NULL as a value, so those rows get copied too.

expand-contract
  1. Expand: add full_name. v1 keeps working, it ignores it.
  2. Deploy v2: writes both columns, still reads name.
  3. Backfill: copy name into full_name for old rows, in batches.
  4. Deploy v3: reads full_name, still writes both.
  5. Deploy v4: uses only full_name.
  6. Contract: drop name. Nothing reads it any more.
step 1 / 6
At every step you can roll the app back one version and it still works.

When to use expand and contract#

Use it for any schema change that the old version can't handle: renaming or removing a column, changing a type, splitting a table. Adding a new nullable column or a new table is already safe in one step, because old code ignores it.

The pattern is called expand and contract, or parallel change. Danilo Sato describes it on Martin Fowler's site in three phases:

  1. Expand: add the new thing next to the old one.
  2. Migrate: move everything over to the new one.
  3. Contract: remove the old one.

It is slower than one migration, but every strategy in this post keeps its rollback.

Each SQL step also takes locks. A step that locks a busy table for too long is downtime of its own. That is why the backfill runs in small batches. For how Postgres locks work and which ALTER TABLE steps are dangerous, read Postgres From the Inside.

quick-check

You are at step 4: v3 reads full_name and writes both columns. v3 has a bug, so you roll back to v2. Does v2 still work?

Quick check: why can't you drop name in the same deploy that stops writing it (step 5)?

Show answer

During that deploy, v3 pods are still running, and v3 still writes name. Dropping it while they run breaks those writes, and a rollback to v3 breaks too. Drop the column only after no running version uses it.

Picking a strategy#

You have now seen each strategy ship one piece of the shop. To pick one for your own app, first compare the three that run two versions on real traffic:

Blue/green, canary and shadow side by side#

Blue/greenCanaryShadow
Who sees the new versioneveryone, after the switcha growing share of usersnobody
Rollbackswitch back, one commandabort, traffic goes backnothing to roll back
Extra costa second full copya traffic router and metricsdouble load, work to fake writes, emails and payments
Best forfast, all-at-once switchrisky changes, enough trafficrewrites, testing under real load

The decision tree#

Start from your situation and follow the questions:

Then add the extras where they fit:

  • A full rewrite? Run shadow traffic first, with side effects cut off.
  • The business sets the launch day, or you want a kill switch? Put the feature behind a flag.
  • Want to know which version users like more? Run an A/B test, on a flag.
  • Changing the database? Use expand and contract, whatever strategy you picked.

Your platform may already pick for you#

Kubernetes Deployments do a rolling update by default.

Cloud Run, Google's service that runs your containers for you, works differently. A deploy starts the new revision (a fixed version of your service). Cloud Run waits for its startup probe (Cloud Run's health check at start) to pass, then sends it the traffic. If the probe fails, it gets none. The old revision stays, so going back is one update-traffic command. That is closer to blue/green than to a rolling update. To send all traffic back to an old revision:

gcloud run services update-traffic SERVICE --to-revisions REVISION=100

You can run a canary by hand too. Deploy with --no-traffic. Then move traffic in steps with gcloud run services update-traffic. One catch: once you set a split by hand, new deploys get no traffic until you move it. Cloud Run from A to Z covers revisions in detail.

quick-check

Small team, one Kubernetes app. Stateless app, and v1 and v2 can run side by side. 50 users a day, no budget for a second copy. The deploy must not cause errors. What fits?

Recap#

Strategy or toolWhat it doesWhere it showed up in the shop
Recreatestops every old pod, then starts the new ones. Simple, with downtimereport-worker
Rolling updateswaps pods a few at a time, set by maxSurge and maxUnavailableapi, 4 pods
Probe, clean shutdown, compatible versionsthe three things zero downtime needs (and keep state out of the pod)the api rollout
Blue/greentwo full copies, one switch, rollback in one commandapi, which takes payments
Canarya growing share of users, with a metric gate at each stepapi with a new query
Shadow trafficcopies real requests to the new version and throws its answers awayrewritten search
Feature flagdeploy now, release later, switch off in secondsnew checkout page
A/B testfinds which version works better for users"Buy now" or "Add to cart"
Expand and contractchanges the schema in steps, so rollback works at every stepusers.name to full_name

Try it yourself:

  • Look at the Deployment of one app you run. Check its strategy, its two settings and its readiness probe. Not on Kubernetes? Write down how your app deploys today, and which chapter it is closest to.
  • Pick the strategy for your riskiest service. Check if your rollback still works after the new version has written data.
  • Find the riskiest feature in your app and put it behind a kill switch.
  • Look at your last schema change and check: could the old version still run on the new schema?

Read next: Cloud Run from A to Z runs these ideas on a platform that picks a strategy for you.

Footnotes

  1. The name blue/green came from Daniel Terhorst-North and Jez Humble. Martin Fowler wrote it up in 2010. back