The interview problem

Practice prompt

Design an engine for business workflows that reserve an item, create an external shipment and notify the customer. A workflow may wait for approval for days. Workers restart, acknowledgments are lost, and workflow code changes while executions remain active. Explain durable state, retries, replay, cancellation and safe upgrades.

Original system-design practice, not a reported company interview. All scale assumptions and protocols below are illustrative. Primary documentation retrieved September 27, 2026; publication date not stated; interview date not applicable.

1. Define the durability boundary

The engine must preserve accepted workflow inputs and committed decisions across worker loss. It should resume unfinished work without repeating already recorded decisions as new commands. This does not automatically make an external shipment creation exactly once. The engine's persistence transaction and the shipment provider's transaction are different boundaries.

Assign a business workflow ID with a documented duplicate-start policy. A client retry after a lost start response should retrieve the same logical execution rather than create another shipment workflow. Distinguish logical identity from an execution attempt or run identifier used for retries and history rollover.

Define business outcomes separately from engine execution status: completed, business-rejected, canceled with confirmed cleanup, failed with unresolved effects, and requiring operator intervention. Intervention may leave the business process unresolved rather than terminal. “Worker stopped” is none of these by itself. Show waiting-for-approval separately from a workflow that cannot make progress because a dependency is broken.

2. Separate decisions from external activities

client start / approval message → durable workflow history
                                           ↓
                                decision task dispatcher
                                           ↓
                                  replayable workflow code
                                           ↓
                             committed commands + task outbox
                                           ↓
                           activity workers → external services
                                           ↓
                              results appended to history

Shard histories by workflow ID. A persistence transaction appends a decision's events and task-dispatch intent with an expected history version. An outbox publishes task intents to workers. Duplicate delivery is expected; task identity and conditional result recording prevent two worker responses from both advancing the same logical transition.

Timers persist their due time and identity. A timer service schedules ready decisions after downtime; it does not require a sleeping process for every waiting workflow. Approval messages carry a stable message ID, authorization context and proposal version, and are durably deduplicated before influencing decisions.

Use leases or task attempts to coordinate workers, but fence stale completions through the authoritative history transition. Expiring a worker lease cannot retract an HTTP request already sent to an external service. External effects require their own idempotency or reconciliation protocol.

3. Make replay deterministic

Temporal's workflow documentation describes replay as checking generated commands against recorded event history. That is useful background for this design: recovery reruns decision logic against recorded outcomes, while already completed activities supply their recorded results rather than being invoked again simply because code is replaying.

Do not let workflow decisions depend directly on the current wall clock, fresh random values, mutable configuration or an unrecorded network response. Use recorded values or the engine's deterministic abstractions. Activity code may perform network I/O, but its returned result becomes history data that future replay can consume.

For example, a branch that reads today's shipping policy directly might choose a different provider when replayed next week. Record the applicable policy version as part of the decision. Preserve replay of past decisions while separately enforcing current authorization for new external actions; a recorded policy version must not bypass a later revocation. A business requirement to adopt a new policy for an active execution needs an explicit transition rather than silently changing historical behavior.

Replay should reproduce command history, not necessarily every incidental implementation detail. Still, nondeterministic iteration that changes the order of emitted commands can break recovery. Test real saved histories against candidate code before rolling it out.

4. Recover an external effect with a lost acknowledgment

The reserve activity completes and its result is recorded. The engine commits shipment activity S with stable operation key K. A worker sends K to the provider, which creates shipment X. The worker crashes before the completion reaches workflow history. The engine sees S as unfinished and schedules another attempt.

The replacement worker sends the same key and payload within the provider's supported deduplication scope and retention period. If the provider returns X, the worker records that result and the workflow can continue to notification. A new attempt ID must not become a new business operation key, or every retry can create another shipment.

If the provider offers lookup by operation key, reconcile before deciding what to do. If the key has expired and no authoritative lookup exists, preserve an unknown outcome and escalate. A timeout is not evidence that nothing happened. Retrying blindly or releasing the reservation can create inconsistent business state.

The engine can durably record one accepted completion for S while multiple attempts ran. That is an internal state guarantee. Exactly one shipment depends on the provider contract and the application's use of it. State both guarantees rather than describing the entire distributed process as exactly once.

5. Bound retries and cancellation

Classify transient failures, permanent input failures and unknown outcomes. Use exponential backoff with jitter, an attempt or elapsed-time budget and dependency-specific rate limits. Retrying a malformed address ten thousand times does not improve reliability. Many workflows retrying together can overload a recovering dependency.

