Skip to content
Forward Deployed

Forward Deployed

Reliable Workflow Orchestration System

Orchestrate a days-long approval, payment, email and three internal updates so each business effect lands exactly once, state stays visible and failed steps are compensated.

Kind
Case study
Level
Core
View
Interview prep
Sections
4
By
Sourav Banerjee
Last updated
21 Nov 2026

Practise this as a worksheet: Reliable Workflow Orchestration System

Report an issue

Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.

Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.

Case brief

The case in one line: a long-running process across six systems where each business effect lands exactly once, state stays visible and a failed step is compensated, so nobody is ever charged twice.

30-Second Cheat Sheet

  • The process: one business process touches six systems: a document sign-off, a payment, an email and three in-house systems.
  • The waits: any step can fail, and the sign-off can sit untouched for days.
  • The hard constraint: the payment cannot be taken back, so the system must never charge twice, whatever else fails or retries.
  • The goal: apply each business effect of a long-running process exactly once, keep its state visible, and compensate when a step fails.
  • "Exactly once" is about the business outcome, not message delivery. Messages may arrive twice; the charge may not happen twice.
  • The core idea: durable history decides what has happened; workers only carry out steps, each under its own idempotency key.
  • The scale: 10 million active workflows, 100 million activities a day, week-long waits.
  • People stay in the loop at two points: the approver, and an operator with audited permission to resume, replay or compensate.

1. One Process That Must Never Charge Twice

The situation

  • A customer runs a business process that touches six systems:
    • A document needs sign-off.
    • A payment is taken.
    • An email goes out.
    • Three in-house systems are updated.
  • Any of those steps can fail. The sign-off can sit untouched for days.

Four people, four demands

Stakeholder What they want
Business sponsor Every case reaches the end
Operations lead Retries, a clear view of each case and a way to roll back
Application team No more fragile web of direct integrations
Auditor Proof of each approval: who gave it, when, and under which control

The hard constraint

  • The payment cannot be taken back.
  • So whatever else fails or retries, the system must never charge the customer twice.
  • The case asks for something more specific than "reliable":
    • Apply each business effect of a long-running process exactly once.
    • Keep its state visible.
    • Compensate when a step fails.

The terms that carry the whole case

Term Meaning
Workflow One run of the business process for one case, for example one order from approval to the final internal update
Activity One step inside a workflow that does real work, such as charging a card
Side effect A change outside the orchestrator: money moves, an email arrives, a CRM (customer relationship management) record changes
Exactly once Describes the business outcome, not message delivery. Messages may be delivered twice and steps may be retried. The charge, the email or the record change the customer can see must not happen twice.
Idempotency key A unique label sent with a request, so a repeated request with the same key returns the first result instead of acting again
Compensation An explicit business action that reverses or limits a side effect that already happened, such as a refund
Saga A multi-step process in which each step that can be undone has a matching compensation
Durable history An append-only record, stored outside any worker, of every attempt, signal, transition and result in a workflow

The core idea in one sentence

Durable history decides what has happened, and workers only carry out steps, each under its own idempotency key.

The loop in the source's core-idea figure:

durable history → scheduler reads it → queues the next step → worker runs it with a key → result goes back into history

  • A step that fails for good → a compensation, such as a refund.

2. Follow One Order Through the Process

  • The source's own code and tests use one order, o-123, for 5,000 cents.
  • The walkthrough returns to it whenever a mechanism needs a concrete case.

The happy trace

  1. Start.
    • The caller sends POST /v1/workflows/order_approval with the header Idempotency-Key: start:o-123.
    • The Workflow API validates the request, writes the first event to durable history and returns an instance ID.
    • If the caller times out and sends the same request again, it gets the same instance ID back, not a second workflow.
  2. Validate and wait.
    • The workflow checks the amount is positive.
    • It waits for approval for up to seven days.
    • Nothing sleeps in memory. A durable timer holds the deadline, and the approval arrives later as a signal.
  3. Charge.
    • Once approved, a worker charges the card with the key pay:o-123.
    • The payment provider returns a receipt, and the receipt is written to history.
  4. Update and notify.
    • The CRM update runs under crm:o-123.
    • The receipt email runs under mail:o-123.
  5. Compensate on permanent failure.
    • If the CRM update fails permanently, the workflow issues a refund under refund:o-123.
    • It records the failure and ends visibly failed, rather than quietly half-done.

Now break it

  • The charge succeeds and the worker crashes before it writes the receipt.
  • A naive retry charges the customer again.
  • This design prevents that: the decision to charge again, skip ahead or compensate is taken from durable history and the provider's receipt.
  • Never from what a worker happened to remember.

Where people stay in the loop

Who What they do
Workflow participant Gives or refuses the approval, with the case context in front of them
Operator With elevated and audited permission, resumes, replays or compensates one named instance when automation cannot settle it safely
  • Everything else runs without a person.

3. What You Need to Design

The task in one sentence

Design a reliable workflow orchestration system, as a Forward Deployed Engineer (FDE), for a document approval, a payment, an email and three internal systems, any of which can fail or wait for days.

  • "Exactly once" refers to the business outcome, not to individual messages.
Planning figure Value
Active workflows 10 million
Activities 100 million a day
Waits between some steps Week-long

By the end you should be able to

  • Explain the design end to end at interview depth, starting from that goal.
  • Answer follow-ups on:
    • Sizing for 10 million active workflows
    • Idempotency keys
    • Retry versus compensation
    • Durable timers
    • Tenant isolation
    • Changing the definition of workflows that are already running

What it assumes you know

  • Queues, retries and idempotency.
  • Basic distributed-systems ideas, such as at-least-once delivery.

At-least-once delivery = a message can arrive more than once but is never silently lost.

Who it's for

  • Interviews for Forward Deployed, solutions or applied-AI engineering roles.
  • Especially a round on payments, approvals, back-office automation or any long-running process that touches systems you do not control.

How the sections divide the work

  • Design walkthrough: the complete answer, in reasoning order. Read it first.
  • Technical deep dives: the records, code, tests and trade-offs behind it.
  • Practice (in the full casebook): the blank worksheet with worked answers behind reveals. Its level calibration table is worth rereading last.
  • Quick review: the card for the night before.

Quick Recall: Lines to Say in the Interview

  • "Apply each business effect exactly once, keep its state visible, and compensate when a step fails."
  • "Exactly once is about the business outcome, not message delivery."
  • "The payment can't be taken back, so whatever else retries, nobody is charged twice."
  • "Durable history decides what has happened; workers only carry out steps."
  • "Every side effect gets its own key: pay:, crm:, mail:, refund:."
  • "A seven-day approval is a durable timer and a signal, never a sleep in memory."
  • "A lost worker is not a lost charge: history and the provider's receipt decide what happens next."

Design walkthrough

The goal: a durable orchestrator that applies each business effect exactly once, keeps every case visible and compensates failed steps, so a crash after payment never charges the customer twice.

30-Second Cheat Sheet

  • Open with the outcome, not the tool: apply each business effect of a long-running process exactly once, keep its state visible, and compensate when a step fails.
  • Size it: 100M activities/day ÷ 86,400 s ≈ 1,157/s average; plan peaks at 3x to 10x; ~400 GB of raw history at 40 events × 1 KB.
  • Split deciding from doing: the control plane (registry, scheduler, timers, signal gateway, compensation engine, operations UI) decides; queues and workers act.
  • One owner of progress: only the durable history store. Queues deliver, workers suggest effects, the scheduler rebuilds from history.
  • One key per side effect: pay:, crm:, mail:, refund:. Never one key for the whole workflow.
  • Retry is not compensation: backoff spaces out attempts; only an explicit step such as a refund reverses a charge that landed.
  • Name each failure policy: fail closed on approval, payment and repairs; email degrades; CRM sync queues.
  • Release one workflow: prove replay determinism and crash recovery first, add operator visibility, then migrate by version behind a canary.

