A CI/CD pipeline is built to compile code and exit; orchestrating multi-hour, stateful database migrations on ephemeral runner processes guarantees orphaned cloud mutations and half-switched failovers.

TL;DR

  • Problem: Linear CI/CD runners (Jenkins, GitHub Actions) hold workflow state in volatile RAM, pin worker slots with while-sleep loops, and lack native Saga compensation when a multi-hour database upgrade fails mid-flight.
  • Answer: Move stateful database orchestration to an event-sourced Durable Execution Engine (Temporal) using idempotent, heartbeating Activities and defer-based LIFO Saga compensation.
  • Watch out: Temporal enforces a hard cap of 51,200 events (50 MB) per workflow history, non-deterministic code breaks replay, and Go Sagas must use workflow.NewDisconnectedContext so cancellations do not abort cleanup.

Four-stage durable database orchestration from event history to defer-based Saga rollback

Situation

Database platform teams manage fleets of relational instances, replica sets, and sharded clusters across public clouds. Routine lifecycle operations—major-version engine upgrades, cross-region failovers, storage resizes, and zero-downtime schema cutovers—often span hours. Historically, teams automated these tasks inside CI/CD pipelines such as Jenkins, GitLab CI, or GitHub Actions by wrapping shell scripts, Ansible playbooks, or Python CLIs inside pipeline runners.

A typical pipeline triggers an AWS RDS snapshot, polls the cloud API until the snapshot reaches available, initiates an engine upgrade, runs validation queries, and updates an internal catalog. On small development databases that finish in three minutes, linear runners appear reliable. Once storage grows into multi-terabyte volumes—where EBS snapshot synchronization, engine catalog conversions (pg_upgrade), and multi-AZ replica resynchronization routinely span 2 to 8 hours of asynchronous cloud control-plane work—the impedance mismatch between ephemeral CI runners and stateful distributed orchestration causes recurring operational incidents.

The Problem

Linear CI/CD runners were designed to build artifacts and exit, not to act as fault-tolerant distributed state machines. Using them for multi-hour database orchestration fails against four constraints:

  1. Volatile Process RAM: Pipeline step progress lives in the runner’s volatile memory. If a Linux OOM killer, Spot instance reclamation, or agent restart kills the runner during a six-hour migration, the orchestrator loses which step completed, which snapshot IDs were created, and whether a cutover already began.
  2. While-Sleep Slot Exhaustion & Runner Timeouts: Multi-terabyte snapshots and storage modifications force scripts into while true; do aws rds describe-db-snapshots ...; sleep 60; done loops. Holding a runner open for hours wastes concurrency slots and collides with hard platform ceilings (for example, GitHub Actions’ 6-hour job execution limit on GitHub-hosted runners). On a self-hosted Jenkins fleet with 20 executors, 10 concurrent 4-hour upgrade jobs pin half of the organization’s CI capacity solely to sleep 60 loops.
  3. Orphaned Cloud State: When a CI runner dies mid-upgrade, the AWS RDS control plane continues executing the upgrade or snapshot in the background while Jenkins marks the build ABORTED or FAILED. The control plane and infrastructure diverge immediately, forcing engineers to reconstruct state manually from AWS CloudTrail logs and RDS event streams.
  4. Missing Saga Compensation: Multi-step failovers are distributed transactions. If a workflow promotes a replica and updates Route53 DNS at step 3, then fails post-cutover validation at step 4, aborting leaves traffic split or degraded. Linear pipelines lack native Last-In, First-Out (LIFO) backward compensation, so every partial failure becomes a manual incident.

Four constraints where linear CI runners break: volatile RAM, while-sleep timeouts, orphaned cloud state, and missing Saga compensation

The core engineering question is: How can platform teams replace volatile CI/CD scripts with event-sourced state machines that checkpoint progress to persistent storage, survive arbitrary worker crashes, and guarantee deterministic Saga rollback?

Options Considered

