System Design Part 10 Delivery

CI/CD and Deployment Strategies: Old and New Versions Run Side by Side, So Design Changes for It

Bill.Lin 20 min read

System Design series Part 10-2 | Previous: Testing at Scale | Series map

Read first: Part 8-4 Encryption in Transit and at Rest, and Secrets Management, Part 10-1 Testing at Scale.

Scenario and problem

The talk platform’s 30 services deploy a dozen or more times a day. Last quarter’s deploy-related incidents:

  1. A column dropped during a deploy: the new version no longer used registration.member_id, and the migration in the same deploy dropped the column. During the rolling update, the old version, still running, started throwing errors in large numbers
  2. No way to roll back: when the problem was found, the team wanted to go back to the previous version, but the migration had already converted the data to a new format that the old version could not read
  3. A deploy during a flash sale: a routine deploy happened to land 5 minutes before sales opened; the restarted instances were still warming up when the opening traffic arrived
  4. A leaked CI key: the CI platform stored a long-lived cloud access key, and a compromised third-party CI package printed it to the build log
A deploy is not instantaneous1 / 4
A deploy is not instantaneousOld versionDatabaseNew versionCI platformSale trafficNew versionDatabaseOld versiondrop member_idread member_idFloods of errorsOld versionDatabasecan't read dataAlready in the new formatSale trafficNew versionsale trafficRestarting, still warming upCI platformNew versiondeployLong-lived key in the log
  1. A column dropped during a deployThe new version no longer used registration.member_id, and the migration in the same deploy dropped the column. During the rolling update, the old version, still running, started throwing errors in large numbers.
  2. No way to roll backWhen the problem was found, the team wanted to go back to the previous version, but the migration had already converted the data to a new format that the old version could not read.
  3. A deploy 5 minutes before the saleA routine deploy happened to land 5 minutes before sales opened; the restarted instances were still warming up when the opening traffic arrived.
  4. A leaked CI keyThe CI platform stored a long-lived cloud access key, and a compromised third-party CI package printed it to the build log.

The first three share one cause: a deploy is not instantaneous. During a rolling update, a canary, or a rollback, the old and new versions are live at the same time, reading and writing the same database, the same cache, and the same topic. The fourth is a reminder that the pipeline itself is a system that can change production, and it deserves the same level of security.

The simplest approach and its limits

Once the CI tests pass, roll the update straight across every production instance, and roll back by hand if something goes wrong:

  • The blast radius is 100%: a bug that only shows up under real traffic hits every user at once
  • People have to notice: you only find out from an alert or a customer complaint, and the damage keeps growing in the meantime
  • Rollback is slower than the damage: deciding by hand and rolling back by hand, ten-odd minutes are gone; if the schema has already changed, rollback may not even be possible
  • No thought for coexistence: every deploy assumes “the old version vanishes instantly”, but in reality the versions coexist for minutes to hours

Core mechanism

The pipeline: build once, promote through environments

flowchart LR
    C[Commit] --> B[Build and unit tests<br/>integration and contract tests]
    B --> S[Security checks<br/>dependency vulnerabilities, secrets, static analysis]
    S --> I[Build image<br/>identified by digest, signed, SBOM]
    I --> ST[Deploy to staging<br/>smoke tests]
    ST --> CA[Production canary<br/>automated analysis]
    CA --> P[Gradually expand to 100%]
    CA -.->|metrics look abnormal| RB[Abort and roll back automatically]
  • Build once: the same image (identified by the digest of its content, not by a tag that can be moved) is promoted from staging all the way to production. If each environment builds again, there is no guarantee that what you tested is what you shipped
  • Inject configuration at deploy time: the only differences between environments are configuration and secrets, and they are not in the image (the Encryption and Secrets post)
  • Fast feedback: from commit to “test results” should ideally take less than 10 minutes. Slow tests (load tests, full security scans) run daily or before a release, and do not block every commit
  • Every stage is a gate: a failure stops the pipeline; nobody has to remember to look

