Blue Green CMS Deployments Done Right

Backend developer profiling SQL query execution plans
Backend developer profiling SQL query execution plans (Photo via Unsplash)

Draw a blue-green deployment on a whiteboard and it looks almost too easy. Spin up an identical green stack next to live blue, run a smoke test, flip the load balancer, and drain blue. For a stateless Go binary serving JSON over HTTP, it really is that boring. You can push forty builds a day without breaking a sweat.

Try that playbook on a self-hosted CMS and you'll break production before lunch. At 2:14 PM on a Tuesday, while your deploy job swaps releases, marketing is uploading an 18MB press-kit PDF, a copywriter is saving a draft across four serialized metadata tables, and a worker is halfway through generating WebP thumbnails. Treat a publishing platform like a stateless API and you'll strand uploads in a dead release folder, crash old workers against dropped columns, or serve HTTP 500s from mismatched PHP classes.

Making continuous deployment work on a CMS follows one rule: code is immutable and disposable, while state is shared and version-tolerant.

Why Stateless Playbooks Break on Live CMS Stacks

A CMS—whether Craft, Drupal, WordPress, Concrete CMS, or Wagtail—juggles three sticky forms of state the exact second you swap source trees:

  • Uploads inside the webroot. Default installs still dump media into public/uploads or sites/default/files. Put that folder inside a versioned release and every mid-cutover upload disappears onto the wrong side of the switch.
  • One database under dual-version traffic. During a rollout—and a rollback twenty minutes later—both old and new code hit the same Postgres or MariaDB primary. Any destructive schema change breaks the other side immediately.
  • Warm caches and sticky sockets. PHP-FPM caches resolved symlinks, Redis holds serialized objects whose class shapes may shift, and edge proxies hold open multiplexed streams. When tuning persistent connections on an origin server—something we covered in HTTP/3 and QUIC tuning on origin boxes—you also have to account for how long streams stay pinned during a reload.

You don't need Kubernetes to solve this. On bare metal or a pair of VPS boxes, three boring primitives cover it: externalized object storage, expand-and-contract SQL migrations, and atomic cutovers.

Shared Object Storage Beats Synchronized Disks

The first trap teams hit with parallel CMS releases is syncing local upload folders across nodes. I've watched engineers wire up cron-driven rsync loops, lsyncd daemons, and two-node GlusterFS volumes over noisy private VLANs. They pass staging and crumble under editorial load. An editor uploads a hero image on green, hits Preview, lands on a lagging node, and gets a 404. Eventually two-way sync collides on thumbnail rewrites and leaves you untangling split-brain directories at 11 PM.

Pull media out of the release tree completely. On multi-node setups, write uploads directly to S3-compatible object storage—self-hosted MinIO, Garage, or a managed bucket—and configure your CMS asset driver accordingly. On a single origin box where an object store is overkill, keep uploads in a persistent directory outside releases and symlink it into each build before traffic arrives:

/srv/cms/
  shared/
    env/.env.production
    storage/uploads/
  releases/
    20261124-0915-blue/
    20261128-1402-green/
  current -> /srv/cms/releases/20261128-1402-green

Immutable Asset Keys and Isolated Scratch Caches

Prefix uploaded filenames with a short content hash or ULID (like 2026/11/01je8k9v-annual-report.pdf). When an editor replaces a file, the CMS writes a new key and updates the database pointer instead of overwriting bytes in place. Rolling back to blue won't serve a half-overwritten file or fight stale CDN caches.

Keep scratch caches out of shared storage. Compiled Twig or Blade templates, local thumbnail transforms, and upload temp chunks belong in a per-release cache directory or tmpfs mount. If green compiles templates with a newer engine version, blue shouldn't choke on compiled PHP written by green.

Expand-and-Contract SQL Migrations Without Table Locks

Broken uploads show up fast. Bad database migrations are sneakier: the deploy turns green, then quietly breaks in-flight blue requests or blocks your rollback ten minutes later.

Say you replace a plain-text author_byline column on cms_entries with a normalized author_id foreign key. A naive migration runs ALTER TABLE cms_entries DROP COLUMN author_byline right before flipping traffic. The moment that commits, blue workers draining requests crash with an unknown column error. Even if nobody notices during a two-second switch, you just burned your bridge back to blue. If green leaks memory, you can't roll back without restoring a database dump.

Split breaking schema changes across separate releases using expand-and-contract:

  1. Expand: Add nullable author_id and build its index online. Deploy green code that writes both columns on save while tolerating nulls on reads.
  2. Backfill in batches: Run an idempotent job updating 2,000 rows per transaction with a 50ms pause between batches. Never fire one giant UPDATE across two million rows unless you want to lock writers out of the admin UI for forty seconds.
  3. Switch reads: After verifying zero nulls remain and soaking green for a full editorial cycle (24 to 72 hours), ship a release reading exclusively from author_id and dropping writes to the old column.
  4. Contract: Drop author_byline in a later maintenance release once rollback to the old code is off the table.