ApproachState PersistenceWhere It BreaksDecision
Jenkins / GitHub ActionsVolatile runner RAM + log filesSpot eviction or 6h timeout loses state; no native LIFO Saga compensationRejected — fragile at hours scale
Cron + State Table in PostgresCustom polling daemon + SQL status columnTeams reinvent retries, backoff, heartbeats, locking, and replay semantics poorlyRejected — undifferentiated plumbing
AWS Step FunctionsManaged ASL JSON state machineHard to unit-test complex branching locally; 256 KB state payload cap; AWS-onlyPartial — viable for simple AWS-only flows
Temporal Durable ExecutionAppend-only event history in Postgres/Cassandra + stateless workersStrict determinism rules in Workflow code; 51,200-event hard history limitChosen — testable, cloud-agnostic durability

Comparison of CI/CD pipelines, AWS Step Functions, and Temporal durable execution

Hand-rolling a state machine table in PostgreSQL looks simple until you need exponential backoff, distributed worker leases, crash recovery mid-poll, and backward compensation. Every engineering team that starts with a migration_jobs table eventually builds a fragile, untested mini-scheduler on top of SELECT ... FOR UPDATE SKIP LOCKED. AWS Step Functions removes cluster operations, yet authoring complex LIFO Saga compensation and custom retry predicates in Amazon States Language (ASL) JSON is cumbersome to unit-test locally, caps state payloads at 256 KB, and binds orchestration to AWS APIs. Temporal keeps orchestration in typed Go, Python, or TypeScript code with an in-memory replay test framework (TestWorkflowEnvironment) that validates branching and compensation in milliseconds without spinning up cloud resources.

The Durable Execution Architecture: Event-Sourced Orchestration

In Temporal, workflow state is persisted as an append-only event log in a backing database (PostgreSQL or Cassandra). Workers are stateless Go or Python processes that long-poll task queues over gRPC. If a worker pod is OOM-killed at hour four of an upgrade, a surviving worker replays the recorded event history to reconstruct exact local variables and resumes from the last completed checkpoint.

Temporal architecture: Frontend and History Service backed by PostgreSQL/Cassandra, stateless EKS workers, and idempotent RDS APIs

flowchart TD
    A[Temporal Frontend — gRPC] --> B[History Service — State Shards]
    B --> C[Event History DB — Postgres or Cassandra]
    D[Stateless Worker Pod 1] --> A
    E[Stateless Worker Pod 2] --> A
    D --> F[AWS RDS Control Plane]
    E --> F

1. Workflows vs. Activities: Enforcing Determinism

Temporal separates orchestration into two primitives:

  • Workflows (Pure Determinism): Define state transitions, timers, and conditional branching. Because Temporal reconstructs state by replaying the Workflow function from the start against the recorded event log (WorkflowExecutionStarted, ActivityTaskScheduled, ActivityTaskCompleted), Workflow code must be strictly deterministic: no time.Now() (use workflow.Now(ctx)), no random numbers, no direct network or SQL calls, and no iterating over Go maps with randomized key order.
  • Activities (Side Effects): Encapsulate all external I/O—AWS SDK calls, SQL queries, DNS updates, and Slack alerts. When a Workflow replays after a worker crash or sticky-cache eviction, completed Activities are not re-executed; Temporal injects their recorded results directly from the event history.
  • History Bounding via Continue-As-New: For long-running fleet monitors or multi-day migration loops, workflows check workflow.GetInfo(ctx).GetContinueAsNewSuggested() (which triggers well before the 51,200-event hard ceiling) and return workflow.NewContinueAsNewError(...). This atomically closes the current run, rotates the RunID, keeps the same WorkflowID, and starts a fresh empty event history with the carried-over state.

2. Activity Heartbeating, Timeouts, and Idempotent Polling

Instead of blocking a CI runner with while-sleep, long-running cloud operations execute inside an Activity that polls asynchronously and emits Heartbeats back to the Temporal History Service. Configuring three distinct Temporal timeouts keeps failure detection tight without aborting legitimate multi-hour work: StartToCloseTimeout bounds a single execution attempt (for example, 6 hours for a multi-terabyte snapshot), HeartbeatTimeout bounds how long a worker can go silent before Temporal assumes the pod crashed (for example, 2 minutes), and RetryPolicy controls exponential backoff across transient cloud API errors. Note that Temporal only delivers cancellation signals to an Activity if the Activity calls activity.RecordHeartbeat(ctx, ...)—without heartbeating, a worker will not learn that its workflow was cancelled until the attempt finishes.