Separate deploying from releasing

  • Deploy: the new code runs on the servers
  • Release: users see the new feature

Use feature flags to separate the two: the code for a new feature can be deployed at any time but is off by default; later you turn it on gradually, for internal staff, then 1% of members, then all members. When something goes wrong, turning the flag off is much faster than rolling back the deploy, and it does not affect the other changes in the same deploy.

The cost of feature flags is branches in the code. Every flag needs an owner and a removal date; once a flag is fully on, delete the old branch, or a few years later you will have hundreds of flags nobody dares to touch.

Deployment strategies

Strategy How Downtime Rollback speed Extra resources Old and new versions coexist
Recreate Stop every old instance, then start the new version Yes Slow (redeploy) None No
Rolling Replace instances batch by batch No Medium (roll again) A little Yes, for as long as the batches take
Blue-green Deploy the new version in full to a second environment, then switch traffic at once No Fast (switch back) Double At the moment of the switch; the database is shared
Canary The new version takes a small share of traffic first, expanded step by step based on metrics No Fast (shift traffic back) A little Yes, and deliberately for longer

The talk platform’s default is canary plus automated analysis: a problem only affects a small share of traffic, and a machine decides whether to continue. Blue-green has the fastest rollback, but the doubled resources and the shared database make it a better fit for the few systems that cannot be rolled out in batches.

Note that blue-green does not avoid coexistence: both environments share one database, so schema changes still have to work with both the blue and the green version.

Old and new versions side by side: expand–contract

The fix for incidents 1 and 2 is to split one incompatible change into several deploys, each compatible on its own. Take “rename member_id to attendee_id” as an example:

Phase Schema Code Can this step be rolled back?
1. Expand Add attendee_id, nullable No change Yes, the old code does not know about the new column
2. Dual write — Write both columns, still read member_id Yes, the old version still reads and writes member_id
3. Backfill Copy member_id into attendee_id for existing rows, in batches — Yes
4. Read the new column — Read attendee_id, still dual write Yes, back to the phase 2 version
5. Stop writing the old column — Write only attendee_id Back to phase 4, yes; earlier versions would read a stale member_id
6. Contract Drop member_id — No, so it comes last, after the earlier versions have been stable for a while

Every step is an independent deploy, and any two adjacent versions can be live at the same time without errors. This also applies to fields in APIs and events (the contract tests in Testing at Scale), and to data in caches: the new version writes an object with one extra field to Redis, and if the old version fails when it reads a field it does not recognize, you get a flood of cache read errors during the rolling update (the Caching post).

Schema changes on large tables also have to watch for locks: since MySQL 8.0.29, adding and dropping columns can use ALGORITHM=INSTANT to change only metadata; changes that rebuild the table (such as changing a column’s type) need an online schema change tool like gh-ost on tables with hundreds of millions of rows, to avoid long locks and replication lag (the Replication post).

Canary and automated analysis

Each step of a canary:

  1. The new version takes 5% of traffic, then you wait for a while (bake time)
  2. Compare the new version’s metrics with the stable version’s: error rate, p99 latency, saturation, and business metrics (sign-up success rate, payment success rate)
  3. If the metrics look normal, expand to 25%, 50%, then 100%; if any step looks abnormal, shift traffic back to the stable version automatically

A few details decide whether a canary works:

  • Wait long enough: for a low-traffic service, 5 minutes may mean only a few dozen requests, too few to show a statistical difference. Set the wait by traffic, or make up the volume with synthetic traffic
  • Compare against the stable version, not a fixed threshold: the error rate at 8 p.m. is naturally higher, so a fixed threshold raises false alarms at peak and misses problems off-peak
  • Pin each user to one version: otherwise users bounce between the old and new versions, and the frontend and backend versions do not match
  • Bring instances up and down cleanly: a new instance takes traffic only after it passes its readiness check; an old instance is first removed from the load balancer, finishes its in-flight requests, and then exits. Spring Boot 4.1’s embedded server enables graceful shutdown by default, and Kubernetes also needs a preStop wait to cover the gap between removal and stopping (the Service Discovery post)

