All posts Engineering, 14 min read

Durable execution vs idempotent re-derivation for AI workflows

AI workflows fail partway through at real volume. Durable execution resumes from a checkpoint; idempotent steps re-derive. How each works and when to pick each.

If "durable workflow" is new to you, durable here means the end state survives a crash. Stop the process at any point, start it again, and you end up where you'd have been if nothing had failed.

Durable execution is one way to get there: an engine saves a checkpoint after each step and resumes from it after a crash.

Getting there is hard because once work spans 2 systems, such as your database and a payment API, or your queue and your worker, there's no instant where both are guaranteed consistent, and a crash can land in the gap between them.

Double-entry bookkeeping exists for the same reason. A transfer is 2 events, money leaving 1 account and arriving in another, and the books are kept so they never show 1 event without the other. A durable workflow applies that rule to code that can die mid-step.

Failure is the normal case

A sync pulled records from a customer's CRM, enriched each one through a provider, and ran an agent pass over the result. It worked in the demo and for 2 weeks. Then on a Tuesday the enrichment provider returned a 503 halfway through a batch of 4,000 records, the process retried the whole batch, and the customer woke up to duplicate work and a sync that reported "complete" after finishing a third of the job.

Once a workflow has more than 1 step, calls an external API, and runs long enough to be interrupted, it's a distributed system. These are the usual failures:

  • The model call times out.
  • The provider rate-limits you.
  • The CRM returns a page and fails on the next.
  • A deploy kills your process in the middle of step 4 of 7.

At real volume these happen every day.

Start with the simplest version: 1 process, 1 loop, no crashes. That works. Then add 1 thing at a time:

  1. Add a retry, and it can repeat work.
  2. Add a second worker, and 2 of them can grab the same record.
  3. Add an external API, and a crash can land between paying for a call and recording its result.

Each of those gets a section below.

A durable workflow makes "something failed partway through" end in the same state as "nothing failed." There are 2 ways to get there. I've built both and run them in parallel, and which one fits depends on a few constraints I cover at the end.

2 approaches: durable execution and re-derivation

  • Resume. Record progress as you go, and on a crash, pick up where you left off. This is what a durable-execution engine gives you. Temporal is a well-known example. The engine checkpoints each step, persists workflow state, and replays from the last durable point. You write linear code, and the engine keeps it going through crashes. The cost is that you now operate a stateful orchestration system, and its execution model shapes your logic.
  • Re-derive. Make every unit of work idempotent and re-runnable from its inputs, so a crash means you run it again and get the same result. There's no saved position to resume from, because position doesn't matter. The work is a pure function of its inputs plus what's already in your database. The cost is that you have to make that true for every step, including the ones that touch the outside world.
flowchart LR
  C[Crash mid-run] --> A{Strategy}
  A -->|Resume| R[Read last checkpoint]
  R --> R2[Continue from step N]
  A -->|Re-derive| D[Discard partial state]
  D --> D2[Run again from inputs]
  R2 --> S[Same end state]
  D2 --> S

After a crash, resume skips the finished steps because it kept a record of them, while re-derive runs them again, which is safe because every step is idempotent.

ResumeRe-derive
What it keepsA checkpoint after each stepNo saved position
After a crashContinue from the last checkpointRun the work again from its inputs
What you operateA stateful orchestration engine, such as TemporalPostgres and a queue
What it costsThe engine's execution model shapes your logicEvery step must be idempotent, including the ones that touch the outside world

We run our high-volume data pipelines on re-derive, on Postgres and a queue, with no durable-execution engine. Parts of our agent fleet run on the same idea.

The pieces below are what make re-derivation safe. They are also the baseline to weigh an engine against.

Idempotent steps

Re-derivation rests on a single property: running a unit of work twice has the same effect as running it once. Get it wrong and every retry can create duplicate or inconsistent data.

  • Deterministic key. Every piece of work gets an identity computed from its inputs. When it ran and which worker picked it up don't come into it. For a record-enrichment job, that's a pair like (jobId, recordId). The same record in the same job always produces the same key.
  • Upsert on the key. A second attempt overwrites the first attempt's row instead of inserting a duplicate. In Postgres, INSERT ... ON CONFLICT (key) DO UPDATE. The database makes sure the work lands once.
  • Guard external side effects. A step that calls a paid provider must not pay twice on retry. Record an idempotency key for the outbound call and check for a completed result before re-issuing. Many APIs accept an idempotency key directly. Where they don't, record "about to call for key X" before and "result for key X is Y" after, so a retry sees the marker and doesn't fire again.