func SnapshotDatabaseActivity(ctx context.Context, args SnapshotArgs) error {
	svc := rds.NewFromConfig(args.AWSConfig)

	existing, err := svc.DescribeDBSnapshots(ctx, &rds.DescribeDBSnapshotsInput{
		DBSnapshotIdentifier: aws.String(args.SnapshotName),
	})
	if err == nil && len(existing.DBSnapshots) > 0 {
		if *existing.DBSnapshots[0].Status == "available" {
			return nil
		}
	} else {
		if _, err = svc.CreateDBSnapshot(ctx, &rds.CreateDBSnapshotInput{
			DBInstanceIdentifier: aws.String(args.DBInstanceID),
			DBSnapshotIdentifier: aws.String(args.SnapshotName),
		}); err != nil {
			return fmt.Errorf("create snapshot failed: %w", err)
		}
	}

	ticker := time.NewTicker(30 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-ticker.C:
			resp, err := svc.DescribeDBSnapshots(ctx, &rds.DescribeDBSnapshotsInput{
				DBSnapshotIdentifier: aws.String(args.SnapshotName),
			})
			if err != nil {
				activity.RecordHeartbeat(ctx, "transient_describe_error")
				continue
			}
			status := *resp.DBSnapshots[0].Status
			activity.RecordHeartbeat(ctx, fmt.Sprintf("progress=%d", resp.DBSnapshots[0].PercentProgress))
			if status == "available" {
				return nil
			}
			if status == "failed" {
				return fmt.Errorf("rds snapshot failed")
			}
		}
	}
}

If the worker pod dies mid-snapshot, Temporal detects the missed HeartbeatTimeout (for example, 2 minutes), re-queues the Activity task, and dispatches it to another worker. The idempotent DescribeDBSnapshots check finds the in-progress snapshot and resumes polling without duplicating work.

3. Idiomatic Go Sagas with defer and Disconnected Contexts

Unlike Temporal’s Java SDK, the Temporal Go SDK does not ship a workflow.Saga struct. Idiomatic Go workflows implement LIFO Saga compensation using native defer closures, a named (err error) return, and workflow.NewDisconnectedContext(ctx) so workflow cancellation does not abort cleanup activities:

func UpgradeClusterWorkflow(ctx workflow.Context, params UpgradeParams) (err error) {
	ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
		StartToCloseTimeout: 6 * time.Hour,
		HeartbeatTimeout:    2 * time.Minute,
		RetryPolicy:         &temporal.RetryPolicy{InitialInterval: 5 * time.Second, BackoffCoefficient: 2.0, MaximumAttempts: 5},
	})

	if err = workflow.ExecuteActivity(ctx, SnapshotDatabaseActivity, params).Get(ctx, nil); err != nil {
		return err
	}
	if err = workflow.ExecuteActivity(ctx, RerouteTrafficActivity, params.MaintenanceEndpoint).Get(ctx, nil); err != nil {
		return err
	}
	defer func() {
		if err != nil {
			cleanCtx, _ := workflow.NewDisconnectedContext(ctx)
			err = multierr.Append(err, workflow.ExecuteActivity(cleanCtx, RerouteTrafficActivity, params.OriginalPrimary).Get(cleanCtx, nil))
		}
	}()

	if err = workflow.ExecuteActivity(ctx, ExecuteMajorUpgradeActivity, params).Get(ctx, nil); err != nil {
		return err
	}
	return workflow.ExecuteActivity(ctx, ValidateIntegrityActivity, params).Get(ctx, nil)
}

How It Rolls Out

Migrating fleet-wide database operations to Temporal requires proving crash recovery before touching production primaries:

Four-phase rollout from idempotent activities and chaos SIGKILL testing to production fleet scale

  1. Phase 1 — Idempotent Activities & Replay Tests: Wrap every cloud and SQL mutation in idempotent Activities (Describe before Create), add workflowcheck to CI to catch non-deterministic Go imports or map iterations, and write Temporal TestWorkflowEnvironment replay tests against saved production JSON histories. Gate: zero non-determinism errors across simulated replays.
  2. Phase 2 — Staging Chaos Recovery: Run a multi-step upgrade against a staging RDS instance and send SIGKILL to the active worker pod mid-snapshot. Verify that the History Service detects the missed HeartbeatTimeout and dispatches the task to a surviving pod. Gate: the second worker resumes heartbeating without duplicating snapshots, and an injected post-cutover error triggers the defer Saga cleanly with multierr.Append preserving both errors.
  3. Phase 3 — Non-Critical Fleet Canary: Onboard development and staging database upgrades first while monitoring workflow history size in Temporal Visibility. Gate: workflows stay well below Temporal’s 10,240-event warning threshold (or call workflow.NewContinueAsNewError for long-running monitors).
  4. Phase 4 — Production Rollout with Queue Rate Limits: Enable production schedules with per-task-queue rate limits (WorkerOptions.TaskQueueActivitiesPerSecond) so batch upgrades do not throttle cloud control-plane APIs, and configure HPA on worker pods based on task queue backlog. Rollback: pause the Temporal Schedule or drain the task queue while in-flight workflows finish or compensate safely.

In Practice

I have not run a 1,200-cluster PostgreSQL upgrade on Temporal personally; the design choices above follow Uber’s Cadence/Temporal architecture and documented Temporal Server and AWS RDS mechanics.

  • Event-Sourced Actor Orchestration (Uber Cadence / Temporal): Uber built Cadence (the direct predecessor to Temporal) to replace fragile cron and queue-based state machines for long-running distributed workflows, persisting every decision and activity result as an immutable event history so stateless workers can replay and recover from arbitrary host failures (Uber Engineering). Under normal execution, workers cache active workflow coroutines in memory via sticky task queues so each new event advances state in sub-millisecond memory without re-reading the full log; only when a worker crashes or evicts its cache does another worker fetch and replay the event history.
  • Bounded Event History & Replay Mechanics (Temporal Docs): Temporal enforces a hard limit of 51,200 events (or 50 MB) per workflow execution and logs warnings at 10,240 events (or 10 MB) because workers must replay the history on cache eviction or failover. Long-running loops must poll inside Activities or reset history with Continue-As-New (Temporal Event History).
  • Asynchronous Cloud Control-Plane Polling (AWS RDS): CreateDBSnapshot and ModifyDBInstance return asynchronously while storage blocks copy or engines upgrade in the background. Checking DescribeDBSnapshots or DescribeDBInstances before issuing mutations makes the Activity idempotent across Temporal retries and worker failovers, ensuring a network timeout after AWS accepts a request never triggers a duplicate failure on retry.

Where It Breaks

Edge CaseFailure MechanismConsequenceDetection & Mitigation
Non-Deterministic ReplayCode calls time.Now(), rand, or changes branching without versioning.Replay diverges from history; Temporal throws NonDeterministicWorkflowError.Enforce workflowcheck in CI; gate logic changes with workflow.GetVersion().
51,200-Event History CapWorkflow loops in-memory calling short timers or Activities repeatedly.History hits 50 MB / 51,200 events; Temporal terminates the workflow.Keep polling loops inside heartbeating Activities; use NewContinueAsNewError when GetContinueAsNewSuggested() is true.
Cancelled Saga ContextWorkflow receives cancel signal while defer compensation runs.Standard ctx is cancelled, aborting rollback Activities mid-flight.Wrap compensation calls in workflow.NewDisconnectedContext(ctx).
Non-Idempotent Cloud CallsNetwork timeout after CreateDBSnapshot succeeds on AWS side.Retry throws DBSnapshotAlreadyExists and fails workflow.Query DescribeDBSnapshots first; use client idempotency tokens where supported.
Tight HeartbeatTimeoutTimeout set shorter than AWS API throttling or backoff window.Temporal assumes worker died and schedules a duplicate Activity.Set HeartbeatTimeout to 2–5 minutes; heartbeat even on transient API errors.
Worker Versioning DriftNew worker binary deployed while old v1 workflows are mid-flight.v1 histories fail replay against v2 workflow control flow.Use workflow.GetVersion() or Temporal Worker Versioning build IDs.
Task Queue ThrottlingBulk script launches thousands of DB upgrades simultaneously.Cloud API rate limits (ThrottlingException) trigger retry storms.Cap TaskQueueActivitiesPerSecond and stagger batch schedules.
History DB SaturationTemporal’s backing PostgreSQL/Cassandra runs out of IOPS or disk.All fleet workflows stall because no new events can append.Run multi-AZ persistence with dedicated IOPS alarms and retention policies.

