Workflow Engine
1. Executive Summary
A workflow engine orchestrates long-running, stateful business processes across distributed services with durability, retries, timers, and human tasks. Principal-level design covers event sourcing of workflow history, deterministic replay, activity workers, saga compensation, versioning, and multi-tenant isolation.
This chapter designs a Temporal/Cadence-class engine executing billions of workflow steps per month with 99.99% durability guarantees and automatic recovery from worker crashes. Event history, at-least-once activity execution with idempotency, and explicit versioning strategy are mandatory interview topics.
2. Why This Topic Matters
Microservices need orchestration beyond naive message chains. Architects must explain:
- Orchestration vs choreography tradeoffs.
- Why workflow code must be deterministic (replay model).
- Activity vs workflow task separation.
- Compensation in sagas for partial failure.
- Long timers (days/weeks) without holding threads.
Failures include duplicate charges, stuck orders, and unrecoverable state from non-deterministic workflow code. Review Sagas, Idempotency, and Transactional Outbox.
3. Problems Being Solved
| Problem | Solution |
|---|---|
| Long-running processes | Durable workflow state |
| Partial failure | Retries; saga compensation |
| Timeouts / timers | Server-managed clocks |
| Human approval | Signal/wait patterns |
| Visibility | Workflow history query |
| Scale workers | Task queue polling |
| Version upgrades | Workflow versioning API |
| Exactly-once illusion | Idempotent activities |
4. Assumptions and System Model
Functional:
- Define workflows as code (order fulfillment, onboarding).
- Activities call external services (payment, email).
- Signals for external events; queries for read-only state.
- Cron/scheduled workflow starts.
- Cancel and terminate workflows.
Non-functional:
- Workflow history durable 99.999%.
- Activity task dispatch latency p99 < 500 ms.
- Support workflows running up to 1 year.
- 100K concurrent workflow executions per cluster.
- Multi-tenant namespaces.
| Assumption | Implication |
|---|---|
| Workflow code deterministic | No random/time without SDK wrappers |
| Activities may fail/retry | Idempotency keys required |
| At-least-once task delivery | Duplicate activity execution possible |
| History grows unbounded | Compaction/archival policies |
| Workers stateless | All state in server history |
5. Essential Terminology
| Term | Definition |
|---|---|
| Workflow | Durable function coordinating steps |
| Activity | Single unit of side-effecting work |
| Event history | Append-only log of workflow events |
| Replay | Re-execute workflow code from history |
| Task queue | Work distribution to workers |
| Signal | External async message to workflow |
| Query | Read-only workflow state without mutation |
| Timer | Durable sleep until deadline |
| Saga | Compensating transactions on failure |
| Run ID | Unique execution instance |
| Continue-as-new | Reset history for long workflows |
| Side effect | Non-deterministic op wrapped for replay |
6. Core Mechanism
6.1 Architecture
Figure 1: History service persists events; matching dispatches tasks to stateless workers.
6.2 APIs (conceptual)
StartWorkflow(workflow_type, workflow_id, input)
SignalWorkflow(workflow_id, run_id, signal_name, payload)
QueryWorkflow(workflow_id, query_name)
CancelWorkflow(workflow_id)
Worker.poll_task_queue(queue_name) → task
Worker.complete_task(result | failure)
6.3 Data Model
Workflow execution:
workflow_id, run_id, namespace, type, status,
start_time, close_time, parent_run_id?
Event history (append-only):
event_id, event_type, timestamp, attributes
Types: WorkflowExecutionStarted, ActivityTaskScheduled,
ActivityTaskCompleted, TimerFired, SignalReceived...
Task:
task_token, workflow_id, activity_id?, task_queue, attempt
Shard by hash(workflow_id) % num_history_shards.
6.4 Deep Dives
Workflow execution model:
- Client starts workflow;
WorkflowExecutionStartedevent written. - Matching enqueues workflow task to worker task queue.
- Worker polls task; replays history; executes until next yield (activity schedule, timer, wait).
- Worker returns commands (schedule activity, start timer).
- History service appends events; may enqueue new tasks.
- Repeat until workflow completes.
Deterministic replay:
- Workflow code re-run from event 1 on each task.
workflow.now()returns recorded time from history.- Random and external I/O only via activities or
sideEffect(). - Non-determinism causes workflow task failure—version carefully.
Figure 2: Event-sourced loop between history service and workers.
Activity retries:
- Exponential backoff: 1s, 2s, 4s… max 5 attempts.
- Non-retryable errors fail workflow (or trigger compensation).
- Idempotency key =
workflow_id + activity_id + attemptpassed to payment API.
Saga compensation pattern:
# Pseudocode workflow
try:
reservation = execute_activity(reserve_inventory)
payment = execute_activity(charge_payment)
except:
execute_activity(release_inventory, reservation)
execute_activity(refund_payment, payment)
raise
Figure 3: Saga forward steps with compensation on payment failure.
Versioning:
workflow.GetVersion("change-id", min, max)branches replay for old runs.- New deployments must not break open workflows' replay.
Continue-as-new:
- Workflows with millions of events (e.g., loop) call
continue_as_newto truncate history.
7. Step-by-Step Walkthrough
7.1 Order fulfillment
- Start
OrderWorkflow(order_id). - Activity: validate payment (idempotent charge).
- Activity: reserve inventory.
- Timer: wait 24h for fraud review window OR signal
approved. - Activity: ship; complete workflow.
7.2 Worker crash mid-activity
- Activity worker dies after payment succeeds but before reporting completion.
- Activity times out; retry scheduled.
- Payment API idempotency returns same result; activity completes.
- Workflow continues—no double charge.
7.3 Non-deterministic deploy bug
- Developer adds
Math.random()in workflow code. - Replay produces different command; workflow task fails permanently.
- Fix: use
sideEffect()or move randomness to activity. - Version gate for in-flight workflows.
7.5 Scheduled workflow cron
BillingWorkflowstarts 1st of month via scheduler service.- Each run new
run_id;workflow_idincludes2026-07for idempotency. - Duplicate scheduler tick does not double-bill—start API rejects duplicate workflow_id.
7.6 Human task timeout escalation
- Manager approval signal not received in 7 days.
- Timer fires; workflow escalates to skip-level manager via activity.
- Audit trail in event history for compliance.
7B. History Size Management
| Workflow type | Events/year | Strategy |
|---|---|---|
| Order | ~20 | Keep full history |
| Sensor tick | 1M | Continue-as-new daily |
| Subscription billing | 12 | Archive after close |
Mis-sized histories inflate storage and replay CPU—design event budget per workflow type at authoring time.
10A. Worker Scaling Formula
Activity tasks/sec = 5000
Avg activity duration = 200 ms
Workers needed = 5000 × 0.2 = 1000 concurrent activity workers
Add 30% headroom → 1300 workers across task queues
Workflow tasks lighter—fewer workers; profile separately.
| Phase | Key decisions |
|---|---|
| Requirements | durable orchestration, retries, timers |
| Scale | history shards; task queue workers |
| APIs | start/signal/query/cancel |
| Data | append-only event history |
| Deep dives | replay; idempotent activities |
8. Invariants and Guarantees
| Property | Guarantee |
|---|---|
| Durability | Accepted events never lost |
| At-least-once activities | May run multiple times |
| Workflow state | Derived from event history |
| Ordering | Events total order per workflow |
| Idempotent start | Same workflow_id dedup policy configurable |
9. Failure Scenarios
| Scenario | Mitigation |
|---|---|
| History shard loss | Replicated storage; multi-AZ |
| Task queue backlog | Scale workers; split queues |
| Poison activity | Max attempts; DLQ alert |
| Replay nondeterminism | Versioning; CI replay tests |
| History size explosion | Continue-as-new; archival |
| Clock skew | Server timestamps authoritative |
10. Performance Characteristics
100K concurrent workflows × 50 events avg = 5M events active
Event append: 1–5 ms per decision task
Worker poll long-poll reduces empty requests
History shard: 500–1000 RPS write per shard typical
Archival to object store after workflow close
11. Scalability Limits
| Limit | Mitigation |
|---|---|
| Hot workflow_id | Shard by hash distributes |
| Large histories | Continue-as-new |
| Activity fan-out | Parallel activities; batch |
| Matching bottleneck | Partition task queues by domain |
| DB size | Retention + cold archive |
12. Operational Considerations
- Metrics: task schedule latency, backlog depth, workflow failure rate, replay errors.
- Alerts: nondeterminism spike; queue age > 5 min.
- Runbooks: reset stuck workflow; patch with versioning.
- Load test worker capacity per task queue.
13. Security Considerations
- Namespace isolation per tenant.
- mTLS between workers and frontend.
- Encrypt workflow input/output if PII.
- AuthZ on start/signal APIs.
- Audit admin terminate operations.
14. Cost Considerations
Event storage grows with workflow count × steps. Archive closed workflows to S3. Right-size history shards vs over-sharding overhead. Self-hosted Temporal vs managed service ops tradeoff.
15. Production Implementations
| System | Notes |
|---|---|
| Temporal | Cadence fork; widely adopted |
| Cadence | Uber-origin workflow engine |
| AWS Step Functions | Managed state machines |
| Apache Airflow | Batch DAGs—not transactional workflow |
| Camunda | BPMN enterprise workflows |
Distinction: Temporal/Cadence share replay model; Step Functions JSON ASL is different paradigm.
16. Alternatives and Tradeoffs
| Approach | Pros | Cons |
|---|---|---|
| Choreography (events only) | Loose coupling | Hard to trace; no central state |
| Orchestration (workflow engine) | Visibility; sagas | Operational complexity |
| DB state machine table | Simple | Polling; timer pain |
| Step Functions | Managed | Vendor lock; expressiveness |
| Cron + scripts | Easy start | No durability guarantees |
| Two-phase commit | Strong consistency | Does not scale cross-service |
16A. Workflow Boundaries—What NOT to Orchestrate
Avoid workflow engine for:
- Single RPC with no retries needed
- Sub-100ms synchronous request path
- Pure CRUD without multi-step compensation
- High-frequency tick processing (millions/sec)—use stream processor
Use workflow when failure recovery spans minutes to days and human steps exist. Misapplied workflows add latency and ops burden without durability benefit.
16B. Disaster Recovery for Workflow State
History store is tier-0 data:
- Replicated across AZ; RPO < 1 min
- Regular backup restore drill quarterly
- Document behavior if history unavailable: queue new starts vs hard fail
- Multi-region: active-passive history with failover runbook
Losing workflow history loses in-flight business processes—same severity as payment ledger loss for order domains.
| "Activities run exactly once" | At-least-once; idempotency required | | "Any code in workflow" | Must be deterministic | | "Airflow replaces Temporal" | Different use case | | "Signals are synchronous RPC" | Async; may arrive before wait |
18.1 Human-in-the-Loop at Scale
Workflows involving thousands of approvals (vendor onboarding batch) use child workflows or continue-as-new per batch chunk—never single workflow with 50K signal waits. Pattern: parent fans out 100 child workflows each handling 500 items; parent aggregates completion via signal. Principal architects review fan-out limits in design doc before implementation—history event explosion has taken down production Temporal namespaces in anecdotal industry reports; verify limits against your engine documentation.
18. Principal Architect Perspective
- Idempotency keys on every activity touching money or inventory.
- Versioning strategy before first production workflow—retrofit is painful.
- Compensation design in same PR as happy path.
- Task queue isolation per team prevents noisy neighbor.
- Replay tests in CI catch nondeterminism pre-deploy.
19. Architecture Review Exercise
Scenario: Order state in Redis with cron pollers checking status.
Review: Migrate to workflow engine; durable timers; saga compensation; visibility API.
20. Whiteboard Explanation
"Clients start workflows via frontend API. History service appends events to sharded durable store. Workflow workers poll tasks, replay event history deterministically, and submit commands to schedule activities or timers. Activity workers poll separate queues, call external services with idempotency keys, and report results as events. Matching service routes tasks. Signals inject external events. All state is event history—workers are stateless and replaceable. Versioning guards replay compatibility on code changes."
21. Interview Questions
- Design durable order workflow. — Signals: event history, activities, saga. Red flags: DB polling.
- Orchestration vs choreography? — Signals: visibility vs coupling. Follow-up: when choreo OK.
- Why deterministic workflow code? — Signals: replay model.
- Activity retry without duplicate charge? — Signals: idempotency key.
- Long timer 30 days? — Signals: server timer event, not sleep().
- Worker crash handling? — Signals: task timeout, redispatch.
- Workflow versioning? — Signals: GetVersion pattern.
- Scale history storage? — Signals: sharding, continue-as-new, archive.
- Human approval step? — Signals: signal + wait condition.
- Query workflow state? — Signals: query API without side effects.
- Poison message activity? — Signals: max attempts, DLQ.
- Multi-tenant isolation? — Signals: namespace, task queue.
- vs Step Functions? — Signals: code-as-workflow vs JSON ASL.
- Saga compensation example? — Signals: release inventory on payment fail.
21B. Extended Interview Question Deep Dives
Q15 (Principal): 2-year subscription billing workflow—history millions of events.
Strong signals: Continue-as-new monthly; archive closed periods to object store; query API returns summary not full history by default. Red flags: Single run accumulates all events.
Q16 (Principal): Regulatory requirement: prove who approved wire transfer 18 months ago.
Strong signals: Event history immutable; signal payload includes approver identity; export workflow history for audit; retention policy matches regulation. Link Architecture Decision Records for policy storage.
- Workflow update patch. — Server-side migration of running instances.
- Event history export for audit. — Compliance replay.
22A. Production Low-Level Design (Interview + Game Day)
Workflow LLD: durable orchestration history + worker activity execution (at-least-once).
Context diagram
Step-by-step flow:
| Step | Action |
|---|---|
| 1 | Durable start; workflow id |
| 2–4 | Activities via queue; heartbeats |
| 5 | Timers, signals, compensations |
Production stack
| Layer | Choice | Role |
|---|---|---|
| Orchestrator | Temporal / Cadence-like | Decision replay |
| History | Append-only per run | Recoverability |
| Task Q | Matching service | Activities |
| Workers | Stateless fleets | Side effects |
| Visibility | Advanced search | Ops |
API + schema
StartWorkflow({ id, type, input, idempotency })
SignalWorkflow / QueryWorkflow
ActivityComplete / ActivityFail
| Entity | Fields |
|---|---|
workflow_run | id, run_id, state, version |
history_event | seq, type, payload |
activity | id, attempt, lease |
Happy-path sequence
Failure — duplicate activity
Observability + SLO
| SLI | Idea |
|---|---|
| Schedule-to-start | |
| Activity success | |
| Sticky workflow backlog | |
| History size growth |
22B. Game Day Playbooks
Catalog
| ID | Drill | Inject | Signal |
|---|---|---|---|
| GD-1 | Activity timeout storm | Slow dependency | Retries + backoff |
| GD-2 | Orchestrator partition | Kill node | Replay recover |
| GD-3 | Non-idempotent pay | Dup charge | Detect & refund |
| GD-4 | Poison payload | Bad input | Fail workflow |
| GD-5 | Timer wake lag | Clock / backlog | SLA |
| GD-6 | Version skew | Worker old | Compatible builds |
GD-1 — Activity timeout (detailed)
GD-3 — Duplicate charge attempt (detailed)
Pass criteria: ledger shows one capture; workflow eventually completes.
23. Strong Answer Example
Question: "How handle payment activity that may run twice?"
Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—activities are at-least-once; make the charge idempotent.

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.
Student interview script (PRACTICE)
P — Problem framing
"In Temporal-class engines, activities are delivered at-least-once. A worker can charge the card, crash before reporting completion, time out, and the engine retries the same activity. If the payment call isn't idempotent, the customer is billed twice.
The workflow layer does not give you exactly-once side effects. Safety lives in the activity + payment service + PSP.
Short answer: Derive a stable idempotency key (e.g.
workflow_id+activity_idor apayment_intent_id)—not the retry attempt number—pass it to the payment API/PSP, persist key → charge_id locally, and on retry return the same result. Reconcile for money paths."
R — Requirements
| Requirement | Design |
|---|---|
| No double charge on retry | Same idempotency key across attempts |
| Safe after crash mid-activity | Local ledger + PSP key both dedupe |
| Workflow can still retry | Activity returns success with same charge_id |
| Audit / support | Log duplicate attempts; link to workflow_id |
| Intentional refund | Separate compensate activity—not "retry = undo" |
"I'd ask: authorize vs capture? Which PSP? Is
workflow_idunique per checkout?"
A — Assumptions (state aloud)
| Assumption | Why it matters |
|---|---|
| Engine retries on timeout / worker death | Duplicate execution is normal |
| PSP supports Idempotency-Key (or equivalent) | External fence for charges |
| Payment service has a DB | Store key→result for app-level dedupe |
| Workflow code is deterministic | Replay doesn't invent new keys |
| At-least-once ≠ bug | Design for it |
"I'd correct a common trap: don't put
attemptin the PSP idempotency key—that defeats retries."
C — Capacity
Dedupe / payment_attempts table → unique(idempotency_key); cheap
PSP idempotency store → their SLA; still keep local record
Activity timeouts → longer than p99 PSP; heartbeats for long calls
Reconcile job → low QPS, high value for money drift
"I'd rather pay for a unique index and PSP keys than 'hope the activity runs once.'"
T — Topology (draw this)