What I underestimated was that idempotency has to hold across the whole path from "work selected" to "result committed," including the network call in the middle and the commit at the end. A single idempotent function inside that path isn't enough.

We had a step that was idempotent in its database write but issued its external call before the write committed. A crash in that gap meant the call happened and the record never showed it. We had to make the side effect re-derivable from a committed marker.

The failures I've hit sat at boundaries: between our write and someone else's API, and between a batch and the database. I wrote up the ingestion side, including a batch that hit the Postgres cap of 32,767 bind parameters in one statement, in idempotent ingestion.

The transactional outbox

A request comes in, you write a row to Postgres saying "work accepted," then you publish a message to your queue. That's 2 writes to 2 systems:

  • Process dies between them: you have accepted work no one will do.
  • Publish first and the DB write fails: you have a queued task with no backing record.

Whichever order you pick, a crash can land in the gap between the 2 writes.

The transactional outbox turns the 2 writes into 1. You write the business row and an outbox row in the same database transaction. Either both commit or neither does.

A separate poller reads unprocessed outbox rows, publishes them, and marks them done. If it crashes after publishing but before marking, the row publishes again, which is fine because the consumer is idempotent.1 The only atomic step the system relies on is a single-transaction commit, and Postgres already guarantees that.

Top: 2 writes to 2 systems, with a crash between them. Bottom: the outbox turns them into a single Postgres commit, and the poller can safely publish the same row twice.

The poller also has a concurrency problem. If 3 workers poll at once, they can't grab the same rows. Lease-based polling with SELECT ... FOR UPDATE SKIP LOCKED handles that.

SELECT * FROM outbox
WHERE status = 'pending' AND available_at <= now()
ORDER BY available_at
LIMIT 100
FOR UPDATE SKIP LOCKED;

FOR UPDATE locks the selected rows. SKIP LOCKED tells every other poller to step over locked rows instead of blocking. Each worker gets a disjoint batch, and you have a work queue inside Postgres without a separate broker.

Add a lease, an expiry, and a visibility timeout, and the same table recovers from a worker dying mid-task: the lease expires, the row becomes visible, another worker picks it up. That second pickup is safe because the work is idempotent.

Checkpoints and watermarks

Pulling from a CRM is rarely one-shot. You sync incrementally: ask for everything changed since last time, process it, and remember where you stopped.

The place you stopped is a watermark, usually a timestamp or a monotonic cursor. That's how you avoid re-pulling 1 million records every hour.

A partial failure can lose data at the watermark, with no error, like this:

  1. Pull a page of records modified after T.
  2. Advance the watermark to the newest timestamp you saw, before confirming every record committed.
  3. Process some of the records, then die.

The unprocessed records now sit in a gap no future run will ask for. The data looks consistent, but rows are missing.

  • Advance only after commit. The watermark advances only after every record up to it is durably committed. On partial failure it stays put, and the next run re-pulls the window. Idempotent upserts make re-pulling the committed records harmless. Only the missing ones change.
  • Break timestamp ties. Many records can share a modified-at value. A naive "greater than the watermark" query skips boundary records or reprocesses them forever. Use a (timestamp, id) cursor so resumption is exact even when 100 records share a second.
Parallel workers commit out of order, so "the newest record I saw" and "everything before this point is done" are different positions. The watermark has to mean the second one.

A watermark means every record before it is committed. Records after it may or may not be.

Work that can't be retried: dead-letter queues and salvage

Some work can't be retried into success:

  • a malformed field that crashes the parser;
  • model output that fails validation every time;
  • an API rejecting a specific id with a permanent error.

If your retry logic treats these like transient failures, you get a poison message: work that fails, retries, and either spins forever or blocks the workers behind it.

flowchart TD
  F[Work fails] --> R[Retry with backoff]
  R --> B{Attempts left?}
  B -->|Yes| R
  B -->|No| Q[Quarantine / DLQ]
  Q --> AL[Alert human]
  AL --> FIX[Fix cause]
  FIX --> RP[Replay through pipeline]
  • Bound the retries. Stop after a fixed number of attempts and move the work somewhere safe.
  • Quarantine poison work. Park poison rows in a dead-letter table holding the original work, the error, the attempt count, and a timestamp. The pipeline moves on, and the work waits with enough context to understand and replay it.
  • Alert on depth. Every row increments a metric that feeds an alert, and when depth crosses a threshold, a human finds out.
  • Replay after the fix. What lands there is usually fixable: a parser handling a new shape, an input that needs sanitizing.

