Building Zero-Downtime Database Cutovers with the Transactional Outbox Pattern in Go
Vikram Sengupta
Engineering Team
Index(14 sections)
Building Zero-Downtime Database Cutovers with the Transactional Outbox Pattern in Go
Define the Cutover Invariants: Availability, Data Integrity, Ordering, and Recoverability
The production problem
A naive migration writes to the source database and then publishes a replication message:
- Commit the business transaction.
- Publish the corresponding event.
A process crash, broker timeout, or network partition between those operations leaves committed source data without a migration event. Reversing the operations creates the opposite failure: the target receives an event for a source transaction that later rolls back.
Synchronous dual writes do not remove the problem. They couple request availability and tail latency to two databases. They also hold application connections while waiting on another fault domain. Under target degradation, the source connection pool becomes the backpressure queue.
The transactional outbox keeps the atomic boundary inside the source database. Each business mutation and its event commit in one transaction. A relay later performs an at-least-once handoff. The target must therefore tolerate duplicates and reordering.
Treat zero downtime as a set of invariants:
- A committed source mutation always has a committed outbox row.
- The relay never marks an event complete before durable downstream acknowledgement.
- Events contain a stable identifier, aggregate identifier, monotonic version, schema version, and full desired state.
- The target records deduplication state and data changes in one transaction.
- Backfill cannot overwrite a newer live event.
- Only one database accepts authoritative writes at a time.
- Rollback remains possible after target-primary routing begins.
The outbox removes the dual-write gap. It does not automatically provide fencing, validation, or rollback.
Design the Migration State Machine from Baseline Snapshot to Final Traffic Switch
Architecture and request flow
The controller should persist each transition with compare-and-swap semantics. Valid states include source-primary, baseline copy, catch-up, verification, write-fenced, target-primary, rollback, and cleanup. An operator must not skip states through an ad hoc configuration edit.
Model the Business Transaction and Outbox Schema for Atomic Writes in Go
Assume PostgreSQL on both sides, pgx, a durable partitioned channel, and events keyed by aggregate ID. PostgreSQL documents transaction atomicity in Transactions.
CREATE TABLE migration_outbox (
seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id uuid NOT NULL UNIQUE,
aggregate_id uuid NOT NULL,
aggregate_version bigint NOT NULL,
event_kind text NOT NULL,
schema_version text NOT NULL,
payload jsonb NOT NULL,
available_at timestamptz NOT NULL DEFAULT now(),
lease_owner text,
lease_until timestamptz,
attempts bigint NOT NULL DEFAULT 0,
published_at timestamptz,
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX migration_outbox_pending
ON migration_outbox (available_at, seq)
WHERE published_at IS NULL;Generate the aggregate version while locking or updating the business row. Do not derive it from wall-clock time.
type Mutation struct {
ID uuid.UUID
Body json.RawMessage
Deleted bool
}
type EventPayload struct {
ID uuid.UUID `json:"id"`
Version int64 `json:"version"`
Body json.RawMessage `json:"body"`
Deleted bool `json:"deleted"`
}
func Apply(ctx context.Context, db *pgxpool.Pool, m Mutation) error {
tx, err := db.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("begin mutation: %w", err)
}
defer tx.Rollback(ctx)
var version int64
err = tx.QueryRow(ctx, `
UPDATE customer
SET body = $2, deleted = $3, version = version + 1
WHERE id = $1
RETURNING version`,
m.ID, m.Body, m.Deleted,
).Scan(&version)
if err != nil {
return fmt.Errorf("update customer: %w", err)
}
payload, err := json.Marshal(EventPayload{
ID: m.ID, Version: version, Body: m.Body, Deleted: m.Deleted,
})
if err != nil {
return fmt.Errorf("encode outbox payload: %w", err)
}
_, err = tx.Exec(ctx, `
INSERT INTO migration_outbox
(event_id, aggregate_id, aggregate_version,
event_kind, schema_version, payload)
VALUES ($1, $2, $3, $4, $5, $6)`,
uuid.New(), m.ID, version, "customer.changed", "customer-current", payload,
)
if err != nil {
return fmt.Errorf("insert outbox: %w", err)
}
return tx.Commit(ctx)
}Propagate the request context through every database call. Configure server-side statement timeouts as a second boundary because client cancellation can arrive after the server starts work.
Implement a Reliable Go Outbox Relay with Claiming, Checkpoints, Retries, and Backpressure
Multiple relay instances can claim work with FOR UPDATE SKIP LOCKED. PostgreSQL explicitly identifies SKIP LOCKED as suitable for queue-like access in the `SELECT` documentation.
WITH picked AS (
SELECT seq
FROM migration_outbox
WHERE published_at IS NULL
AND available_at <= now()
AND (lease_until IS NULL OR lease_until < now())
ORDER BY seq
FOR UPDATE SKIP LOCKED
LIMIT $1
)
UPDATE migration_outbox AS o
SET lease_owner = $2,
lease_until = now() + $3::interval,
attempts = attempts + 1
FROM picked
WHERE o.seq = picked.seq
RETURNING o.seq, o.event_id, o.aggregate_id,
o.aggregate_version, o.payload, o.attempts;Use a fixed worker count and a bounded jobs channel. Claim only enough rows for currently available worker capacity. Release the database connection before waiting for broker I/O.
type RelayConfig struct {
Workers int
Batch int
Lease time.Duration
PublishTimeout time.Duration
MinBackoff time.Duration
MaxBackoff time.Duration
}
func (r *Relay) deliver(ctx context.Context, owner string, e Event) error {
attemptCtx, cancel := context.WithTimeout(ctx, r.cfg.PublishTimeout)
defer cancel()
// Publish returns nil only after the channel confirms durable storage.
if err := r.publisher.Publish(attemptCtx, e.AggregateID, e.EventID, e.Payload); err != nil {
delay := retryDelay(r.cfg, e.Attempts)
return r.store.Release(
ctx, owner, e.EventID, time.Now().Add(delay), err.Error(),
)
}
return r.store.Complete(ctx, owner, e.EventID)
}Complete must include lease_owner in its predicate. If a lease expires during publication, another worker can publish the event again. That is safe only because the applier is idempotent.
Run the dispatcher and workers under errgroup.WithContext. Stop claiming when cancellation begins, allow active publications to finish within the shutdown deadline, and return unprocessed leases to expiry. The Go `context` package defines the cancellation contract.
Use capped exponential backoff with full jitter. Keep poison events pending or quarantined with an alert; never convert rejection into a successful checkpoint. A global “last sequence” checkpoint is unsafe because transactions can commit out of sequence and claimed batches can contain holes.
Build an Idempotent Target Applier for Replays, Deletes, Version Conflicts, and Schema Translation
Transform the payload deterministically before opening the target transaction. Then insert the event ID and apply its state together:
WITH accepted AS (
INSERT INTO migration_inbox (event_id, received_at)
VALUES ($1, now())
ON CONFLICT DO NOTHING
RETURNING event_id
)
INSERT INTO customer_target
(id, version, body, deleted, source_event_id)
SELECT $2, $3, $4, $5, $1
FROM accepted
ON CONFLICT (id) DO UPDATE
SET version = EXCLUDED.version,
body = EXCLUDED.body,
deleted = EXCLUDED.deleted,
source_event_id = EXCLUDED.source_event_id
WHERE customer_target.version < EXCLUDED.version;Represent deletes as versioned tombstones until backfill and rollback are closed. Otherwise, an older snapshot row can recreate deleted data.
Full-state events tolerate version reordering. Patch events do not: park them until the missing predecessor arrives. For equal versions, compare a canonical payload hash and raise an alert if content differs. Include a schema version and retain old translators until all events using that version have expired.
Coordinate Historical Backfill with Live Outbox Events Without Gaps or Overwrites
Deploy outbox-writing application code before starting the baseline. Fence old application versions and drain their active transactions so every later mutation produces an event.
Open a repeatable-read transaction, export its snapshot, and let snapshot workers import it before reading assigned key ranges. PostgreSQL documents this mechanism under Snapshot Synchronization Functions.
Each copied row must include its aggregate version. The target backfill uses the same conditional upsert as the live applier. A newer event therefore wins even when snapshot and event workers overlap.
Do not treat MAX(outbox.seq) as commit order. A transaction can allocate a lower sequence and commit after another transaction. Keep the baseline snapshot open until workers attach, replay all retained events from the established coverage boundary, and validate convergence by version. Monitor the snapshot’s effect on vacuum because a long-lived snapshot retains old row versions.
Execute the Cutover with Shadow Reads, Consistency Validation, Write Fencing, and Rollback Controls
Run shadow reads outside the user request’s critical path. Compare canonical records, tombstones, aggregate versions, and deterministic hashes. Sample comparisons help detect defects, but the final gate should scan the authoritative key space.
For the write handoff:
- Fence new source writes with a database-enforced migration epoch.
- Drain active source transactions.
- Wait until every eligible outbox row has a durable handoff and the applier has caught up.
- Run the final consistency gate.
- Change the router to target-primary.
- Release queued writes against the target.
Reads can continue during the write fence. Buffered writes increase tail latency, so bound the queue and rehearse behavior at client deadlines.
Stale application instances must fail closed when their epoch is obsolete. Routing changes alone cannot prevent split-brain writes.
Rollback after target-primary requires a reverse replication path. Enable an equivalent target outbox before cutover, apply target-originated changes back to the source, and suppress event loops with an origin marker. Without that path, rollback means another write fence and forward recovery, not an immediate router reversal.
Test and Operate the Migration with Fault Injection, Observability, Runbooks, and Safe Cleanup
Local verification and profiling
curl -fsS -X POST "$API_URL/customers/$CUSTOMER_ID" \
-H 'content-type: application/json' \
--data '{"name":"cutover-probe"}'
go tool pprof -top "$PPROF_URL/debug/pprof/heap"
k6 run \
-e BASE_URL="$API_URL" \
-e VUS="$LOAD_VUS" \
-e DURATION="$LOAD_DURATION" \
cutover.js
psql "$SOURCE_DSN" -c "
SELECT query, calls, rows, total_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC;"Expose net/http/pprof only on an internal listener; see the official `net/http/pprof` documentation. Use load-test results to inspect request tail latency, pool wait time, relay pending age, broker acknowledgement latency, and applier lag. Do not infer capacity from averages.
Configuration manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: outbox-relay
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
template:
spec:
containers:
- name: relay
image: registry.example.com/outbox-relay:release
envFrom:
- configMapRef:
name: outbox-relay-tuned
- secretRef:
name: outbox-relay-credentials
readinessProbe:
exec:
command: ["/app/relay", "ready"]The rolling-update fields follow the Kubernetes Deployment specification. Derive relay workers, batch size, and database pool limits from measured broker acknowledgement behavior and the source connection budget. Reserve source connections for application traffic and operator recovery.
Failure modes and recovery
Inject failures after the source commit, after broker acknowledgement, during target commit, and after inbox insertion. Also test broker partitions, source failover, expired leases, malformed payloads, duplicate delivery, and events arriving in reverse version order.
Watch for these operational faults:
- Connection starvation: use a separate relay pool and never hold its connection during publication.
- Memory growth: bound claim batches, worker channels, payload size, and validation buffers.
- Lease churn: renew long-running claims or keep the lease longer than the enforced publication deadline.
- Table bloat: retain audit data through the rollback window, then delete in controlled chunks and let vacuum recover space.
- Poison events: quarantine with full error context while keeping the cutover gate closed.
- Validation drift: freeze state transitions, replay from durable event IDs, repair the translator, and rerun the complete gate.
Remove the outbox, inbox, tombstones, reverse relay, and migration epochs only after the rollback window closes, backups are verified, and the target has operated as the sole authority.
Related Topics
Share This Article
More Engineering Architecture Playbooks
Deep dives and blueprints from our senior engineering team
Alpine Linux Security Advisory: OpenSSH-server password authentication bypass
Organizations should treat the advisory as an identity-boundary incident until package inventory, SSH configuration, network exposure, and access records establish otherwise. The paper will translate verified Alpine guidance into a production-safe workflow covering exposure analysis, containment, upgrades, validation, threat hunting, and recovery.
vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters
This whitepaper explains how vLLM uses PagedAttention and block-based KV cache management to decouple request growth from contiguous GPU-memory allocation. It translates those mechanics into a production architecture for NVIDIA H100 clusters, covering scheduling, topology, capacity governance, observability, resilience, and safe multi-tenant operations without relying on unsupported benchmark claims.
Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability
CVE-2024-27834 should be handled as a trust-boundary issue rather than a routine endpoint update because improper authentication can undermine assumptions about who or what is permitted to access protected resources. The paper will translate vendor-confirmed facts into an operational response spanning asset discovery, risk-based containment, controlled patch deployment, post-update verification, and executive governance without speculating beyond published evidence.