Rolling back and fixing forward

  • Roll back by default: when you find a problem, go back to the last known good version first, then investigate. This assumes every deploy can be rolled back, which is exactly what expand–contract guarantees
  • Fix forward: when rolling back is itself risky (for example, data has already been written in the new format), ship a fix quickly instead. This requires a pipeline that is fast enough from commit to production
  • The fastest rollback is a feature flag: it takes effect in seconds, with no redeploy

When and how often to deploy

  • Freeze periods: for a while before and after big events (sales opening for a 10,000-person talk, the annual course launch), allow only emergency fixes (incident 3)
  • Error budget: when a service has used up its SLO error budget, pause feature releases and deploy only reliability fixes (the Observability post)
  • Measure: DORA’s four key metrics: deployment frequency, lead time for changes, change failure rate, and failed deployment recovery time. The goal is not “deploy less to stay stable”; research shows that frequent, small-batch deploys correlate positively with stability

Comparing options

Decision Choice Rejected alternative and why
Artifact Build once, promote by digest Rebuild for each environment: what was tested and what ships may differ
Deployment strategy Canary + automated analysis Roll out to 100% in one go: large blast radius, relies on people noticing
Release Feature flags Deploy equals release: rolling back a feature means rolling back the whole deploy
Schema changes expand–contract over several deploys All in one go: the old version throws errors during the rolling update, and there is no rollback
Deploying to the cluster GitOps: the pipeline updates a config repo, and an agent in the cluster pulls it The pipeline holds cluster admin rights directly: a compromised CI means a compromised cluster
CI cloud permissions OIDC exchanged for short-lived credentials Long-lived keys stored in CI: still valid long after a leak (incident 4)

In Java

1. The expand–contract migration and dual writes

sql
-- V42__add_attendee_id.sql (phase 1: metadata change only, no table rebuild)
ALTER TABLE registration ADD COLUMN attendee_id BIGINT NULL, ALGORITHM=INSTANT;

-- V43__index_attendee_id.sql (build the index online; use an online schema change tool for large tables)
CREATE INDEX idx_registration_attendee ON registration (event_id, attendee_id);
java
@Repository
public class RegistrationWriter {

    private final JdbcClient jdbc;

    public RegistrationWriter(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    // Phases 2 to 4: write both columns, so the old and new versions read the same data
    public void insert(long eventId, long attendeeId) {
        jdbc.sql("""
                        INSERT INTO registration (event_id, member_id, attendee_id)
                        VALUES (:eventId, :attendeeId, :attendeeId)
                        """)
                .param("eventId", eventId)
                .param("attendeeId", attendeeId)
                .update();
    }
}
java
// Phase 3: backfill in batches, one small transaction per batch, to avoid long transactions and replication lag
@Component
public class AttendeeIdBackfill {

    private static final int BATCH = 2_000;
    private final JdbcClient jdbc;

    public AttendeeIdBackfill(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    public void run() throws InterruptedException {
        long lastId = 0;
        while (true) {
            List<Long> ids = jdbc.sql("SELECT id FROM registration WHERE id > :last ORDER BY id LIMIT :batch")
                    .param("last", lastId).param("batch", BATCH)
                    .query(Long.class).list();
            if (ids.isEmpty()) {
                return;
            }
            long maxId = ids.getLast();
            jdbc.sql("""
                            UPDATE registration SET attendee_id = member_id
                             WHERE id > :last AND id <= :max AND attendee_id IS NULL
                            """)
                    .param("last", lastId).param("max", maxId)
                    .update();
            lastId = maxId;
            Thread.sleep(50);                       // give replicas time to catch up; adjusting it to replication lag is better
        }
    }
}
  • Split batches by keyset (id > :last), not OFFSET (the Batch and Stream Processing post)
  • attendee_id IS NULL makes the backfill safe to rerun: after an interruption, run it again from the start, and rows already backfilled are not updated again
  • The dual-write code is live before the backfill starts, so rows inserted during the backfill are not missed

2. Feature flags: stable percentage rollout

java
@Component
public class FeatureFlags {