Replay the rows back through the pipeline. Because the pipeline is idempotent, replaying the ones that would have succeeded anyway costs nothing.

Backoff, rate limits, and a fleet-wide stop

External APIs rate-limit you. The standard signal is a 429 with a Retry-After header.

  • Per-request: back off with jitter. Wait a bit, then 2x as long, then 4x, with randomness added so 1,000 retrying workers don't all retry at the same instant.
  • Per-account: stop the fleet. The quotas that cause trouble are per account: 1 API key, 1 quota, shared across every worker. Per-worker backoff doesn't help there. 100 workers each backing off still send 100 streams of calls at the same quota, burn it on rejected calls, and push recovery further out.

So when we hit a shared limit, we stop the whole fleet. The worker that gets the hard signal trips a fleet-wide circuit: a flag in Postgres or the cache that every worker checks before an outbound call to that provider.

Backing off per worker leaves every other worker still spending the shared quota. A single flag, checked before each outbound call, pauses the whole fleet and resumes it together.

Until the flag clears, no worker calls that provider. We back off once, for the whole fleet, then resume together.

Durable multi-agent orchestration

Agent work has the same problem, plus 1 more way to fail: the model can confidently do the wrong thing. A multi-step agent task is a long-running workflow whose steps are non-deterministic. Durability here means a failed or wrong run leaves nothing behind to clean up, so re-running is always safe.

  • Wire roles at deploy time. The set of agents, what each can touch, and how they hand off is fixed configuration, set before the run starts. The same task with the same inputs runs through the same wiring every time.
  • Isolate each task. For agents that modify code, a throwaway git worktree per task (this is how Alfred runs its coding agents): a clean checkout that lives for the run and is discarded after. 1 agent's work can't overwrite another's, and after a crash you discard the worktree and start over from the input.
  • Gate with plan, review, execute. The agent that proposes a change isn't the agent that approves it. A separate read-only pass reviews the plan before any write. That catches the confident-but-wrong failure that retries can't, because a retry of a bad plan produces the same bad plan. Keeping the proposer and the reviewer apart is the same rule as not letting a single process both decide the work and commit it.

Human approval as a workflow step

Some steps are a person deciding something:

  • A sync wants to delete records that no longer match, and a human approves.
  • An agent drafts an outbound action, and someone signs off.

The naive build has the workflow block and wait for the human. Then the process hangs while the approver is away, and a dropped message loses the decision.

We model human approval as a workflow state, with the same durability rules as any other step.

stateDiagram-v2
  [*] --> Pending: work needs human decision
  Pending --> Approved: human approves
  Pending --> Rejected: human rejects
  Pending --> TimedOut: window elapses
  Pending --> TransportFailed: notice or reply lost
  TimedOut --> SafeDefault: resolve to do-not-proceed
  TransportFailed --> SafeDefault: recorded verdict
  Approved --> [*]
  Rejected --> [*]
  SafeDefault --> [*]
  • Park durably. The work sits in a pending-approval state, and the workflow is free to do other things.
  • Time out to a safe default. If no decision arrives within the window, the step resolves to a defined outcome, usually "do not proceed."
  • Define transport failure. When the notification never reaches the human or their response never gets back, that resolves to an explicit verdict too, recorded durably.

A person can answer in a minute, days later, or never, so human steps need explicit timeout logic.

Choosing between them

Both approaches work, and I run both. Which one fits a given workflow comes down to these constraints.

Reach for a durable-execution engine when:

  • A single logical workflow spans hours or days and fans out into many dependent steps.
  • Each step accumulates state that is expensive or impossible to recompute.
  • The process is approval-heavy with long waits and complex branching.
  • Re-running a step has a cost you can't make idempotent, like sending money, where you need to resume past the step rather than redo it.

Reach for stateless re-derivation when:

  • The unit of work is small and its inputs are cheap to fetch.
  • You can make each step idempotent, so it is safe to run again.
  • You operate with 1 or 2 people and a ceiling on infrastructure you run yourself. The durability lives in Postgres, which you already operate, with no orchestration engine to upgrade and reason about.
  • You need to scale a path horizontally, where a stateless idempotent worker is the cheapest thing to add.
flowchart TD
  W[New workflow] --> Q1{"Long-lived, branchy,<br/>expensive state to recompute?"}
  Q1 -->|yes| Q2{"Steps you cannot<br/>make idempotent,<br/>like sending money?"}
  Q2 -->|yes| ENG["Durable-execution engine<br/>(resume)"]
  Q1 -->|no| Q3{"Small unit, cheap inputs,<br/>each step idempotent?"}
  Q3 -->|yes| RED["Stateless re-derivation<br/>on Postgres"]
  Q2 -->|no| RED
  Q3 -->|no| ENG