Figure B: Stable idempotency key → local unique insert → PSP with same key → retries return the same charge.

Figure C: Crash/retry/duplicate delivery causes; defenses are local dedupe, PSP keys, heartbeats, reconcile—not "exactly-once activities."
| Layer | Role |
|---|---|
| Workflow | Schedules ChargePayment; records result in history after complete |
| Activity | Performs side effect with stable idempotency key |
| Payment DB | UNIQUE(idempotency_key) → charge_id / status |
| PSP | Honors Idempotency-Key; returns same charge on replay |
| Compensate | Explicit RefundPayment activity if saga rolls back |
I — Invariants (safety)
"Non-negotiable:
- Activities are at-least-once—never claim exactly-once execution.
- Idempotency key stable across retries for the same logical charge.
- Local unique constraint + PSP key—defense in depth.
- Don't include attempt number in the money key.
- Compensation is intentional (refund activity), not a side effect of retry.
- Reconciliation compares workflow outcomes ↔ payment ledger ↔ PSP."
C — Constraints (second C)
| Constraint | Design response |
|---|---|
| Crash after PSP success, before activity complete | Retry + same key → same charge_id |
| Crash after local insert, before PSP | Retry; insert no-op or resume; call PSP with same key |
| Non-idempotent PSP | Don't use for auto-retry; or wrap with strong local ledger + careful capture |
| Long PSP calls | Heartbeats so activity doesn't false-timeout |
| Workflow nondeterminism generating new keys | Keep key derivation in activity from workflow_id/activity_id inputs |
| Poison failures | Non-retryable after N; alert; don't infinite-charge-loop |
E — Evolution (prove it)
Phased delivery:
| Phase | Deliverable |
|---|---|
| M1 | ADR: activities ALO; payment must be idempotent |
| M2 | payment_attempts unique key; PSP Idempotency-Key wiring |
| M3 | Chaos: kill worker after mock PSP success; assert one charge |
| M4 | Metrics: duplicate activity attempts, PSP idempotent hits |
| M5 | Nightly reconcile workflow paid ↔ PSP captures |
| M6 | Compensation path tested (refund) separately |
Failure modes:
| Failure | Mitigation |
|---|---|
| "Engine runs activities exactly once" | Teach ALO + idempotency |
| key includes attempt | Stable key only |
| Retry without PSP key | Double charge |
| Refund on every retry | Separate compensate activity |
| No reconcile | Silent money drift |
Observability: activity attempt count, idempotent hit rate, charge vs workflow mismatch, timeout/heartbeat failures, DLQ/poison.
Closing line (interview)
"So when a payment activity may run twice, I treat that as expected. I use a stable idempotency key from
workflow_id+activity_id, persist it in the payment service under a unique constraint, and send the same key to the PSP. Retries return the same charge_id—no double bill. I would not put the attempt number in that key. Heartbeats reduce false retries, compensation is an explicit refund activity, and we reconcile the ledger. The workflow engine gives durable orchestration—not exactly-once money movement."
Scoring signals
| Strong | Weak / red flag |
|---|---|
| At-least-once + idempotent charge | "Activities run exactly once" |
| Stable key (no attempt in PSP key) | New key per retry |
| Local DB + PSP defense in depth | Only "catch and retry" |
| Crash-after-charge scenario | Ignores timeout window |
| Explicit compensate ≠ retry | Refund-on-retry confusion |
| Reconcile / chaos proof | No money follow-through |
Compact outline (if time-boxed to 2 minutes)
"Activities are at-least-once. Stable idempotency key from workflow_id+activity_id—not attempt. Unique local row + PSP Idempotency-Key. Retries return same charge. Heartbeats, explicit refund compensate, reconcile."
24. Weak Answer Example
Question: "How handle payment activity that may run twice?"
"The workflow engine runs each activity exactly once, so we just call the payment API. If it fails we retry."
Why weak / red flags: Assumes exactly-once activity execution; no idempotency key; retry after a successful-but-unacked charge causes double billing—classic workflow money bug.
25. Hands-On Exercise
- Implement toy workflow with event log and replay.
- Add activity retry with idempotency map.
- Simulate worker crash mid-activity.
- Add signal handler for approval step.
- Extension: Continue-as-new after 1000 iterations.
25A. Extended Hands-On Lab
- Deploy Temporal docker-compose; run sample order saga with intentional payment failure.
- Record history JSON; modify workflow code; run replay test in CI.
- Measure task queue backlog vs worker count under 1000 workflows/sec synthetic load.
- Principal lab: Document compensation order for 5-step saga with external legal review.
25B. Production Readiness Review Questions
- Are all money-moving activities idempotent with proof in payment service?
- Can support query workflow state without engineer access?
- What is max history size before continue-as-new mandatory?
- Is nondeterminism alert wired to paging?
Workflow bugs are silent until replay fails in production—CI replay is non-negotiable.
- Why replay?
- Three saga compensation steps for order?
- What causes nondeterminism error?
27. Flashcards
| Front | Back |
|---|---|
| Event history | Append-only workflow state log |
| Replay | Re-execute workflow from events |
| Activity | Side-effecting external call unit |
| Signal | Async external workflow message |
| Task queue | Worker poll distribution |
| Idempotency key | Prevents duplicate side effects |
| Continue-as-new | Truncate history for long runs |
| Saga | Forward steps + compensation |
| Timer event | Durable server-managed delay |
| Namespace | Multi-tenant isolation boundary |
28. Cheat Sheet
REQUIREMENTS: durable workflows, retries, timers, signals
SCALE: history shards; task queue workers
APIs: start, signal, query, cancel
DATA: append-only events; task tokens
ARCH: frontend → history → matching → workers
DEEP: deterministic replay; idempotent activities
RELIABILITY: at-least-once; timeout redispatch
SECURITY: namespace; encrypt PII payloads
OPS: queue backlog; nondeterminism alerts
17A. Failure Scenario Drill
Deploy introduces time.Now() in workflow code—every open workflow nondeterministic failure; order pipeline stuck 48h. Mitigation: replay test in CI; canary worker pool; workflow.GetVersion gate. Principal blocks workflow changes without replay compatibility review.
18.1 Child Workflow Patterns
Parent starts child workflows for each line item—parent close policy ABANDON vs TERMINATE affects cleanup on parent cancel. Document policy per use case; wrong policy orphans compensating activities.
19A. Extended Review Scenario
Scenario B: Activity calls external API without idempotency—retry causes triple shipment.
Review: Idempotency-Key header; activity wrapper stores completion in side table keyed by workflow+activity id.
21A. Additional Interview Questions
- Workflow vs cron job? — Signals: cron starts workflow; durable state inside. Red flags: cron alone for multi-step money flow.
- Maximum history events? — Signals: continue-as-new at 10K–50K events; archive to object store.
28A. Principal Interview Deep Dive
Task queue naming convention
{domain}-{activity}-{priority} e.g. payments-charge-critical vs payments-charge-batch—isolates noisy batch from user-facing latency.
Signal vs Update (Temporal)
Signal: external event. Update: synchronous validated mutation with response—use sparingly; adds complexity to replay.
Compensation ordering
Compensate in reverse order of forward steps—LIFO. Payment refund before inventory release if payment succeeded last.
28B. Extended BOE Walkthrough
Interviewer: "Durable order saga across 5 services."
Strong candidate:
"One OrderWorkflow orchestrates: reserve → pay → ship. Each step activity with idempotency key. Failure after pay → compensate refund + release inventory.
History in sharded event store; workers stateless. Timers for fraud hold 24h via server timer event—not thread sleep.
100K concurrent orders: history shards ~500 writes/sec each; scale shards and task queue workers.
Integrate outbox via Transactional Outbox before starting workflow from DB transaction."
29. Related Concepts
- Sagas
- Idempotency
- Transactional Outbox
- Kafka-like Event Platform
- Payment Platform
- System Design Methodology
30. References
- Temporal documentation — workflow determinism and replay (official).
- Bernstein, Melnik — Saga paper (academic).
- Kleppmann, DDIA — stream processing and derived state.
Distinction: Replay model formalized in Temporal docs; saga theory from Bernstein et al.
30A. Further Reading Paths
Compare choreography using Kafka-like Event Platform vs orchestration here. Payment flows in Payment Platform should use workflow + idempotent activities.
30B. Workflow Testing Strategy
| Test type | Purpose |
|---|---|
| Unit | Activity logic mocked |
| Replay | Recorded history replay after code change |
| Integration | Test server + real activities in docker |
| Load | Task queue backlog under 10K workflows/sec |
Replay tests mandatory in CI for workflow package changes.
30D. Principal Architecture Review Checklist
- Replay compatibility test in CI for every workflow module change
- All activities touching external systems use idempotency keys
- Compensation paths tested—not only happy path integration tests
- Task queue isolation between batch and interactive workloads
- History shard capacity model documented with headroom
- Continue-as-new policy for workflows expected >10K events
- Namespace RBAC for prod workflow start/signal APIs
- Runbook: safe terminate vs cancel semantics documented for support
Workflow engines trade simplicity for operational discipline—nondeterminism and missing idempotency cause multi-day incidents.
30F. Closing Principal Note
Workflow engines reward teams that treat workflow code as production-critical infrastructure: deterministic, versioned, replay-tested, and paired with idempotent activities.
30G. Multi-Cluster and Multi-Region
Large enterprises run separate Temporal namespaces per region for data residency—workflows do not cross region boundaries; hand off via async events on Kafka-like Event Platform with idempotent consumers. Failover is namespace-level DR not active-active workflow migration—plan RPO for in-flight workflows explicitly.
30H. Support and Debuggability
Expose read-only workflow query API to customer support with strict RBAC—reduces engineering toil for "where is my order" tickets. Mask PII in query responses. Every workflow type should register human-readable status strings—not only internal state enum codes—for support tooling integration. Budget 2–4 weeks per major workflow for support UI and query handler implementation—often omitted and paid as ongoing toil tax. Workflow documentation should include sequence diagram of activities and compensation paths attached to each PR that introduces new workflow types. Run annual disaster recovery drill restoring history store from backup into isolated namespace and executing sample workflows end-to-end. Measure replay test coverage percentage in CI dashboard—target 100% of workflow packages before each release train. Failed replay tests block deploy same as failing unit tests for services owning workflow definitions. Principal sign-off on any workflow change touching payment or inventory requires attached replay CI green screenshot in change ticket. This single gate prevents more production incidents than adding another workflow worker replica.