    private final FlagStore store;               // flag settings, for example stored in the database and cached for a few seconds

    public FeatureFlags(FlagStore store) {
        this.store = store;
    }

    public boolean isEnabled(String flag, long memberId) {
        FlagConfig config = store.get(flag);
        if (config == null || config.killSwitch()) {
            return false;                        // missing or switched off in an emergency: take the old path
        }
        if (config.allowList().contains(memberId)) {
            return true;                         // internal staff, test accounts
        }
        // A member always lands in the same bucket for the same flag, so they never flip between old and new behavior
        return bucketOf(flag + ":" + memberId) < config.rolloutPercent();
    }

    private static int bucketOf(String key) {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256").digest(key.getBytes(StandardCharsets.UTF_8));
            return Math.floorMod(ByteBuffer.wrap(digest).getInt(), 100);     // take the first 4 bytes
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);                              // the Java platform requires SHA-256 support
        }
    }
}
  • The hash includes the flag name, so the 5% for different flags is not always the same set of members
  • Use SHA-256 rather than String.hashCode(): both are stable, but hashCode() mixes poorly, so members with consecutive IDs land in adjacent buckets, and the members picked by different flags are just shifted versions of each other. SHA-256’s output is uniform, and the Java platform requires every implementation to support it
  • Flag changes need an audit trail: who changed which flag to what value, and when

3. Canary and automated analysis (Argo Rollouts)

yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: registration-api
spec:
  # selector and template are the same as in a Deployment, omitted here
  strategy:
    canary:
      analysis:
        templates:
          - templateName: success-rate
        startingStep: 1                 # start background analysis after the first traffic shift
        args:
          - name: service-name
            value: registration-api
      steps:
        - setWeight: 5
        - pause: {duration: 10m}
        - setWeight: 25
        - pause: {duration: 10m}
        - setWeight: 50
        - pause: {duration: 10m}
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: success-rate
spec:
  args:
    - name: service-name
  metrics:
    - name: success-rate
      interval: 1m
      successCondition: result[0] >= 0.99
      failureLimit: 2                   # abort after more than two failures; traffic goes back to the stable version
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            sum(rate(http_server_requests_seconds_count{app="{{args.service-name}}",outcome!="SERVER_ERROR"}[2m]))
            /
            sum(rate(http_server_requests_seconds_count{app="{{args.service-name}}"}[2m]))
  • The background analysis keeps running for the whole canary; if it fails at any point, the Rollout aborts and sets the canary weight back to 0
  • http_server_requests_seconds_count is the Prometheus name of Micrometer’s HTTP server metric; the app label is assumed to be added from the Pod’s labels by the scrape configuration
  • This example looks at the overall success rate; a more precise approach queries the canary and stable Pods separately, compares the two, and adds p99 latency and business metrics

4. CI: OIDC short-lived credentials and locked dependencies

yaml
# .github/workflows/build.yml
name: build
on:
  push:
    branches: [main]

permissions:
  contents: read
  id-token: write                       # exchange OIDC for short-lived cloud credentials; CI stores no long-lived keys

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-java@v5
        with:
          distribution: temurin
          java-version: '21'
      - run: ./mvnw -B verify            # unit, integration (Testcontainers), contract, and authorization regression tests
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/ci-push-image
          aws-region: ap-northeast-1
      - uses: aws-actions/amazon-ecr-login@v2   # log in to the image registry with the short-lived credentials just obtained
      - id: push
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/registration-api:${{ github.sha }}
      # Later steps: sign steps.push.outputs.digest, generate an SBOM,
      # then write the digest into the staging directory of the GitOps config repo, where Argo CD in the cluster pulls it
  • Third-party actions are referenced by tag, but .github/workflows/actions.lock locks them to exact commits (generated with gh actions-lock). The lockfile also covers transitive dependencies and verifies the source repository at run time; reusable workflows are outside the lockfile’s scope, so reference them by full commit SHA
  • The cloud IAM role trusts only OIDC tokens issued for this repository and this branch, and its only permission is pushing images, not deploying
  • Production deploys are controlled by the GitOps config repo, where merges require review; the pipeline itself has no cluster permissions