It comes down to 3 questions:

  • How long does a single workflow live, and how much irrecoverable state does it carry?
  • How expensive is it to recompute a step versus resume past it?
  • How many people are on call for it at 3am, and what's your ceiling on self-run infrastructure?

A durable-execution engine is a second distributed system you have to operate and upgrade. Re-derivation adds no new system, but every boundary has to stay idempotent, and only your tests check that.

We chose re-derivation for the small, re-runnable paths, and we'd choose an engine the day a workflow becomes long-lived, branchy, and full of state we cannot afford to recompute.

The Tuesday sync with these patterns in place

This is what each piece would have done to the Tuesday sync from the top of the post.

  • Deterministic key and upsert. The retried batch overwrites the third of the records that already landed instead of duplicating them.
  • Side-effect marker. Records whose enrichment call already succeeded aren't sent to the provider again, so the retry doesn't pay twice.
  • Watermark after commit. "Complete" can only be reported once every record up to the watermark is committed, so a third of a job never reads as done.
  • Bounded retries and quarantine. If a record keeps failing after the provider recovers, it lands in the dead-letter table with an alert instead of retrying the whole batch.

Key takeaways

  • A multi-step workflow that calls an external API and runs long enough to be interrupted is a distributed system. At real volume it fails partway through every day.
  • There are 2 strategies: resume from a checkpoint with a durable-execution engine, or re-derive from inputs with idempotent steps.
  • Re-derivation depends on idempotency: a deterministic key from the inputs, an upsert on that key, and a guard so a retry never repeats a paid side effect.
  • The transactional outbox removes the gap between writing a business row and queuing a message by making them a single database transaction, with a separate poller publishing the outbox row.
  • Advance a watermark only after every record up to it is committed, or in-flight records fall into a gap no future run re-pulls and vanish without an error.
  • Bound retries, quarantine poison work instead of dropping it, alert on queue depth, and replay after the fix. Idempotency makes replay safe.
  • For shared rate limits, stop the whole fleet with a single flag every worker checks before calling the provider.
  • Pick by constraints: an engine for long-lived, branchy work with state you can't recompute, and re-derivation on the Postgres you already run for small, cheap-to-refetch, idempotent work.

Footnotes

  1. Re-publishing on that crash is only safe if the consumer is idempotent in practice. Test it: publish the same outbox row twice manually and confirm the downstream state is identical to publishing it once. If it isn't, the outbox has moved the duplicate-delivery problem downstream. ↩

Common questions

When should I use a durable-execution engine like `Temporal` instead of idempotent re-derivation?↓

Use an engine when a single workflow runs for hours or days, fans out into many dependent steps, carries state that is expensive to recompute, or includes steps you cannot make idempotent, such as sending money. Use idempotent re-derivation when the unit of work is small, its inputs are cheap to fetch, and you want durability to live in the Postgres you already run.

What does idempotency mean in a workflow?↓

Running a unit of work twice has the same effect as running it once. You give each piece of work a deterministic key from its inputs, upsert on that key, and guard external side effects so a retry never repeats a paid call.

What problem does the transactional outbox solve?↓

It removes the gap between writing a business row and publishing a message to a queue. You write both in a single database transaction, then a separate poller publishes the outbox row. A crash can no longer leave you with accepted work that was never queued, or a queued task with no record behind it.

What makes a workflow durable, and why is it hard?↓

Durable means the end state survives a crash: stop the process at any point, start it again, and you arrive where you would have if nothing failed. It is hard because once work spans 2 systems, a database and a payment API, or a queue and a worker, there is no instant where both are guaranteed consistent, and a crash can land in the gap. Double-entry bookkeeping solves the same problem: a transfer is 2 events, and the books must never show 1 without the other.

Why advance a watermark only after commit?↓

If you advance the watermark before every record up to it is committed, the records still in flight fall into a gap that no future run re-pulls, and they are lost with no error. Advancing only after commit means a partial failure re-pulls the window, which is safe when your upserts are idempotent.

What is durable execution?↓

Durable execution is a way to run a multi-step workflow so it survives a crash: an engine saves a checkpoint after each step, and after a failure it resumes from the last checkpoint. The other way is to make every step idempotent and run it again from the start, landing in the same state.

Keep reading

All posts Get in touch