Four failure paths in Temporal database workflows: non-deterministic replay, 51,200-event cap, cancelled Saga context, and non-idempotent retries

April 2026 Update

Between 2023 and 2026, durable execution patterns for database platforms matured in three ways:

  1. Temporal Nexus for Cross-Namespace Contracts: Platform teams expose database upgrade or failover workflows as Nexus services, letting product teams trigger safe lifecycle operations from their own namespaces without sharing VPCs or raw database credentials.
  2. Worker Versioning & Managed Durable Backends: Temporal Cloud, Worker Versioning build IDs (which pin in-flight v1 upgrade runs to v1 workers while routing new runs to v2 workers), and AWS Step Functions Distributed Map reduced the operational burden of self-hosting Cassandra clusters and managing GetVersion() branches.
  3. Human-in-the-Loop AI Triage on Signals: When a database upgrade fails pre-checks, workflows pause on a Temporal Signal, pass the compact failure summary to a read-only diagnostic agent, and wait for an operator approval signal before executing compensation or retry.

Key Takeaways

  • Never keep multi-hour database state in CI runner RAM: Spot evictions, OOMs, and 6-hour runner caps sever the link between the pipeline and ongoing cloud API mutations.
  • Keep polling inside heartbeating Activities, not Workflow loops: Polling in Workflow code bloats event history toward Temporal’s 51,200-event / 50 MB hard cap.
  • Implement Go Sagas with defer and NewDisconnectedContext: The Temporal Go SDK has no built-in workflow.Saga struct; defer closures with a disconnected context ensure cancellations still unwind DNS and traffic routing.
  • Make every infrastructure Activity idempotent: Check DescribeDBSnapshots or instance state before issuing Create or Modify calls so timeout retries never fail on AlreadyExists.
  • Prove recovery with SIGKILL chaos tests: Verify in staging that killing a worker pod mid-snapshot resumes cleanly on a second worker before migrating production maintenance.

What to Do Next

  • Problem: Audit your database automation for while-sleep polling loops inside Jenkins, GitLab CI, or GitHub Actions runners.
  • Solution: Move multi-hour upgrades, snapshots, and failovers into an event-sourced Temporal workflow with heartbeating Activities and defer Saga compensation.
  • Proof: Run a staging chaos test where you kill the orchestrating worker process mid-snapshot and verify automated resumption without orphaned cloud resources.
  • Action: Enforce workflowcheck in CI, set HeartbeatTimeout to 2–5 minutes, and wrap all compensation calls in workflow.NewDisconnectedContext(ctx).

Sources to Verify

  • Temporal Documentation: Workflow Event History Limits & Continue-As-New (docs.temporal.io/workflows#event-history)
  • Temporal Documentation: Detecting Activity Failures & Heartbeats (docs.temporal.io/encyclopedia/detecting-activity-failures)
  • Temporal Go SDK Samples: Saga Pattern with defer and NewDisconnectedContext (github.com/temporalio/samples-go/blob/main/saga/workflow.go)
  • Uber Engineering Blog: Cadence: Open Source Actor Engine (uber.com/blog/cadence-open-source-actor-engine/)
  • AWS RDS API Reference: CreateDBSnapshot & DescribeDBSnapshots (docs.aws.amazon.com/AmazonRDS/latest/APIReference/)