The code above is written from the official documentation for Spring Boot 4.1, MySQL 8.4 (ALGORITHM=INSTANT), Argo Rollouts 1.10, and GitHub Actions, and has not been compiled or run. FlagStore and FlagConfig are illustrative components; the account, role, and image path in the workflow are example values.

Pitfalls and gotchas

  • Dropping a column the old version still uses, in the same deploy: the old version throws errors during the rolling update
  • Shipping an irreversible migration together with the code: rollback becomes impossible
  • Incompatible cache and message formats: the old version cannot read data written by the new version
  • Rebuilding for each environment: the image tested in staging is not the one running in production
  • Deploying by a movable tag: once latest or v1 is repointed, the same deployment config runs different code
  • A canary wait that is too short, with too little traffic: the result is not statistically significant, and the problem goes straight to 100%
  • Comparing against a fixed threshold: false alarms at peak, missed problems off-peak
  • Feature flags without a removal date: old branches stay in the code forever, the combinations explode, and nobody knows which flags are still in use
  • Deploying right before a big event: put freeze periods on the calendar and have the pipeline enforce them, instead of relying on memory

Security

The pipeline can ship arbitrary code to production, so it is a target in its own right:

Attack How it happens Defense
Long-lived CI key stolen The key sits in a CI variable and a malicious build step reads it out (incident 4) Exchange OIDC for short-lived credentials; the role trusts only specific repositories and branches, with least privilege
Third-party action tampered with An attacker gains access to the action’s repository and points an existing tag at a malicious commit. The tj-actions/changed-files incident in March 2025 (CVE-2025-30066) did exactly this and printed the secrets of a large number of repositories to their build logs A lockfile for workflow dependencies, or references by full commit SHA; restrict which actions are allowed
Untrusted code running with privileges A trigger such as pull_request_target, which runs with the target repository’s permissions, checks out and runs code sent from a fork Workflows that handle outside contributions use no secrets and do not run the PR’s code; split them into two workflows when needed
Malicious or tampered dependencies A library you depend on gets a backdoor; internal package names are registered first on a public registry (dependency confusion); the 2024 xz-utils backdoor (CVE-2024-3094) was a long-term infiltration at the maintainer level Fetch dependencies through an internal package proxy and pin versions; dependency vulnerability scanning; an SBOM records what each image contains
Image replaced An attacker pushes a tag with the same name to the image registry Deploy by digest; sign images (for example with Sigstore), and let the cluster run only images whose signature and provenance (SLSA provenance) have been verified
Shipping without review A developer’s account is stolen and used to push straight to the main branch or trigger a production deploy by hand Branch protection and required reviews; production deploys need approval from a second person; deploy records go to an audit log
Secrets leaked into logs or images A build step prints environment variables; a config file gets packaged into the image Secrets are injected by the platform only at run time (the Encryption and Secrets post); log masking; image scanning

When to use it, and when not to

  • Rolling deploys: the starting point when you have few services and modest traffic, and the team is just starting to build a pipeline
  • Canary plus automated analysis: traffic is high enough to show a statistical difference in a short time, and a bad deploy is expensive
  • Blue-green: systems that need instant switchover and instant rollback, and can afford double the resources
  • Feature flags: when the timing of a release differs from the timing of a deploy, or when you need to open a feature to users gradually; do not use them as a substitute for cleaning up code
  • expand–contract: any change that would make two adjacent versions incompatible, including schemas, APIs, events, and cache formats
  • Do not adopt too early: GitOps, automated analysis, and signature verification are all systems you have to operate. For a small project maintained by one person, simple scripts plus deploys you can roll back are enough; add these one at a time as the number of services, deploy frequency, and team size grow

References

Comments