On PostgreSQL 16, Phase 1 stays non-blocking by avoiding table rewrites and indexing concurrently:

-- Phase 1: Safe while blue and green share the primary
ALTER TABLE cms_entries
  ADD COLUMN IF NOT EXISTS author_id BIGINT;

-- Run outside a transaction block so editorial writes never stall
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_cms_entries_author_id
  ON cms_entries (author_id)
  WHERE author_id IS NOT NULL;

Watch your DDL locks closely. Rebuilding a composite index synchronously on a busy content table can stall saves longer than a restart. The online-DDL habits from our notes on database indexing for slow CMS views matter even more mid-cutover. On InnoDB, pass ALGORITHM=INPLACE, LOCK=NONE so MySQL or MariaDB fails fast instead of quietly taking a full table copy lock.

This discipline pays off even more during major platform upgrades. Following a staged zero-downtime CMS migration methodology keeps block schemas, legacy packages, and attribute tables from colliding mid-flight. Always rehearse forward and rollback scripts against a scrubbed copy of last night's snapshot—the exact routine from our automated offsite backups and drills playbook. An untested rollback plan in a wiki isn't a rollback plan.

Atomic Symlink Flips and the OPcache Trap

With media externalized and a dual-compatible schema live, you're ready for the switch. Self-hosted boxes usually point /srv/cms/current at the active release, and almost every team starts with this line:

# Do NOT run this under production traffic
ln -sfn /srv/cms/releases/20261128-1402-green /srv/cms/current

It looks atomic. It isn't. Trace GNU ln -sfn with strace and you'll see two syscalls: unlink("/srv/cms/current") followed by symlink(...). Between them, current briefly doesn't exist. At 15 requests a second you may get lucky for months. At 600 requests a second, Nginx hits that gap and returns 404s or FastCGI file-not-found errors.

Make the swap truly atomic by creating a temporary link on the same filesystem and replacing the live link with mv -Tf, which executes a single POSIX rename(2) syscall:

#!/usr/bin/env bash
set -euo pipefail

RELEASE_DIR="/srv/cms/releases/20261128-1402-green"
TMP_LINK="/srv/cms/.current-next-$$"

ln -s /srv/cms/shared/storage/uploads "${RELEASE_DIR}/public/uploads"
ln -s "$RELEASE_DIR" "$TMP_LINK"
mv -Tf "$TMP_LINK" /srv/cms/current

That closes the filesystem race. Next comes the trap that burns almost every PHP team on their first live cutover: the kernel flipped the symlink atomically, yet PHP-FPM didn't notice.

PHP-FPM keeps a per-worker realpath_cache that defaults to 120 seconds, and OPcache keys bytecode by resolved path. Pass $document_root/index.php (the literal /srv/cms/current path) and old workers resolve blue from cache while fresh workers resolve green. For two minutes, one request can mix a blue autoloader with a green controller and die on a fatal interface mismatch.

Force Nginx to resolve the symlink per request and pass the canonical directory via $realpath_root:

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
With $realpath_root, PHP-FPM sees distinct canonical paths for blue and green bytecode. In-flight blue requests finish cleanly while new traffic boots straight into green—zero class mixing and no panicked OPcache flush.

For major PHP upgrades or Redis format shifts, run separate upstream pools (cms-blue.sock and cms-green.sock) under distinct systemd units, warm green on localhost, swap an Nginx upstream include via mv -Tf, and trigger nginx -s reload. Graceful reloads drain blue cleanly while routing fresh traffic to green, keeping rollback one file swap away.

Five Checks Before We Flip the Link

We've trimmed our production cutover script down to five hard gates. If any check fails, the deploy aborts untouched:

  • Schema compatibility check: Reject migrations with drops, renames, or narrowing type changes, and confirm both blue and green test suites pass against the expanded database.
  • Live storage probe: Have green write a 64-byte sentinel object to shared storage, fetch it over the public URL, and delete it. Catching a bad bucket policy before editors log in beats an angry incident channel.
  • Loopback cache warmup: Curl green's internal socket across the top twenty landing pages and admin login before cutover. Cold OPcache on a busy site can pin CPU at 100% in three seconds.
  • Queue worker rollover: Gracefully restart long-running workers (systemctl reload cms-worker) right after the flip so background jobs don't run yesterday's code for hours.
  • 48-hour blue retention: Leave the prior blue release untouched on disk for two full days. NVMe space is cheap; rebuilding an old artifact during an outage isn't.

Blue-green CMS deployments aren't magic. Keep uploads outside the release tree, write every SQL migration assuming both app versions will share it for a week, and let rename(2) plus $realpath_root do the work. When a Friday security patch ships in four seconds while twelve editors keep publishing uninterrupted, you'll know the plumbing is right.

Comments

Popular posts from this blog

PostgreSQL vs MariaDB for Modern CMS

Edge Caching Without Stale CMS Edits

Hardening Self Hosted Linux CMS Nodes