Ch.60: Workflow Engine System Design: Recover After a Crash
Outline
- 0:00 Recovering after a worker disappears
- 0:44 The workflow engine architecture
- 1:22 Accepted is not finished
- 2:07 Millions of waiting jobs
- 3:01 Workflow, run and asset identities
- 4:05 Commit progress and deliver work
- 4:37 Replay versus retry
- 6:22 Compatible decisions during replay
- 6:59 Success with a lost response
- 7:58 Timers and asynchronous approvals
- 8:50 Cancellation after publication
- 9:41 Ordered updates and independent runs
- 10:38 History size and state handoff
- 11:51 Code compatibility for old runs
- 13:07 Crash tests and progress signals
- 14:11 Follow the job across the map
- 14:48 What recovery can guarantee
Transcript
0:00 A workflow engine keeps a multi-step process moving even when its workers disappear. Let's design what it must save, how a replacement rebuilds the next decision and where an outside action can still leave us uncertain. So recovery means knowing what's safe to do next, not bringing the dead worker back. Exactly. Give our engine one job: a creator uploads a video, we inspect and convert it, wait for approval and publish the approved version. If a worker crashes, we can't lose progress or publish the wrong video.
0:32 Including the awkward case where the publishing service succeeded, but our worker disappeared before reporting success. Yes. Recovering our progress doesn't automatically tell us what happened in somebody else's service. Let's put that recovery path on the complete architecture map. The app enters through an authorized gateway. A coordinator records progress and future work. Workers make decisions or perform outside actions; stored timers and incoming approvals wake waiting jobs. The record stays while workers come and go.
1:01 We'll return to this same map once we can follow a crashed job through it. Temporal's public documentation explains recovery through recorded history. We'll borrow that model, but design our own illustrative database and delivery path. The source links are in the description. Our map has to satisfy the app's requirements, not just connect a plausible set of boxes. With that map in view, define our app's functional requirements. A request creates a job and returns its identity. Let the app inspect progress and accept later approval or cancellation requests.
1:33 Approval needs to name the video's version. Otherwise a creator could approve yesterday's upload and accidentally authorize today's replacement. Agreed. The engine also invokes the external inspection, conversion and publishing steps, persists waits and recovers work when a worker fails. When the app gets a successful response to “approve,” can it tell the creator that the video is public? No. Acknowledge approval after recording it durably; publication still needs work. The status endpoint must report committed progress, not turn that accepted input into a public-video success banner.
2:07 Now give those API promises non-functional requirements. Accepted progress must survive the failures our database is configured to tolerate. Keep unrelated jobs independent and isolate tenants, the customers sharing our engine. For a capacity exercise, suppose we start 100 jobs a second and they last a day on average. That's 8,640,000 open jobs at steady state. Mostly waiting, potentially. We haven't established how many are runnable, or how expensive their next steps are. That total doesn't size a worker fleet.
2:39 Oh, right. Giving every open job a sleeping thread would make us pay for the wait itself. I'd store the wait instead. Yeah, a stored wait costs space without occupying a worker. We also need to reject or delay work we can't safely accept, and tell callers when we're overloaded. Recovery speed depends on incoming events, history size and available workers. So identify the waiting job. The tenant is the customer that owns it. Within that customer, a workflow identifier names this video's processing job; a run identifier names one execution of that process.
3:14 So restarting the creator's whole process can get a different run identifier, without confusing its approval with the earlier execution. Yes. Keep the start request's identity when retrying it, so our chosen contract can return the existing run instead of starting another. And those identities need an access check. The gateway gets the tenant from authenticated credentials, not a tenant field the caller invented. It checks access to this run and the chosen asset version. Then keep ordered history events, the current state and a record revision.
3:45 That revision changes when the engine commits progress; it isn't the creator's video version. History says what happened; current state makes common status reads cheaper. And the video stays in object storage. History holds the authorized asset reference and necessary results, not the whole video repeated in every recovery read. Now, for example, record that conversion should begin. Our coordinator saves the history and status update with work for a relay in one transaction. Its outbox entry is a durable request to deliver to the task queue.
4:17 I think the important boundary is what that commit says: conversion requested, not video converted. The relay can recover the request, but it hasn't produced the output. Right. Delivery can repeat, so tasks keep stable identities. Our transaction preserves the engine's request; it doesn't finish a converter or publisher's outside action. With delivery working, separate two worker jobs. A decision worker runs the workflow's control code; an Activity worker performs outside work, such as converting the video.
4:47 That's the part that talks to another service. What does a replacement decision worker receive after a crash? Let's say our video's history records inspection completed and conversion requested, but no output yet. The replacement runs the decision code from the beginning against that history. Hold on. Wouldn't we repeat the inspection? No. When the code reaches that completed Activity, replay supplies its saved result. The conversion request is already recorded too, but that doesn't prove the outside work finished.
5:16 If the converter died halfway through the file, does the replacement continue at that byte? Not through workflow replay. After the Activity attempt times out, our simple converter can be retried with the saved input and starts that work again. Resuming partway would need the converter's own durable checkpoints: saved partial progress. So rebuilding decisions and retrying unfinished outside work are different jobs. The engine doesn't recover an unreported half-file from the vanished worker's memory. Exactly. Once conversion completes and its output is recorded, later replay can use that saved result as well.
5:51 Our job then reaches the approval wait. And a replacement can reach that same wait without making the already completed calls again. Yes. Think of following a recipe with completed steps checked off and their results saved. Rereading “bake” doesn't put the cake back in the oven. But the checkmarks have to correspond to the same recipe. Otherwise the next instruction could change underneath them. And replay must distinguish a completed step from one merely requested. A missing result cannot be filled in with a hopeful guess.
6:22 But our recipe comparison needs a replay constraint: the code must follow a compatible path. For example, use the approval's earlier inputs and time, so today's clock doesn't make yesterday's on-time response late. And an inspection API response belongs in recorded Activity output. Otherwise rebuilding control flow could ask a changed outside world a different question. Yes. Genuinely new input can change our next decision. Recovery must first rebuild what the old record already decided. Cadence documents the same separation.
6:53 Predictable workflow code makes replay possible; the Activity boundary lets the useful, unpredictable outside work happen separately. Now take a concrete case: the publishing service exposes the video, but its response is lost before completion reaches our engine. History still shows publication pending. If a retry calls the publishing service again, replay can't protect us using a completion that was never recorded. Correct. Temporal's Activity documentation warns about this unreported-completion boundary. I think this is where “durable execution” can sound like a stronger promise than we've actually built. Couldn't the replacement just ask the publisher what happened to our request?
7:30 For this example, it can. Before the call, we save one operation identity for the approved asset version. The publisher's contract makes repeated requests one logical publication and returns that operation's durable outcome. Then the engine records the publisher's evidence. What does our status endpoint show if a real publisher has no reliable answer? Publication unresolved, not completed. Durable engine state alone cannot prove that outside action succeeded. Our chosen publisher contract is doing work replay cannot do.
7:58 But publication is only one step; our job spends most of its life waiting for approval. Save that waiting state and return the decision worker to the pool. And if approval has a deadline? Store a durable timer. When it's due, timer processing records the wakeup and schedules another decision task. An outage may make it late; durability doesn't guarantee exact wall-clock execution. Approval arrives as an asynchronous message, often called a signal. Record which asset version was approved and keep the request identity, then schedule the run to process it.
8:33 Almost like leaving a ticket in a queue rather than asking the worker to sit beside the counter until the customer returns. Yes. No resident worker during the wait. And the app can know its message was accepted without claiming the workflow handler has already acted on it. And approval isn't our only incoming message. Suppose the creator cancels while another request approves the video. Which one wins? Our coordinator orders accepted inputs at the run's commit boundary. The application policy then decides whether this state may schedule publication or must stop. That handles a decision not yet executed.
9:09 But cancellation can arrive after the publishing worker has already exposed the asset. Then stopping the workflow doesn't remove the video. Cancel is cooperative: work has to observe the request and respond. Even terminating execution cannot reverse an outside effect. I wouldn't describe a successful cancel request as “nothing happened.” For this app, removal would need its own authorized operation and observable outcome. Agreed. Cancellation stops what it can under the chosen policy; it doesn't turn the history record into an undo button.
9:40 With approval and cancellation ordered, the next storage question is how a worker returns commands against history that's already changed. Which engine writes must agree? Compare its expected revision with the stored value. Accept matching results by appending events, advancing the revision and saving the next-work intention together; reject stale proposals. So approved progress and its associated work commit together. A stale proposal can't add a conflicting continuation of that history. And completion reports carry task identity too.
10:09 Repeating a report for an already completed task shouldn't advance the run again. Partition runs so unrelated jobs can progress independently. Keep decision and Activity capacity separate, and bound each tenant's admitted work and retries. A slow publisher shouldn't occupy every decision worker. We can spread independent runs across machines. One run still has ordered decisions, so a single exceptionally busy run needs its own limits rather than a promise of unlimited parallelism. Now consider what replay costs.
10:40 Cache warm execution state when useful. Temporal calls the preference for returning work to that cached worker sticky execution. If that worker disappears, we lose the saved reconstruction effort, not the durable history. Recovery can't depend on finding its old memory. Exactly. And many completed steps or review cycles can make replay expensive. A quiet day waiting isn't what grows the event history; recorded activity does. Then what would we carry into a fresh history for our waiting video job?
11:09 Starting with nothing would forget which asset is awaiting approval. For our example, choose a handoff point with no outside action in flight. Carry the asset's storage reference, its version, the approval state and the existing approval deadline into the new execution. And coordinate that switch with incoming approvals. An accepted input must land on one side or be carried across, not disappear between the two runs. Right. Our coordinator writes the old-run closure and new starting state in one transaction, ordered against those inputs.
11:41 Temporal's continue-as-new is the reference idea: same workflow identity, new run and history, with relevant state passed forward. A warm cache never authorizes erasing durable evidence. But preserving history isn't enough: a replacement also needs compatible code. Suppose our old workflow requested conversion before approval, but a deployment reverses that order. Existing history may contain commands the new code wouldn't have produced. Replay can detect that mismatch instead of safely continuing the old process.
12:08 Then the quiet approval wait is part of the deployment problem. When can we turn the old workers off? First keep existing runs on compatible code. Pinning means routing a run to its chosen worker version, not upgrading it just because a new binary exists. Finish or deliberately migrate the runs that still need the old version before retiring it. Could the fresh-history handoff move us onto newer code automatically? Not necessarily. In Temporal, a pinned version can carry across that new run. Starting fresh history and choosing a new code version are separate decisions.
12:43 So an empty task queue isn't enough. A waiting run could wake tomorrow and need that code. We'd also check any retained-history operations our service promises. Yes. An automatic-upgrade approach still needs code that can replay the histories it receives. Test old histories against proposed code, and expose jobs stranded without suitable workers. New jobs starting successfully doesn't prove the rollout is safe. Let's test that recovery promise at its boundaries. Crash the coordinator after its transaction commits but before relay delivery.
13:13 The saved intention must still produce work. Deliver the same task twice and repeat its completion report. Then kill a conversion worker before completion and lose the external publisher's response after success. Those are different tests. The first group checks engine progress; the lost-response test also checks whether external deduplication actually works. Send duplicate approval, an approval for an old asset version and approval racing cancellation. Verify each outcome against the policy, not just a worker log.
13:43 Also make the compatible worker version unavailable. The engine should expose pending work, not pretend the job completed or send it to incompatible code. We need measurements for the oldest runnable work, pending Activity attempts and replay failures. Millions of open jobs could be healthy; a small queue that never moves isn't. And test those signals during the crashes. An empty exception dashboard wouldn't prove that our creator's video ever progressed. Let's return to the original map. Our gateway authorizes the creator's input.
14:15 The coordinator commits progress and work intent together; the relay delivers tasks even after a crash. Decision workers rebuild from history, Activity workers contact outside services, and durable timers or approvals wake the waiting run. When publication's response vanishes, the publisher's operation identity lets us recover its outcome. Our history alone couldn't settle that uncertainty. And replacing a worker doesn't erase approved progress. We can reconstruct the next decision without keeping that worker alive all day.
14:43 That's what each region of the map contributes to this particular video's recovery. So a long process can survive short-lived workers when its record, delivery path and compatible decision code agree about what happens next. And publication can remain uncertain even when our own record is durable. Recover recorded progress, keep the operation identity fixed and make unresolved outcomes visible. Thanks for listening to Learning Podcasts.