A cancellation request becomes a recorded decision to stop new work and request cleanup where supported. It is not proof that a running activity stopped or that a shipment was undone. If an external operation is already committed, compensation is a new business action with its own identity, failure handling and audit trail.

Record compensation intent before dispatching it, and make it safe to retry. Release inventory only when shipment outcome and business policy permit it. If shipment cancellation remains uncertain, report incomplete cleanup instead of setting a generic canceled flag that implies all effects disappeared.

Race an approval message against a deadline in the authoritative event order. Define the policy for a message received before the deadline but processed afterward, and record the trusted receipt time if that matters. Do not let whichever worker's local clock happens to run first decide the business outcome.

6. Upgrade code without rewriting the past

Suppose old history records reserve followed by create-shipment. New code inserts an address-verification activity before shipment. Replaying old history under the new command sequence can diverge. Use a compatible version marker or route active executions to code that understands their recorded branch. Apply the new sequence to appropriately selected new executions.

Keep old executable behavior available for as long as active histories need it, or perform an explicit migration whose correctness is tested. Merely keeping a schema field called version does not ensure a worker honors it. Include version routing in recovery tests after worker restarts and deployment rollback.

For long-lived workflows, roll history into a new run with a compact continuation state at a safe boundary. Preserve logical operation identities, pending message handling and unresolved effects. A shorter history must not forget that a shipment exists or allow an old approval to be consumed twice. Keep required audit history under its own retention policy.

7. Calculate history and task load

Assume one million new workflows/day, thirty recorded events per workflow and an average serialized event size of 1 KB decimal. This produces thirty million events/day and 30 GB/day of logical history. Three replicas use 90 GB/day before indexes, backups and storage overhead. Thirty days of this workload represents 2.7 TB of replicated event bytes.

With three activities per workflow and an average of 1.2 attempts per activity, workers execute 3.6 million attempts/day, about 41.67/s on average. A twentyfold arrival peak suggests about 833.3 attempts/s under the same mix; synchronized retries can exceed that profile. Durable timers reduce waiting-worker requirements but not dispatch bursts.

If a cold replay consumes 0.2 milliseconds per event, a five-thousand-event history needs about one second of replay CPU under that benchmark. At a thousand such cold replays/s, replay alone requires roughly a thousand continuously busy CPU cores. Cache affinity and history rollover may help, but measure actual replay cost and avoid claiming an in-memory cache is the durable state.

8. Verify the guarantees under failure

Test crashes before command commit, after commit but before dispatch, after an external effect but before result persistence, and after result commit but before acknowledgment. Inject duplicate tasks, stale worker responses, duplicate approvals and timer bursts. Assert business identities and effects as well as final workflow status.

Track decision-task lag, activity schedule-to-start latency, retry counts, history size, replay failures and unknown external outcomes. A workflow that retries forever is not a successful reliability result. Give operators evidence and a supported repair path; manual history edits can break replay or duplicate effects.

History payloads can contain sensitive input and activity results. Minimize stored data, use access controls and preserve versioned references when large payloads live elsewhere. If a referenced object disappears while history still needs it, replay may fail despite an intact event log.

9. Trade-offs and follow-ups

Event replay provides an audit trail and recoverable decision state but constrains code evolution and increases history storage. A direct persisted state machine can simplify some upgrades while requiring equally careful transition and dispatch semantics. Durable workflows coordinate long-lived business processes; they do not eliminate the need for external consistency contracts.

Follow-ups: How do you process concurrent approval messages? What if an activity runs for hours? How do you change a workflow's policy mid-flight? What does compensation mean for an irreversible action? Which fields survive history rollover? How would you recover when the provider's deduplication window is shorter than the outage?

10. Self-review rubric

  • Define logical workflow identity and accepted-start behavior.
  • Persist history transitions and dispatch intent atomically.
  • Separate deterministic decisions from external I/O.
  • Recover a lost acknowledgment with a stable business operation key.
  • Distinguish cancellation requests from completed compensation.
  • Preserve replay compatibility across upgrades and rollover.
  • Calculate storage, retry load and cold-replay capacity separately.

Sources and related practice

Temporal: Workflow Execution overview, publication date not stated; retrieved September 27, 2026. Primary background for workflow history and replay. The engine protocol, external-effect example and capacity calculations are original practice, not vendor performance claims.

Continue with distributed transactions and leases and fencing.

Continue your preparation

Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.