Spoken answer (source's two-minute opening): "So we have a document sign-off, a payment, an email and three in-house systems to coordinate, and each step might fail or stall for days. First I'd pin down whose workflow this is, which business event counts as done, and which steps need a person to approve and which run on their own. My working goal: apply each business effect of a long-running process exactly once, keep its state visible, and compensate when a step fails. Unless you say otherwise, I'll take durable state, retries, an audit history and recovery from worker crashes as given. Next I'd size the volume, the latency and how much failure we can absorb. Then I'd build the orchestration, security and observability on top of those numbers."


1. Frame the Outcome and the People It Serves

Turn the feature request into an outcome

  • Resist naming a tool first. Compare two framings:
Framing The line Problem
Feature-led "Let's build an orchestrator that calls the payment, email and three internal APIs." Accurate, but puts the wiring ahead of what the customer wants
Outcome-led "Apply each business effect of a long-running process exactly once, keep its state visible, and compensate when a step fails." Already demands most of the design
  • What the outcome-led line forces:
    • Exactly-once effects need idempotency and durable state.
    • Visible state needs a history people can read.
    • Compensation needs an explicit undo path.
    • Days-long waits need pauses for human approval.
    • An auditor needs a trail.
  • It names what we protect: a business transaction spread over days, not a stream of messages.
  • Turning vague customer words into a measurable goal is the habit panels hire FDEs for.

Separate the four jobs

  • Group stakeholders by the job each needs done, not by title. Lump them together and you optimise the wrong part.
Stakeholder Job to be done What "reliable" means to them
Workflow participants "Look at a case and decide, with the full context in front of them." Clarity about what they are approving
Operations teams "Spot stuck cases, learn the cause and bring each one back safely." Recovering cases without crossing integration boundaries
Application developers "Connect a system once, without writing bespoke retry code for every corner case." One integration contract instead of hand-rolled retries
Auditors "Rebuild the trail of decisions and check that each control held." A trail they can follow

Make each group concrete with the order:

  • The end user is a real person waiting for an approval or a payout, not "the API".
  • The operator is whoever is on call when a worker dies just after the payment went through.
  • The security owner rules on who may resume or override a stuck case.
  • The executive sponsor wants a predictable process that passes compliance and never has to be pieced back together from spreadsheets.
  • A strong answer meets every group's need, and no single group steers the whole design.

Open with a two-minute answer

  • The opening above (under the cheat sheet) does four things in under two minutes:
    1. Repeats the ask.
    2. Names who it serves.
    3. Sets the goal.
    4. Flags each assumption where facts are missing.
  • Under time pressure: ask fewer questions and make each one count.

What panels listen for:

  • Can you go from a customer's pain to a concrete design without vague platform talk?
  • Name the people, state assumptions out loud and describe success in the customer's words.
  • Draw the architecture only once you can say whose workflow changes and how success is measured. Before that, you are listing software features.

2. Ask the Questions That Change the Design

Spend questions where doubt is highest

  • You don't need equal depth on every subsystem. The interviewer will answer only some of what you ask.
  • Pick questions that remove the most doubt per minute.
  • Guard the riskiest constraint first: no business effect may happen twice when a step fails, pauses or comes back in the wrong order.

Four groups do most of the work:

Group Questions
The business finish line Which event says the workflow is done? Success when every technical step finishes, or when the business effect lands exactly once? For each kind of failure, roll back or compensate?
The workflow shape No humans, a person in the loop, or a blend? Which steps pause for minutes, hours or days? Can a case fork, loop back or be cancelled halfway?
Blast radius and ownership Which team owns each internal integration? Whose pager goes off when a case stalls? Who may resume, rerun or override a case?
Trust and compliance Which evidence must we keep for audit? Which actions need an approval log or signature trail? Do residency, retention or data-minimisation rules apply?

Tie each question to the decision it changes

  • A question earns its place when its answer moves a specific design choice. The source's question tree:
Question What the answer decides
In what order do the steps run, and can any branch or be skipped? A simple sequential runner, or a real state machine
Which steps can be undone after they succeed, and which cannot? Where compensation is safe and where retries need extra caution
What is the longest a workflow may stay open before it times out, is archived or is cancelled? Storage and timers; week-long waits rule out in-memory state and short-lived queues
At what point does a person approve, and how long may that approval sit? How to model paused states, reminders, escalations and cases nobody returns to
Do downstream systems accept idempotency keys, block replays or take a unique business reference? Yes → retries are safe. No → the orchestrator wraps each call in its own deduplication layer, which narrows the duplicate window but cannot close it: after a crash between the call and the record, choose to resend (at least once) or skip and reconcile (at most once)
If a definition changes mid-flight, how do older running instances stay compatible? Versioning, which bites the moment someone adds an approval step while 10,000 old workflows are live

Partial answers are no reason to stall.

  • State an assumption and tie it to the risk it covers.
  • When the interviewer holds back a fact, say so and record the gap.

Spoken answer (source's example): "I can't tell yet if payment is the final business effect or only one link in a longer approval chain. So I'll treat a payment retry as safe only when the provider honours idempotency keys and a durable workflow record proves the effect landed once."

  • The safest anchor: payment is the riskiest step and cannot be reversed. Whatever else degrades, the design must still block a second payment.

Keep an assumption ledger

Assumption ledger = a running list of things you treat as true until the customer says otherwise. Four fields: assumption, impact, verification, owner or follow-up.

Assumption Impact Verification Owner or follow-up
The payment provider accepts idempotency keys Decides whether a retry can run without charging twice Check the provider docs or ask whoever owns payments Payment integration team, before the design is final
Participants can live with a pause of several days Shapes how long state is kept, when cases expire and how people are notified Check with the business sponsor and the support team Product owner, ahead of any sizing work
  • Every discovery blends confirmed facts with provisional guesses.
  • A guess nobody writes down quietly turns into a design decision.
  • Separating checked requirements from assumptions often earns more credit than naming a product, and the ledger costs almost no time.

Leave discovery with four outputs and a success test

Discovery is real design work: it gives the system its shape. Leave with:

Output What it holds
Scope The workflows we will handle and the ones we will not
Assumptions The beliefs we act on until someone confirms them
Risks Where duplicates, lost data or unauthorised actions could creep in
Owners The named owner of every integration, approval, escalation and support route

Describe success the way the business would:

  • "Messages processed" and "tasks retried" are infrastructure measures.
  • Measure instead: completed workflows, duplicate-prevention rate, compensation success rate and mean time to detect stuck cases.
  • Check an operator can walk through any case from first step to last.
  • Interview-sized success test:
    • The business effect landed once.
    • The user sees where the case stands.
    • Each exception leads to a known compensation or escalation.

3. Rank Requirements and Fence the Scope

Must, should and could

  • A ranked list, not a wish list. Each must-have is there because a specific failure would otherwise hurt the customer.
Rank Requirement Why it is there
Must Durable state machine The workflow outlives a crashed process and waits out long pauses
Must Persisted transition history Operators see what happened; a restarted worker recovers intent from the record instead of guessing
Must Idempotent activity execution Retries will happen; a retry with no deduplication is a duplicate side effect under a nicer name
Must Retry and timeout policies Outside systems break, slow down and sometimes stay silent forever
Must Human signals and timers An approval usually arrives as a business event, not an API callback
Must Saga compensation and operator recovery Some steps can be reversed and some can't; the design has to show which is which
Should Versioned workflow definitions Running instances can evolve without breaking
Could Deeper analytics, bespoke dashboards, user-configured branching Allowed only if none of them puts correctness at risk

Keep functional and nonfunctional requirements apart

  • Functional (short): each case goes from approval → payment → notifications and internal record updates.
  • Nonfunctional: how safely it must do that. Survive crashes and even a lost region, keep an inspectable history, never pay twice, change without breaking workflows under way.
  • Mixed together the two lists hide trade-offs. Kept apart they show what the system does and how safely.

Each nonfunctional requirement in a testable form:

Requirement Testable form
Survive process and region failures After losing a worker or a whole site, the workflow resumes with no committed state lost. For a site loss, that holds only if a history write is replicated to a second region before it is acknowledged. With asynchronous replication the last few events can be lost on failover, so the recovering region must check the provider for any payment it has no receipt for.
No duplicate payment A business key, durable deduplication or the provider's idempotency mechanism guards the payment, and the same guard is used every time
Inspectable history Transitions, retries, approval signals, timeouts and compensation events all land in durable, queryable storage
Compatible evolution of running instances A definition change leaves no older execution stranded, and no running state machine is reinterpreted halfway through

Label constraints and preferences

  • A constraint shrinks the set of safe designs. A preference makes the system nicer but can give way.
Item Label
Irreversible payment handling Constraint
Human approval latency Constraint if the business waits days; preference if approvals usually land within hours
Workflow versioning Constraint once the customer confirms in-flight cases will outlive a deployment
A polished dashboard Preference
  • When an interviewer adds a "nice to have" partway through, label it before you respond. That keeps scope creep out of the architecture.

State what the first release will not do

MVP non-goals:

  • No branching logic written freely by users, no multi-tenant visual rule builders, and no promise of exactly-once delivery to every downstream system.
  • No attempt to make every action reversible. Payment and some external writes cannot be safely undone.
  • No keeping transition history forever. A clear retention policy sets how long it lives.
  • No single compensation strategy for every step. Some failures will need a person.

MVP = minimum viable product: the smallest release that proves the idea.

  • Trust comes from handling a few hard problems well, not from posing as a complete business-process platform on day one.

Trace each requirement to a component

  • The traceability table links each requirement to the parts that deliver it, and later to implementation and operations.
Requirement Primary component(s)
Durable state machine Workflow engine, persisted workflow store
Persisted transition history Event/history store, audit log
Idempotent activity execution Activity executor, deduplication keys, provider idempotency adapter
Retry and timeout policies Scheduler, timer service, retry policy engine
Human signals and timers Signal intake, approval queue, deadline manager
Saga compensation and operator recovery Compensation handlers, admin console, manual override path
Survive process and region failures Replicated storage, replayable execution model, failover procedures
No duplicate payment Payment guardrail, unique business reference, payment ledger check
Inspectable history Query API, history viewer, event export
Compatible evolution Versioned workflow definitions, migration rules, compatibility gates

Spoken answer (source's close for this step): "My assumptions are that payment can't be reversed, approvals can sit for days, and definitions will change while old instances are still live. Given that, I'll optimise for durable state, a clear history, idempotent side effects and version compatibility."

  • From patchy input that gives a system safe to ship, small enough to reason about and open to growth.
  • Next: turn these requirements into numbers and SLOs (service level objectives).

4. Size the Envelope That Breaks the First Draft

Why the average hides the problem

  • The usual first draft: a workflow service, a queue, a pool of workers, a state database and a blob store for attachments. At average load it holds.
  • Its weak spot is timing as much as volume:
    • Workflows idle for days.
    • Then approvals arrive in a batch, a payment gateway recovers or a downstream system comes back.
    • The work spikes at once.
  • Sized for the mean, it misses business deadlines once live.
  • So estimate the envelope: concurrent workflows, events emitted, state needing durable retention, task dispatch speed, and slack for peaks and partial outages.

Turn the scenario into a rate

  • Treat the scenario figures as planning inputs, not fixed truth: 10 million active workflows, 100 million activities a day, week-long waits.
  • That's a durable state machine whose population mostly sits idle while a smaller slice keeps moving.

The arithmetic:

  • 100,000,000 activities/day ÷ 86,400 s/day ≈ 1,157 activities/s on average, roughly 1.2k.
  • Don't provision for the mean. Work bunches in office hours, reminders go out in a morning batch, and a dependency outage holds retries back then releases them together.

The source's own planning choices (to defend, not to quote as industry standards):

Dimension Planning value
Average dispatch rate Roughly 1.2k activities/s
Peak dispatch rate 3x to 10x the average, set by how the customer uses the system
Headroom For a new system, at least double the observed peak; more if regional failover or retries matter
Growth Run the numbers at both 2x and 10x before fixing partition counts or storage layout

Keep workflow state small

  • Common scaling error: pushing everything into workflow history.
  • Durable state needs only the facts to replay, resume, audit and compensate: version markers, step status, timestamps, business references and correlation IDs.
  • Documents, PDFs, images and internal payloads live in object storage or a document store. The workflow keeps a pointer.
Payoff Why
Replay cost If every retry or rehydration drags megabytes into the engine, latency climbs and worker memory strains
Retention cost Audit often keeps histories a long time; large payloads on the hot path turn the operational ledger into a costly archive
Blast radius If every event carries its own payload copy, a leak or accidental change does far more harm

Soundbite: "The workflow points at the payload; it never becomes it."

Estimate history storage

  • Formula: active workflows × events retained per workflow × bytes per event.
  • 10 million is the scenario's figure. 40 events and 1 KB per event are the source author's illustrative choices.
Case Arithmetic Raw history
Base 10,000,000 × 40 × 1 KB ≈ 400 GB
Bigger events 2 KB per event ≈ 800 GB
Bigger active set 20 million instead of 10 million Doubles again
  • All before replication, indexing, compaction overhead and backups.
  • The estimate tells you which dimension drives storage design. It's not a final figure.
  • For long retention, give the colder audit path its own home, apart from the hot execution path (task leases, execution metadata). Compaction, tiering and retention get simpler.

Estimate queue throughput

  • The task queue is where operations choke: every status update, payment request, internal call and approval notification becomes a queued task.
  • At 100 million/day: accept, lease and complete a sustained flow above ~1,157/s, and that still hides load.
Queue traffic Volume
Task enqueues Roughly in line with activity count
Leases and acknowledgements One or more per activity, more once retries start
Retry traffic After transient failures or worker restarts
  • Each activity needs at least an enqueue and a dequeue; leasing, visibility timeouts and requeues add more.
  • The queue must survive a retry storm and still serve new tasks.
  • Split queues by priority class, workflow type or tenant, so no single customer or runaway workflow family can monopolise dispatch capacity.

Check what breaks at 10x

Scenario Active workflows Activities/day Avg activities/sec Likely architectural pressure
Base case 10M 100M ~1.2k Durable history, moderate partitioning, a warm worker pool
10x growth 100M 1B ~11.6k More aggressive sharding, tighter queue isolation, heavier compaction and tiering
  • The source author doesn't expect application-server CPU to give out first.
  • More likely to hit the wall: replay latency, queue hot spots, storage fan-out or operating cost.
  • If the design would need a full rewrite for that growth, say so, and pick a layout that partitions easily from day one.

Define SLIs the customer can feel

SLI = service level indicator: the measured quantity behind an objective.

SLI What it measures
Availability Share of time workflow submission, progress updates and operator controls can be reached
Latency Time to accept a new step, send out an activity and show a state change in the UI
Freshness Lag between a real-world event and its appearance in workflow state
Quality Rate of stuck workflows, failed compensations, missed transitions or duplicate side effects
Security Fraction of requests that pass authorisation correctly and are audited. Sensitive-data exposure is pushed toward zero by design, never claimed impossible.
Cost Cost per workflow or per thousand activities, plus the support effort operator intervention demands
  • Turn them into objectives the customer feels.
  • Few customers care whether a task lease takes 80 ms or 120 ms.
  • They do care when:
    • A payment step shows in the UI so late that an operator thinks it was lost and retries it by hand.
    • A workflow that ought to be compensating stays hidden for hours.

Keep retry and compensation apart

  • Capped exponential backoff with jitter: backoff_n = min(cap, base × 2^n) + jitter.
    • Spaces out attempts so a transient incident can clear and dependencies aren't hammered.
    • The retry deep dive works through the variables and an illustrative schedule.
  • Backoff is not compensation:
Situation Right move
Payment goes through, email fails Retry the email
Payment goes through, workflow later finds a validation error No backoff reverses the charge: explicit compensation (refund, or mark the case for review)
  • Retry says "try once more, later".
  • Compensation asks "which business action reverses or limits a side effect that already happened?"

Soundbite: "Backoff never stands in for a business-level reversal." Interviewers like to set this trap.

Let the stress point choose the components

  • Total workflow count rarely decides the architecture. The mix of long waits, visible state and safe side effects does.
    • Week-long waits → durable storage and replay.
    • 100 million daily activities → a scalable queue and a partition strategy.
    • Side effects you can't undo → compensation tooling, unique business keys and idempotency.
  • The source's figure as a decision: find the estimate that dominates, then invest where it points.
Dominant estimate Invest in
History volume Storage tiering and retention
Dispatch rate Queue partitioning and worker elasticity
External APIs Retries, circuit breaking and per-integration throttles
Manual recovery cost Observability, the operator UI and audit trails

Say the uncertainty out loud

Spoken answer (source's example): "I'd take 10 million active workflows as the starting working set. But I'd plan partitions and queue namespaces for a 10x sensitivity case, since growth and retry bursts rarely spread load evenly. If the customer later says only 20% of workflows run long, storage gets simpler. If they say 80% have week-long waits, retention and the replay path jump to the top of my list."

  • Pick the smallest design that stays safe under realistic growth and failure. Don't build for every imaginable future.
  • Each number should back a choice or a limit. If a metric leaves partitioning, storage, retry policy, latency budget and support model all unchanged, it probably doesn't belong at the front of your answer.

5. Separate Deciding From Doing

Draw the outcome boundary first

  • Design back from the outcome: each business effect exactly once, state visible, failed steps compensated.
  • Retries still happen. "Exactly once" means:
    • Nobody is charged twice or sent the same message twice.
    • No step goes missing unnoticed.
    • You can show all of that.

Name the components and their plane

  • First draw the line: the control plane decides what happens next; the data plane does the work. Without it the parts never fall into place.
Component Plane What it does
Workflow definition registry Control Holds approved templates: step order, retry and timeout rules, which compensation undoes which step
Durable history store System of record Logs every attempt, signal, state transition, receipt and final outcome
Workflow scheduler Control Derives the next runnable transition from durable history and hands it off
Timer service Control Brings a workflow back after a delay, at a deadline or when a human wait ends
Signal/approval gateway Control Takes explicit signals from people or systems and releases the waiting workflow
Compensation engine Control After a terminal failure, runs business actions that undo, as far as they can, the steps already finished
Operations UI Control Live state, who blocks whom, retry history; pause, resume and override controls
Activity task queues Data Buffer the handoff from scheduler decisions to workers
Workers Data Make external calls, apply internal side effects, run local validation
  • Why the split: decision-making scales separately from side-effect execution. A burst of payment calls adds workers; it doesn't slow the scheduler's decisions about other workflows.

Follow a request top-down

  1. A caller sends an HTTP request carrying an idempotency key.
  2. The Workflow API looks up the permitted template and policy in the definition registry.
  3. It writes the opening event to the durable history store, and may notify the scheduler that a fresh instance can run.
    • If that notification is lost, the scheduler still finds the instance by scanning history for runnable work. A lost message delays the run but never strands it.
  4. The scheduler reads durable history and pushes runnable work onto the activity task queues.
  5. Workers pull from the queues and call internal systems A, B and C, the external payment system and the approval/document service.
  6. Workers write results and receipts into the durable history store.
  7. The timer service tracks deadlines and wakes workflows. The signal/approval gateway passes approvals, rejections and outside-system signals to the scheduler.
  8. When finished work must be unwound, the compensation engine sends compensations out through the queues.
  9. The operations UI reads the store and scheduler state, so operators can watch, pause, override or resume safely.
  • The source's architecture figure: control-plane services decide; queues and workers act on payment, approval/document and internal systems; the history store records every result.

Give each trust boundary its own policy

  • Three trust boundaries, each with its own authentication, authorisation and logging policy. Merging them into one generic "service layer" loses the differences that matter.
Boundary Why it differs
Public or customer-facing API Accepts the start request and its idempotency key, but can't count on the caller retrying with care
Worker edge Outside systems here may fail, time out or only partly finish
Human approval path Slow, error-prone, and every decision must be auditable

Give progress exactly one owner

  • Only the durable history store owns canonical progress.
  • Queues handle delivery; the truth doesn't live in them.
  • Workers suggest effects; they hold no truth either.
  • The scheduler doesn't trust its memory and rebuilds its view from history each time.

The central consistency rule: once an event is accepted, recovery runs off the history store's record of it.

Draw the synchronous edge narrowly

Synchronous (small) Asynchronous (most)
Validating the start request Activity dispatch
Authentication and permission checks Approval waits
Writing the first history event Timer wakeups
Returning the workflow ID Retries and compensation
Most operations-UI reads Most downstream calls
  • The boundary keeps the API quick while the business process behind it waits for days.
  • Everything synchronous → a fragile chain of requests that snaps when a human is slow.
  • Everything asynchronous without a solid history model → nobody can explain what happened; operators lose control.

Place queues, backpressure, caches and policy deliberately

  • Queues sit at the seam between scheduling and execution, not in the state store. They absorb bursts and stop slow workers holding up the rest.

Backpressure = slowing intake when downstream capacity is full.

  • Backpressure belongs in the scheduler and on queue admission. If one tenant, partition or dependency backs up, throttle new dispatches so retries can't swamp the fleet.
  • Cache only low-risk, often-read data: workflow definitions and UI summaries. A cache must never be the sole home of execution state.
  • Enforce each policy where its decision is made:
Policy Enforced in
Retry limits The scheduler
Approval rules The signal gateway
Permission checks Ahead of any compensation or manual override
  • The partitioning key (tenant ID, workflow ID, or a customer or process key) decides how history and queue load spread.
    • Aim for fewer hot spots and causal order where the business needs it, not raw scale alone.
    • When two steps of one instance must never race, pick a key that puts them in the same partition.

Tell four stories with one diagram

  • A product owner thinks in invoices and approvals; engineers think in retries, locks and queue depth. Both must follow the architecture.
Story Carried by
Data Caller → history → scheduler and worker → back
Identity Authentication, idempotency keys and approval context
State Durable history
Failure Retries, timers and compensation, rather than optimism

6. Trace the Happy Path and the Crash After Payment

The happy path, handoff by handoff

  • Time runs top to bottom, actors left to right. Skip no handoff: the interviewer should hear control leave the model, reach deterministic services and return.
  1. Caller → Workflow API: start a workflow with an idempotency key.
  2. Workflow API → durable history store: append the scheduled transition.
  3. Workflow API → scheduler: notify that the instance is runnable.
  4. Scheduler → activity task queues: dispatch the activity and record the attempt.
  5. Queues → worker: deliver the activity.
  6. Worker → external system: execute the payment, approval lookup, email or internal change.
  7. Worker → durable history store: commit the completion receipt.
  8. Scheduler → timer or signal gateway: wait on a timer or a human signal; it later wakes the workflow.
  9. Scheduler → queues: on a transient failure, retry per policy.
  10. Scheduler → compensation engine: on a terminal failure after partial completion, compensate the completed steps; the engine issues and records compensating actions.
  11. Scheduler → durable history store: close the workflow with an audit summary.

Read the flow as consistency points

The same flow as eight numbered guarantees:

  1. An idempotency key arrives with the start request, so a retry can't spawn a second business process.
  2. The API checks the request, then appends a scheduled transition to durable history.
  3. The scheduler picks it up, queues an activity and logs the attempt.
  4. A worker runs the side effect and writes a completion receipt to durable history.
  5. The workflow enters a wait state until a timer fires or a person signals.
  6. A transient failure gets a retry under policy, not instant escalation.
  7. A terminal failure after some steps are done triggers compensating actions for those steps.
  8. The workflow ends with an audit summary: route taken, waits and retries, manual interventions and the final effect.

Three consistency points hold it together:

  • The request is durable before anything downstream changes.
  • The side effect lands before the workflow reports success.
  • The audit summary comes last, because it's built from history, not worker memory.

The failure to rehearse above all others

  • Inject the fault: the payment goes through and the worker crashes before writing the receipt. Trace o-123:
  1. Caller starts with start:o-123; the API records the scheduled transition.
  2. Scheduler dispatches the payment activity and logs an attempt; the queue hands it to a worker.
  3. Worker sends the charge with pay:o-123; the payment system reports success.
  4. The worker dies before the completion receipt is written.
  5. The scheduler notices no completion arrived or a timeout expired, and chooses a path from the state on record.
  6. Transient or recoverable: the queue redelivers. The redelivered call reuses pay:o-123, so the provider returns the existing charge, and the worker records the receipt.
  7. Terminal after some steps are done: the compensation engine compensates the finished steps through the queue.
  8. The history store closes the workflow with an audit summary.
  • The charge may have gone through before the worker died, so "worker lost" must never be read as "business action lost".
  • Only the record prevents a double charge.

Soundbite (know it cold): "The durable history and the completion receipt decide whether to redeliver or compensate; worker memory never does."


7. Decide Failure Policy Before the Failure

Start from the uncomfortable question

  • The design review: security, operations and the customer's admin are in the room. Within minutes: "The payment went through, then the worker died; now what?"
  • That one injected fault teaches more than twelve happy-path questions: it shows the system's real edges.
  • What the orchestration layer protects: money movement, approval state, customer messages and downstream integrations.
  • From what: half-finished runs, replays, operator mistakes and hostile access.
  • A design that fails this drill is a best-effort script with a database behind it.

Four security controls

  • The threat model comes before failure policy. It rests on four controls:
Control What it means
Authorise starts, signals and repairs at the correct strength Start: at least permission to read the customer object it will change. Signals (approval, rejection, resubmission, cancellation, override): authenticated, limited to the right tenant and instance, checked against the current state machine. Repairs: the tightest control, because they can skip the normal sequence and change an effect after it happened.
Keep secrets out of history History is how the system remembers, so it's a target. A token, API key, password or full payment artifact stored there can be replayed, exported or shown to operators. Keep opaque references only; the worker fetches a short-lived secret at execution time from a secret manager or KMS-backed vault, narrowest scope, clear expiry.
Restrict operator mutation paths Operators pause, inspect and resume. They don't rewrite transitions or quietly mark money as collected. Every manual change goes through a narrow repair API (validates input, checks versions, logs the approval). Admin auth, role-based checks, immutable audit logs and state-machine rules guard the same boundary from different sides.
Audit every compensation and manual override Reversed payments, voided approvals and hand-repaired CRM records leave a trail: who, why, which instance, which state version. The post-incident review then rests on facts.

KMS = key management service.

Name how each branch fails

  • Say which branches fail closed, degrade, queue, need a person or may fail open. Using those words with care is itself a sign of judgement.
Policy Steps it applies to
Fail closed Approval completion, payment authorisation, repair mutations, and any step that could record a business effect that never happened
Degrade Email can fall back to queued sending or a later notice, if the customer accepts eventual delivery
Queue CRM sync, internal analytics updates and noncritical enrichment wait while a transient outage clears
Human intervention Unclear approvals, poison messages that keep failing, policy exceptions code can't settle safely
Fail open, only with extreme caution Occasionally a read-only status view; never an external side effect that can't be undone

Blast radius is a working control:

  • Partition every retry queue, dead-letter stream and repair lane by tenant, region, workflow type and dependency.
  • So a stuck CRM connector can't block document approvals for unrelated tenants.
  • A regional outage must not spill across a region line unless both the customer contract and the data policy allow it.

Dead-letter stream = holds items that keep failing, so they stop blocking the queue and wait for inspection.

Five drills, each with detect, contain, recover and prevent

Drill 1: the worker crashes after payment succeeds
Phase Action
Detect The lease expires, heartbeats stop or the orchestrator's timeout fires
Contain Never send the charge a second time
Recover Replay the history, see the charge step finished, continue at the first unfinished step
Prevent An idempotency key on the payment request; durable history writes the intent before the call and the completion once the acknowledgement arrives
  • A lease expiry presumes the worker is dead but doesn't prove it.
    • A slow worker can still complete the charge after redelivery starts.
    • So the payment key must protect concurrent calls as well as later retries.
    • Stripe answers a second same-key request that arrives while the first is still executing with a conflict and saves nothing; the worker retries later.
  • The source's figure: lease timeout → replay without reissuing the charge → check the recorded payment → transient loss continues from the next unfinished step; terminal failure triggers a refund.
  • This drill matters most. Security and operations inject the crash; you show how the system limits damage and keeps the evidence, not how you'd scramble.
  • A lost worker is not a lost business action. Tie detect, contain, recover and prevent back to durable history every time.
Drill 2: email succeeds but the CRM update fails
Phase Action
Detect Track side effects per step, not per job. The email worker may report success while the CRM update times out or returns a permanent error.
Contain The workflow doesn't claim full success; it moves to a state that can be compensated or repaired
Recover Retry the CRM call idempotently, hand it to dead-letter handling, or open a manual reconciliation task when a person must validate the record
Prevent A status for each step, explicit correlation IDs, and a policy that workflow state is authoritative and notifications are not
Drill 3: approval waits seven days
  • In orchestration a long wait is ordinary: durable timers, visible state and a way to deal with stale instances.
Phase Action
Detect No failure alarm fires. A timeout threshold routes the instance to the queue that should act on it.
Contain Don't burn worker capacity on polling that never ends
Recover By policy: send the reminder again, escalate to a manager or let the request expire
Prevent Waiting is a first-class state, not an improvised sleep loop
Drill 4: the definition changes while instances run
  • Treat it as versioning, not only deployment.
Phase Action
Detect The runtime notices the definition hash or version doesn't match
Contain Each old instance keeps running on the version it began with, unless an explicit migration path exists
Recover Route steps by version so old instances stay forward compatible, or run a controlled, tested and audited migration
Prevent Each durable instance stores its definition version; each deployment publishes a compatible contract or declares a deliberate break
Drill 5: an external API never answers
  • Four mechanisms: bounded timeouts, retries that back off, a circuit breaker, and a route to dead-letter handling or escalation.

Circuit breaker = stops calling a failing dependency for a while after repeated errors.

Phase Action
Detect No progress inside a known limit
Contain Stop hammering the dependency and shield the worker pool
Recover A scheduled retry, a fallback queue, or a person stepping in when the downstream system stays down for long
Prevent A time bound on every dependency call; policy treats transient and permanent failures differently

Have the evidence ready

Before go-live, be able to answer:

  • Who may start a workflow?

  • How does someone request a repair, and who signs it off?

  • Where do compensation logs live?

  • How is a replay explained to support?

  • How do you prove a crash didn't cause a duplicate payment?

  • Make the evidence searchable by tenant and workflow ID, kept as long as the customer's policy and jurisdiction require.

Observability:

  • Trace each transition with correlation IDs.
  • Emit counters for retries, compensations, dead-letter items and manual overrides.
  • Alert when requested, completed and compensated step counts drift apart.
  • Beyond "something is broken", know which tenant, which dependency and which failure policy is absorbing the impact right now.

Answer the trade-off pushes

  • Each push changes a dial and has a cost you should name:
Push Dial Cost
Faster recovery Automate more compensations Higher chance an automated undo gets it wrong
Stronger correctness Fail closed more often Deeper queues and more work for people
Many tenants Sharper blast-radius boundaries, tighter operator permissions Not stated as a cost in the source
  • An FDE is accountable for safe rollout, support and incident response, not only the happy path.
  • A good answer keeps the business effect safe, preserves evidence for the postmortem and moves the workflow forward without repeating any irreversible action.

8. Release One Workflow Behind Evidence

Model one workflow, not the platform

  • The prototype runs; the customer asks when they can rely on it. The conversation becomes a delivery plan with measurable gates, a named owner per step and a route into support.
  • Model a single workflow explicitly: document approval → payment → email → the three internal updates.
  • That slice shows whether business effects survive retries, pauses and crashes, and is small enough to reason through every transition.
  • The aim is learning, not breadth. Confirm:
    • The definition holds steady.
    • Anyone can inspect the state model.
    • The team can say what happens when a worker dies after the card is charged but before the email goes out.
  • Naming that first workflow signals MVP thinking and a staged rollout instead of one risky launch.

Make determinism and crash recovery the first gate

Test two things before any traffic grows:

  1. Replay determinism: feed a recorded history back through the engine; every decision must come out the same.
    • Only possible if workflow code is deterministic: it takes time, random values and activity results from history, never from the wall clock, a random generator or a direct network call inside the workflow.
  2. Crash recovery: kill workers mid-run, bring them back, check the engine resumes from durable state without blindly firing side effects again.

Spoken answer (source's gate): "I won't promote this until we can replay a run from its history, recover from a worker crash, and show that no irreversible effect happens twice."

  • Replay and crash recovery first, ahead of operator tooling and wider release, marks a seasoned plan. A weaker answer promises to "add monitoring later".

Give operators visibility before widening scope

  • With recovery proven: dashboards, logs, traces and admin screens.
  • Support should answer three things fast: what's in flight, what has stalled, what needs a human.
  • Workflow-level state in the business's words: pending approval, payment authorised, compensation pending, completed.
  • Beside it, activity signals: retry counts, timeouts, failed workers, queue depth and downstream latency.
  • Link the two so a user complaint leads straight to the failed step.
  • A good dashboard reads like the business story, left to right: request received → approval pending → payment authorised → internal systems updated → email sent → run closed.
  • Triage gets faster, the customer sees no black box, and visibility becomes part of what they buy.

Version workflows instead of mutating them

  • Ship changes as a new workflow version. Never edit running executions in place.
  • A run may wait days; swap its logic while it waits and old and new instances behave differently.
  • With versions:
    • A run keeps the rules it began with.
    • New runs get the new logic.
    • During an incident, operators know which history applies.
  • Customers trust the platform once changes ship predictably.

Score the rollout on six layers

  • Strong candidates don't squash every number into "the system is up". Each layer has its own data source, owner and alert.
Layer Metric Data source Owner Alert when
Technical health Workflow completion time: start to terminal state Orchestration history and timer records Platform team p95, or a customer-agreed threshold, moves well above baseline
Technical health Activity retry rate: retries over total attempts Worker and scheduler telemetry Worker-runtime owner A sudden spike, or a rate that stays high over a rolling window
Technical health Stuck workflow age: how long the oldest non-terminal run has waited past expected Durable state and queue inspection Operations Any run passes the maximum acceptable age
Model quality Replay determinism pass rate: sampled histories giving identical decisions on replay Replay test jobs and history checks Workflow-runtime engineering Drops under the release gate, because nondeterminism can break the whole model
Model quality State-transition validation failures caught by tests, canaries or runtime guards Engine validation and canary telemetry Platform team Any persistent rise: the model or versioning rules may have drifted
Model quality Schema or definition compatibility failures: changes old or new runs can't load Versioning checks and deploy-time validation Release engineering Any failure in staging or canary
Reliability and correctness Duplicate effect count: effects caught happening twice Idempotency logs, downstream receipts, reconciliation jobs Workflow platform and integration owner Any confirmed rise, because even a handful is costly
Reliability and correctness Compensation rate: share of runs taking a compensating action Workflow history Product and operations An unexpected climb: a bad release or brittle dependency
Operational burden Manual repair count: runs needing a person Operator actions and support tickets Support operations Outgrows team capacity or climbs release over release
Adoption Workflows real customers start, share of teams migrated, operator log-ins to visibility tools Product usage Not named in the source Not specified
Business outcome Fewer failed approvals, shorter payment-to-email gap, fewer escalations, shorter end-to-end cycle Business reporting Not named in the source Not specified

p95 = the value 95% of runs fall within.

  • "Model quality" means the orchestration model itself: whether the definition, replay behaviour and state transitions still match the business logic. Not an AI model.
  • Adoption matters: an elegant platform nobody trusts has failed as a product.
  • Technical health says the machine works; business outcomes say the customer gains from it.

Phase the rollout with owners and rollback triggers

Phase Owner Exit criteria Rollback trigger
1. Model one workflow explicitly A platform engineer with product or a customer design partner The definition has settled, each transition is written down, everyone agrees on the business effect The workflow can't be modelled cleanly, or the customer disputes what success means
2. Test replay determinism and crashes Platform engineering with QA (quality assurance) or release engineering Crash-recovery tests pass, replays are stable, failure drills show no duplicated side effects Some crash path repeats an irreversible action with no idempotency guard
3. Add operator visibility Operations with the orchestration team Operators find stalled work, explain its state and carry out approved repairs from written runbooks Support can't diagnose an incident without pulling in engineering
4. Migrate workflows by version Platform owner and release manager Old and new versions run side by side, migration rules are written down, no in-flight run is rewritten A versioned migration gives inconsistent results or blocks recovery
  • A real go/no-go gate never asks whether the code compiles. It asks:
    • Can support run it?
    • Can we execute the rollback?
    • Can the customer live with the remaining risk?

Decide what is core, adapter, configuration or shared

  • The core engine shouldn't hold everything.
Layer What goes there Why
Core product Durable workflow state, retry policy, compensation orchestration, replay, versioning, building blocks of operator visibility Reusable behaviours the platform should own
Adapters Payment gateway, email providers, document systems, the three internal systems Each behind its own interface, because they differ between customers and environments
Configuration Retry budgets, timeout windows, approval routing, escalation thresholds, per-tenant visibility Change more often than code, so adjusting them must be safe
Shared services Identity, audit logging, metrics export, notification plumbing where a standard exists Reuse cuts duplication only if ownership lines and support commitments stay intact
  • Product judgement: extract reusable value from the pilot rather than building a bespoke engine for one customer.

Train operators and own the risks

Production readiness means trained people and written guidance. The runbook covers:

  • A worker crash after payment.

  • An outside call timing out during approval.

  • An upstream system sending the same callback twice.

  • A run waiting on a human reply.

  • The docs explain how to read state, when and how to escalate, and which compensations an operator may safely trigger by hand.

  • Teach through scenarios: a stalled run, a clean replay and a rollback decision.

  • If operators can't explain a workflow from the dashboard and runbook, it's not ready for wide use.

The owned risk register (short, so rollout doesn't drift into wishful thinking):

Risk Owner Mitigation Trigger
Worker crash after payment succeeds Platform engineering Idempotency keys, durable state, replay tests; history and the completion receipt decide redelivery or compensation A payment event with no terminal workflow record
Replay nondeterminism Workflow-runtime team Deterministic APIs and history-driven replay tests A replayed decision differs from the recorded one
Operator overload Operations Dashboards, runbooks and tuned alerts The manual repair count keeps rising
Version migration error Release manager Version gating and a canary rollout Old and new runs reach different outcomes

The rollout story, in order:

prove one workflow end to end → check replay and crash recovery → give operators visibility → migrate by version behind a canary and a rollback plan

  • Watch six numbers throughout: completion time, retries, stuck age, duplicated effects, compensations and manual repairs.
  • Don't call it a success until customers use it, the business process improves and support runs it without heroics.
  • The measurable impact: each business effect exactly once, visible state, compensated failures, recovery under control and manual work falling. Approval, payment, email and internal updates run as one dependable service instead of a chain of brittle scripts.

Quick Recall: Lines to Say in the Interview

  • "Apply each business effect exactly once, keep its state visible, and compensate when a step fails."
  • "About 1,157 activities a second on average, but I plan peaks at 3x to 10x and at least double the observed peak."
  • "The workflow points at the payload; it never becomes it."
  • "The control plane decides, the data plane acts, and only the history store owns progress."
  • "Backoff never stands in for a business-level reversal."
  • "A lost worker is not a lost charge: the redelivered call reuses pay:o-123 and the provider returns the existing charge."
  • "Fail closed on approval, payment and repairs; email degrades, CRM sync queues."
  • "I won't promote this until we can replay a run from its history, recover from a worker crash, and show no irreversible effect happens twice."

Technical deep dives

What this part covers: the records, API contracts, saga code, tests, retry maths and trade-offs behind the design, plus the source's own view of where it is thin.

30-Second Cheat Sheet

  • Make the state machine concrete: it picks the next move after a step succeeds, fails or is replayed. Get it wrong and cards are charged twice.
  • Four records carry the design: WorkflowInstance, HistoryEvent, ActivityReceipt, Timer. The orchestrator records a payment but is never the financial ledger.
  • Four endpoints: start, signals, history, repair. 409 while a same-key request is in flight, 422 for a reused key with a different payload.
  • One key per side-effecting action: pay:, crm:, mail:, refund:. A deliberate new payment attempt needs a new key such as pay:o-123:2.
  • Read the saga's catch block critically: it wraps the email too, so a permanent email failure would refund a paid order.
  • Two tests carry the claims: a same-key start returns the same instance; a crash after payment refunds once and never charges twice.
  • Backoff: min(cap, base × 2^n) + jitter; AWS favours full jitter. No setting helps a charge that already landed.
  • Orchestrated saga over choreography: with choreography nobody can point to where a run stands.

1. Durable Records and API Contracts

Why the state machine is the part to make concrete

  • Boxes on a whiteboard don't convince an interviewer. Durable records, strict contracts and one code path that runs the riskiest part safely do.
  • The riskiest part is the state machine that picks the next move after a step succeeds, fails or is replayed.
  • The approval screen and email sender matter far less.
  • Get the state machine wrong and the customer suffers however healthy the rest is: cards charged twice, lost approvals, workflows that look frozen for good.

Four records carry the design

  • Each record has a purpose, a key, a lifecycle and a retention rule.
Record Purpose Primary key Lifecycle Retention
WorkflowInstance(id, definition_version, state, next_event) The single row that owns one business process: where it stands and where it resumes id Created at start, changed on each transition, archived or kept as policy requires Live row while running; a slimmer historical copy afterwards if audit or replay needs one
HistoryEvent(instance_id, sequence, type, payload_ref) Append-only trail that rebuilds the exact order of events without memory or short-lived logs (instance_id, sequence) New events appended; past events never edited While debugging, audits and replay need them; then cold storage or deletion by policy
ActivityReceipt(idempotency_key, external_ref, status) A note of each side effect tried or finished, so a retry can't pay again, email twice or repeat an update idempotency_key Written just before or just after the external effect, depending on how the dependency behaves As long as duplicates must be blocked
Timer(instance_id, fire_at) Wakes a workflow after a long wait, expires an approval or checks an outside job (instance_id, fire_at), or whatever key the scheduler uses Inserted when a wait starts, deleted when it ends, inserted again on retry Not stated in the source

Ownership is split:

  • The orchestrator holds workflow state, step history and the intent to retry.
  • External systems own payments, document approval, email delivery and CRM updates.
  • The orchestrator may record a payment, but it never acts as the financial ledger.

Order o-123 in the records:

  1. The instance row moves from waiting for approval → charging → onward.
  2. Each move appends a HistoryEvent with the next sequence number.
  3. The charge leaves an ActivityReceipt keyed pay:o-123 holding the provider's reference.
  4. The seven-day wait is a Timer row whose fire_at is a week after the request.

Four API contracts

Endpoint Purpose Auth Duplicate guard Response and errors
POST /v1/workflows/{type} Begin a workflow (type, business payload, caller context, optional correlation metadata) Normal caller auth, scoped to the tenant or customer Caller's idempotency key: a retried call never yields a second instance Instance ID, starting state, stable status reference. 400 malformed; 401 or 403 authn/authz fails; 409 while a same-key request is still in flight; 422 same key with a different payload, or inputs that make no business sense
POST /v1/workflows/{id}/signals Accept input from a person or another system Permission to signal that workflow or tenant Signal ID + payload hash, or a caller key, filters double-clicked approvals and repeated callbacks The accepted signal and the transition it caused, or a no-op if already applied
GET /v1/workflows/{id}/history Return the audit trail Read rights for the workflow's tenant and policy scope Never writes Pages sorted by sequence. 404 no such workflow; 403 access policy hides it
POST /v1/workflows/{id}/repair Operators, or automation they approved, resume, replay or compensate Elevated, narrowly scoped operator authorisation Each repair has its own idempotency token, so a double click doesn't double side effects Must state its action: retry a step, compensate a finished step or resume from a known checkpoint
  • Each endpoint is quick to explain yet strict enough that no client can slip vague work into the engine.

Caveat on 409/422: the split follows the IETF Idempotency-Key header draft, which had expired by September 2026. It's an Internet-Draft, not an RFC, so present it as a convention you adopt, not a standard you comply with.

  • Duplicates behave predictably: the first call with a key takes the money and saves a receipt; the second returns that receipt or a "completed already" response.

2. The Saga Step in Code

The source slice

  • One saga step: wait for approval → take payment idempotently → update the CRM → compensate if a downstream step fails for good.
  • Narrow on purpose. Production also needs a scheduler, queue workers, persistence, serialisation, distributed locking and stronger typing. The source keeps only the transitions an interviewer cares about most.
from dataclasses import dataclass
from typing import Protocol

class PermanentError(Exception):
    pass

@dataclass(frozen=True)
class Order:
    id: str
    amount_cents: int
    customer_email: str

@dataclass(frozen=True)
class PaymentReceipt:
    idempotency_key: str
    external_ref: str
    status: str

class Activities(Protocol):
    async def charge(self, order: Order, idempotency_key: str) -> PaymentReceipt: ...
    async def update_crm(self, order: Order, idempotency_key: str) -> None: ...
    async def send_receipt(self, order: Order, idempotency_key: str) -> None: ...
    async def refund(self, payment: PaymentReceipt, idempotency_key: str) -> None: ...

async def order_workflow(order: Order, activities: Activities, wait_for_approval):
    if order.amount_cents <= 0:
        raise ValueError("order amount must be positive")

    approved = await wait_for_approval(order.id, timeout_days=7)
    if not approved:
        return "rejected"

    payment_key = f"pay:{order.id}"
    payment = await activities.charge(order, idempotency_key=payment_key)

    try:
        await activities.update_crm(order, idempotency_key=f"crm:{order.id}")
        await activities.send_receipt(order, idempotency_key=f"mail:{order.id}")
    except PermanentError:
        await activities.refund(payment, idempotency_key=f"refund:{order.id}")
        raise

    return "completed"

Read it in the order you would explain it

  1. Order and PaymentReceipt are typed objects at the boundary, so the code never passes loose blobs around.
  2. PermanentError separates failures worth a business retry from failures that should start compensation.
  3. Activities is a protocol (an interface), not a concrete dependency. Easy to test, and vendor SDK details stay out of workflow logic.
  4. order_workflow(...) coordinates the saga. Its opening check rejects plainly bad input before any side effect: typed validation at the workflow's edge.
  5. Waiting for approval creates a pause that must survive restarts. In production a timer and stored state back it, not a bare function call.
  6. payment_key = f"pay:{order.id}" guards the charge, so a retry, a worker crash or a redelivered message can't trigger a second one.
  7. activities.charge(...) touches the outside world. The orchestrator reads the return value as a receipt; the payment ledger stays the source of truth.
  8. update_crm(...) and send_receipt(...) run after payment. except PermanentError compensates with a refund, and re-raising keeps the failure visible, so the orchestrator records the terminal state in history.

Read the catch block critically:

  • It wraps the email as well as the CRM update, so a permanent email failure would refund a paid order, while the failure-policy table lets email degrade to queued sending.
  • In a production definition, only steps whose failure voids the order trigger the refund.
  • A refund after the CRM write succeeded also needs a CRM compensation, or the record shows a sale that was reversed.

The source's saga figure: validate → wait for approval → charge with pay: → update CRM with crm: → send receipt with mail: → refund with refund: on a permanent error.

How fine-grained are the keys? (expect the question)

  • Each business action with a side effect gets its own key (pay:, crm:, mail:, refund:). The workflow as a whole doesn't share one.
  • If it did:
    • The CRM retry would collide with the payment's stored result.
    • A refund could be suppressed as a "duplicate" of the charge.
  • That detail moves an answer from a whiteboard sketch to something a team could run.
  • The limit of one key per action:
    • Stripe saves the first response once execution starts, including a decline or a 500 error.
    • So a retry under pay:o-123 returns that saved failure.
    • A deliberate new payment attempt (for example after the customer updates their card) needs a new key such as pay:o-123:2, written to history before the call.

Idempotency key = a unique label on a request so a repeat with the same key returns the first result instead of acting again.

What the whiteboard version leaves out on purpose

Omitted piece What production adds
Optimistic concurrency Each WorkflowInstance update checks a version number: "update where version = expected_version". If another worker got there first, retry or abort. Answers the worksheet's sixth failure mode: two workers moving the same instance forward.
Schema and contract versioning definition_version lets old and new definitions run side by side. An in-flight instance stays on its starting version unless an explicit migration policy says otherwise.
Idempotency at every write boundary Payment is one case. Repair actions, email sends, CRM updates and approval signals should be as safe to replay, where feasible.
Observability Every transition emits metrics, trace spans and structured logs tagged with step name, outcome and instance_id. The history table is the system of record; telemetry is for fast diagnosis.
Policy checks around model output An LLM (large language model) might classify, route or summarise inside a step. Before its output changes state or fires an external action, it passes typed validation and policy checks.

Soundbite: "The model may propose; it must not quietly decide."

The contrast an interviewer listens for:

Weak Strong
"We'll add retries, and that makes it reliable." Workflow state belongs to the orchestrator, each side effect has an idempotency key, each transition is versioned, each replay is driven by history and compensation is spelled out, never implied

3. Tests That Make the Design Believable

Contract test and failure-injection test

Test What it asserts
Contract test POST /v1/workflows/{type} twice with the same idempotency key → both responses carry the same instance ID
Failure-injection test charge(...) succeeds, the CRM update fails permanently, the workflow refunds, and replay finds the payment made and skips the charge
@pytest.mark.asyncio
async def test_start_workflow_is_idempotent(client):
    payload = {
        "workflow_type": "order_approval",
        "business_payload": {"order_id": "o-123", "amount_cents": 5000},
        "correlation_id": "corr-1",
    }
    headers = {"Idempotency-Key": "start:o-123"}
    first = await client.post("/v1/workflows/order_approval", json=payload, headers=headers)
    second = await client.post("/v1/workflows/order_approval", json=payload, headers=headers)
    assert first.status_code == 201
    assert second.status_code in (200, 201)
    assert second.json()["instance_id"] == first.json()["instance_id"]

@pytest.mark.asyncio
async def test_worker_crash_after_payment_does_not_double_charge(orchestrator, fake_activities):
    order = Order(id="o-123", amount_cents=5000, customer_email="a@example.com")
    async def approval(order_id, timeout_days):
        return True
    async def charge_succeeds(*args, **kwargs):
        return PaymentReceipt(idempotency_key="pay:o-123", external_ref="payref-1", status="captured")
    fake_activities.charge.side_effect = charge_succeeds
    fake_activities.update_crm.side_effect = PermanentError("crm unavailable")
    with pytest.raises(PermanentError):
        await order_workflow(order, fake_activities, approval)
    # On replay, the orchestrator should consult history/receipts and not charge again.
    await orchestrator.replay_from_history(order.id)
    assert fake_activities.charge.await_count == 1
    assert fake_activities.refund.await_count == 1
  • Together they show: the API contract is idempotent in practice, and the central drill holds. A failure after a successful payment ends in a refund; replay never charges twice.
  • Caveats:
    • The client, orchestrator and fake_activities fixtures aren't defined in the source.
    • Read the second test as the shape of the check; it needs a real orchestrator with persisted history to run.
    • A true crash-and-resume test (kill the worker between the two steps) works the same way: replay reads history, skips the charge, continues at the first unfinished step.

The no-double-charge invariant

  • The source's second sketch: crash at the worst moment; replay must still not repeat an irreversible side effect.
  • A teaching sketch sized for an interview: no persistence details, dependency wiring or full engine. Production would put the event log on durable storage, add validation and pin library versions.
class FakePayments:
    def __init__(self):
        self._charges = {}
    def charge(self, order_id: str) -> str:
        self._charges[order_id] = self._charges.get(order_id, 0) + 1
        return f"charge-{order_id}"
    def charge_count(self, order_id: str) -> int:
        return self._charges.get(order_id, 0)

class CrashAfterCharge(Exception):
    pass

class WorkflowEngine:
    def __init__(self, payments: FakePayments):
        self.payments = payments
        self.history = []
        self.completed = set()

    async def run_until_crash(self, order_id: str, crash_after: str | None = None):
        if "charge" not in self.completed:
            self.history.append(("intent", "charge", order_id))
            self.payments.charge(order_id)
            self.history.append(("done", "charge", order_id))
            self.completed.add("charge")
            if crash_after == "charge":
                raise CrashAfterCharge()

    async def resume_workflow(self, order_id: str):
        if "charge" not in self.completed:
            self.history.append(("resume", "charge", order_id))
            self.payments.charge(order_id)
            self.history.append(("done", "charge", order_id))
            self.completed.add("charge")
        self.history.append(("next", "crm", order_id))

@pytest.mark.asyncio
async def test_crash_after_payment_does_not_charge_twice():
    payments = FakePayments()
    engine = WorkflowEngine(payments)
    order_id = "order-123"
    with pytest.raises(CrashAfterCharge):
        await engine.run_until_crash(order_id, crash_after="charge")
    await engine.resume_workflow(order_id)
    assert payments.charge_count(order_id) == 1
  • The lesson: "attempted" ≠ "completed".
    • The engine writes an intent entry before the charge and a done entry after.
    • Recovery checks completion before deciding to repeat the effect.
  • What the sketch does not prove:
    • completed lives on the same in-memory object that survives the simulated crash, and this crash falls after done was recorded.
    • In a real system that set must be rebuilt from durable history.
    • The harder case: a crash between intent and done. Only the provider's idempotency key, or a lookup of its receipt, can tell whether money moved.
  • A production version would also: validate arguments, persist state, log in a structured format, handle timeouts and pass an explicit idempotency key to the payment gateway.

4. Retry, Backoff and Compensation

  • The formula: backoff_n = min(cap, base × 2^n) + jitter.
Variable Meaning
n The retry attempt number
base The first delay
cap The longest allowed delay
jitter Random variation, so many clients retrying at once don't fire in sync

Thundering herd = many clients retrying at the same instant and overwhelming a recovering dependency.

Illustrative schedule (values chosen in the casebook, not taken from the source):

  • With base = 1 second and cap = 60 seconds, attempts wait about 1, 2, 4, 8, 16 and 32 seconds, then 60 seconds for every later attempt, each plus jitter.
  • The cap stops the delay growing without bound.
  • The jitter spreads a thousand workers' retries across the interval instead of stacking them on one instant.
  • Caveat: adding jitter after the cap lets a delay overshoot the cap.
  • AWS's comparison favours "full jitter": a random delay between zero and min(cap, base × 2^n). It did less total work than variants keeping a fixed share of the backoff.

Choose cap and jitter as operational trade-offs, never by habit:

Setting Gain Cost
Low cap Recovers user-facing work faster Can swamp a flaky dependency
High cap Protects the dependency Customers wait longer to see progress
  • Neither setting does anything for a charge that already landed. That needs the compensation path in the saga code.

5. Trade-offs to Defend

Orchestrated saga

  • One control plane holds state transitions, retries, compensation and visibility.
  • Trace o-123: the scheduler records payment completed → dispatches the CRM update → sees it fail permanently → dispatches the refund.
  • An operator asking "where is o-123?" reads one history.
  • Suits long-lived, audit-heavy processes that must survive worker crashes and manual steps.
  • Cost: a central dependency that needs high availability and careful versioning.

Choreography

  • Services share the work by reacting to each other's events, with no central coordinator.
  • Trace o-123 again: the payment service emits "charged" → the CRM service reacts and fails → some service must notice and emit a refund request.
  • Gain: less central coupling; each service's ownership can look tidier.
  • Cost: nobody can easily tell where a run has got to or what halted it; cross-service compensation and human review get harder.
  • Where it fits: a small event-driven system. Once the customer wants visible state, controlled retries and recovery support can run, orchestration is easier to operate.

Spoken answer (to "why not let events drive it all?"): "Choreography lowers coupling, but then nobody can point to where a run stands, which rules it out when the customer needs visible state and support-run recovery."

  • Scale alone doesn't settle the question either way.

History size and debuggability

Choice Gain Cost
Keep every transition, input, output and retry Replay the path a decision took and see where it failed Growing storage, heavier reads, more care with redaction
Cut history Saves overhead Throws away the forensic record operators and support depend on
  • The defensible position: keep what you need to replay and explain each decision, compress or summarise older segments once safe, and hold the audit trail as long as customer policy says.
  • "Keep everything forever" is not the answer.

Automatic compensation and human review

Approach Works when Examples or cost
Automatic compensation The undo is deterministic and safe Cancel a reservation, void a pending authorisation, flag a record as failed, send a correcting notification
Human review queue A side effect is irreversible, unclear or regulated Slower, yet legal, financial or high-risk operational lines may demand it
  • The tension is speed against correctness. Full automation cuts latency and manual effort but can magnify a wrong call.

Workflow code and declarative definitions

Approach Gain Cost
Workflow code Rich branching, shared helper logic, complex compensation flows Harder versioning, more testing
Declarative definitions Easier to inspect and validate; non-engineers can follow them Can prove too rigid for the branching real enterprises need
  • Balanced position: a declarative model for the common shape, code for business-specific logic where it must.

6. Cost, Build or Buy, Governance and AI Risk

Where the source rates itself partial

  • The source author scored the tutorial twice against a fixed 20-item decomposition rubric.
  • Sixteen full, three partial (unit economics, regulation and governance depth, responsible-AI framing), one absent (build or buy and vendor choice).
  • Why the gaps fall there: the design goes deep on durable execution, idempotency and crash recovery, and doesn't invent detail on cost modelling and compliance frameworks it can't back up.
Phase Item Source rating Where it is taught
Problem framing and discovery 1. Feature request turned into a business outcome Full Turn the feature request into an outcome
Problem framing and discovery 2. Stakeholders and personas Full Separate the four jobs
Problem framing and discovery 3. Questions that reshape the architecture Full The question tree
Problem framing and discovery 4. Splitting and ranking requirements Full Must, should and could
Problem framing and discovery 5. A clear fence around scope Full MVP non-goals
Estimation and architecture 6. Rough sizing of scale and capacity Full Sizing
Estimation and architecture 7. What drives unit cost Partial: cost is an SLI but no per-workflow figure is worked out Cost per workflow
Estimation and architecture 8. Architecture and data flow end to end Full Architecture and flow
Estimation and architecture 9. Records and API contracts Full Records and APIs
Estimation and architecture 10. Build or buy, vendor and model choice Absent: touched once in the follow-ups Build or buy
Trade-offs, security and reliability 11. Named trade-offs with fair verdicts Full Four trade-offs
Trade-offs, security and reliability 12. Threats and controls Full Four security controls
Trade-offs, security and reliability 13. Failure and reliability drills Full Five drills
Trade-offs, security and reliability 14. How we test it Full Tests
Delivery, governance and communication 15. Layered metrics and observability Full Six-layer scorecard
Delivery, governance and communication 16. Staged rollout, risks and rollback gates Full Phases and risk register
Delivery, governance and communication 17. Depth on regulation and governance Partial: audit, retention, residency and minimisation, but no named framework Governance
Delivery, governance and communication 18. Responsible AI beyond the obvious failure Partial: LLM policy checks mentioned in passing AI risk
Delivery, governance and communication 19. Adoption and change management Full Operator training and adoption metrics
Delivery, governance and communication 20. Planned talk track and self-scoring Full Interview rehearsal (full casebook)
  • The four subsections below are the source author's own view of how to close each gap live, using only the architecture already built. They're that author's perspective, not part of the core design.

Cost per workflow (item 7)

  • Start from parts already sized: the base case holds about 400 GB of raw history as HistoryEvent rows.
  • At the AWS US East list prices the source checked in September 2026:
Storage List price Monthly for ~400 GB
S3 Standard $0.023 per GB-month About $9
gp3 block storage $0.08 per GB-month About $32
  • Both before replication. Small next to the manual repair count the scorecard already tracks.
  • The author's bet: people, not machines, drive cost.
    • cost per workflow ≈ infrastructure marginal cost + (manual repair rate × loaded operator cost per incident)
    • Both inputs come from metrics already collected: compensation rate and manual repair count. No new metric is needed.
    • The loaded operator cost per repair is a customer fact, so it waits for discovery.

Spoken answer (source's line): "We already have the inputs; we just haven't multiplied them yet."

Build or buy (item 10)

  • The state machine, history store and replay engine form the durable-execution core. Managed durable-execution products already do that job well.
  • Sensible default for most teams: buy the execution runtime, build the workflow definitions and activities.
  • Spend build effort only where you differ:
    • The compensation policy for each business action (the failure-policy table).
    • Where each idempotency key's boundary sits (the saga keys).
    • The domain saga logic, which is the order_workflow function itself.

Soundbite (the rule to say aloud): "Buy the commodity execution layer and let the vendor answer for keeping it durable and available; build only the business state machine and policy layer, because no vendor can get those right for you."

Regulation and governance (item 17)

  • Name the frameworks an interviewer is likely fishing for, and pin each to something already built.
Framework When it applies Pinned to
PCI DSS (Payment Card Industry Data Security Standard) If the orchestrator would ever handle card data Push card data to the payment gateway and hold only opaque references: matches "keep secrets out of history" and shrinks PCI scope. Caveat from the PCI tokenisation guidance: tokens that can start a transaction may stay in scope.
SOX-style controls (Sarbanes-Oxley Act) If an approval counts as a financial authorisation The ActivityReceipt record and audit-log fields already give the auditor the evidence trail
GDPR (General Data Protection Regulation) and data minimisation If an internal system handles PII (personally identifiable information) The retention policy on HistoryEvent, in line with Article 5's minimisation and storage-limitation principles
  • Frame governance as rules on records you already keep, not a new stream of work.

Responsible AI past the obvious failure (item 18)

  • The design touches AI in one place: before an LLM-driven step changes state, it must pass typed validation and policy checks.
  • Push it with a concrete case: an LLM misreads or misroutes an approval.
    • It could quietly approve something a person should have seen.
    • That's an irreversible business effect of exactly the kind the failure-policy table says to fail closed on.
  • No new framework needed:
    • Treat any model output that could start a payment, complete an approval or trigger a repair as untrusted input.
    • Route it through the same human-review lane already kept for irreversible or ambiguous compensation.

7. References

  • The source checked these on 27 September 2026. The notes record what each supports here; the casebook doesn't re-verify current prices or draft status.
Reference What it supports
IETF draft-ietf-httpapi-idempotency-key-header-07 400 for a missing key, 409 while the first request is in flight, 422 for a reused key with a different payload
Datatracker: Idempotency-Key header draft status An expired Internet-Draft, not an RFC
Stripe API: Idempotent requests Provider-side keys; keys can be pruned after 24 hours, so a much later retry can't rely on the provider alone and needs the stored ActivityReceipt, or, if the crash came before the receipt, a lookup at the provider by a business reference such as the order ID stored with the charge. The first response is saved once execution begins, including errors; a concurrent same-key request is refused without saving a result.
AWS Architecture Blog: Exponential Backoff and Jitter Capped exponential backoff with jitter
AWS Price List API: Amazon S3, us-east-1 S3 Standard at $0.023 per GB-month
Amazon EBS pricing gp3 at $0.08 per GB-month in US East
PCI SSC: PCI DSS Tokenization Guidelines Tokenisation can reduce PCI DSS scope; tokens that can start a transaction may stay in scope
GDPR Article 5 (EUR-Lex) Data minimisation and storage limitation principles

Quick Recall: Lines to Say in the Interview

  • "The orchestrator records the payment; it is never the financial ledger."
  • "409 while a same-key request is in flight, 422 for the same key with a different payload, and that's an expired draft I adopt as a convention."
  • "One key per side-effecting action. One key for the whole workflow would suppress the refund as a duplicate of the charge."
  • "A deliberate new payment attempt gets a new key, pay:o-123:2, written to history before the call."
  • "Attempted is not completed: intent before the call, done after the acknowledgement."
  • "A crash between intent and done is the hard case; only the provider's key or receipt lookup can say whether money moved."
  • "No backoff setting helps a charge that already landed."
  • "Buy the commodity execution layer; build the business state machine and policy layer."

Quick review

One sentence: a durable orchestrator owns progress in append-only history, every side effect runs under its own idempotency key with a stored receipt, waits are timers and signals, failures follow a named policy with explicit compensation, and one workflow ships only after replay and crash recovery prove nobody is ever charged twice.

30-Second Cheat Sheet

  • The goal: each business effect exactly once, state visible, failed steps compensated.
  • Payment is the riskiest step: it can't be reversed, so whatever degrades, block a second payment.
  • Control plane decides, data plane acts. Only the durable history store owns progress.
  • One key per side effect: pay:, crm:, mail:, refund:.
  • Retry ≠ compensation. Backoff spaces attempts; only a refund reverses a charge that landed.
  • The numbers: ~1,157 activities/s average, ~400 GB raw history, ~11.6k/s at 10x.
  • Gate order: one workflow → replay and crash recovery → operator visibility → migrate by version behind a canary.

1. Recall the Guarantees and Who Owns What

The goal and the riskiest step

  • Goal: apply each business effect of a long-running process exactly once, keep its state visible, and compensate when a step fails.
  • Payment is the riskiest step because it can't be reversed. Whatever else degrades, the design must still block a second payment.

Who owns what

Part Role
Control plane (registry, scheduler, timers, signal gateway, compensation engine, operations UI) Decides
Data plane (queues and workers) Acts, so decisions scale apart from side effects
Durable history store The only owner of progress
Queues Deliver
Workers Suggest effects
Scheduler Rebuilds its view from history each time

Soundbite: "When the worker dies after payment succeeds, history and the completion receipt decide whether to redeliver or compensate; worker memory never does."

Keys, retries and waits

  • Each side-effecting action has its own key: pay:, crm:, mail:, refund:.
  • Retry and compensation stay separate:
    • Capped exponential backoff with jitter spaces out attempts.
    • Only an explicit step such as a refund reverses a charge that landed.
  • The seven-day approval is a durable timer state: reminded, escalated or expired by policy, never a sleep loop.

Failure policy and isolation

Policy Applies to
Fail closed Approval completion, payment authorisation, repairs
Degrade Email
Queue CRM sync
  • Partition retry and dead-letter lanes by tenant and dependency, so a stuck CRM connector can't block other tenants.
  • Pin each running instance to its starting definition version; ship changes as new versions.
  • Prefer an orchestrated saga over choreography: with choreography, nobody can point to where a run stands.

2. Recall the Numbers and the Gates

Item Value
Scenario 10 million active workflows, 100 million activities a day
Average rate About 1,157 activities a second
Peaks Plan at 3x to 10x
Headroom At least double the observed peak
History (base) 40 events of 1 KB × 10 million ≈ 400 GB raw
History (bigger events) 2 KB events ≈ 800 GB
Payloads Documents in object storage behind payload_ref
At 10x 1 billion activities a day, about 11.6k a second
  • At 10x, expect to break first: replay latency, queue hot spots, storage fan-out or cost, before application-server CPU.

Two caveats to say

  • The 409/422 idempotency split comes from an expired IETF draft: a convention, not a standard.
  • Stripe can prune keys after 24 hours, so a much later retry needs the stored receipt.

The gate order

model one workflow → prove replay determinism and crash recovery → add operator visibility → migrate by version behind a canary

Watch six numbers

# Number
1 Completion time
2 Retries
3 Stuck age
4 Duplicated effects
5 Compensations
6 Manual repairs

3. Close in One Sentence

Spoken answer (source's close): "A durable orchestrator owns progress in append-only history, every side effect runs under its own idempotency key with a stored receipt, waits are timers and signals, failures follow a named policy with explicit compensation, and I ship one workflow only after replay and crash recovery prove nobody is ever charged twice."


Flashcard Drill


Quick Recall: Lines to Say in the Interview

  • "Exactly once, visible state, explicit compensation."
  • "Payment can't be reversed, so whatever degrades, a second payment stays blocked."
  • "Only the history store owns progress; queues deliver and workers suggest."
  • "One key per side effect: pay, crm, mail, refund."
  • "Backoff spaces attempts; only a refund reverses a charge."
  • "About 1,157 a second on average, 400 GB of raw history, 11.6k a second at 10x."
  • "Fail closed on approval, payment and repairs; email degrades, CRM queues."
  • "One workflow, then replay and crash recovery, then visibility, then versioned migration behind a canary."

Where next

Practise this as a worksheet
Reliable Workflow Orchestration System