Shipping reliable AI apps, part 9 of 11
Durable execution for AI agents: resume at step 9, not step 1
A crashed agent run shouldn't start over and pay for every step again. Save each step's result in TypeScript, then resume at step 9.
After this video
You can make a multi-step agent run resume after a crash or deploy, without paying twice or sending anything twice
The short version
A deploy or crash in the middle of a 10-step agent run makes plain code start over, paying for every finished model call again and repeating side effects like emails. Durable execution saves each step's result as it finishes, so a restarted run skips what's done and resumes at the failed step. The episode builds a small TypeScript step helper on a Postgres table, then covers the crash window (idempotency keys), replay rules (deterministic code between steps, stable step names), per-step retries with caps, two workers racing on one run, and when a platform like Temporal, Inngest or Cloudflare Workflows earns its keep.
Durable execution
Each completed step's result is saved. After a crash, the run replays its code, gets finished steps back from storage instead of running them, and continues at the step that didn't finish.
Step 9 of 10. At about 30 cents a step, restarting a run killed at step 9 wastes $2.40 on the 8 steps already paid for; resuming wastes nothing, only step 9 runs again.
A step helper
One table keyed by run id and step name, and one function: look up the step, return the saved result if there is one, otherwise run it, save it and return it.
The crash window
A step can do its side effect and crash before the result is saved, so it runs again. Steps don't make outside actions exactly once; an idempotency key built from run id and step name lets the provider spot the repeat.
One email, not two. Resend checks whether an email with the same idempotency key went out in the last 24 hours.
Replay rules
Code outside steps runs again on every resume, so it must take the same path: time, random numbers and model calls go inside steps, and step names stay stable across deploys.
The 5 pm branch. A check on Date.now() reads 4:59 on the first run and 5:01 on the resume, and the run takes a different path.
Retries per step
Retry only the failed step, with backoff, and cap the attempts on paid steps; errors that can't succeed on a retry stop the run. A parked run keeps its saved steps.
Defaults. Temporal: 1 s, doubling, capped at 100 s, unlimited attempts by default. Inngest: 4 retries after the first try.
Two workers, one run
Two workers resuming the same run can both run the next step. A unique constraint with ON CONFLICT DO NOTHING keeps one saved result, and an advisory lock gives the run to one worker at a time.
The code
async function step<T>(runId: string, name: string, fn: () => Promise<T>): Promise<T> {
const saved = await db.getStep(runId, name);
if (saved) return saved.result as T;
const result = await fn();
await db.saveStep(runId, name, result); // INSERT ... ON CONFLICT DO NOTHING
return result;
}const tickets = await step(runId, "fetch-tickets", () => fetchTickets(week));
const summary = await step(runId, "summarise", () => model.summarise(tickets));
const report = await step(runId, "draft", () => model.draft(summary));
await step(runId, "send-email", () =>
email.send(report, { idempotencyKey: `${runId}:send-email` }));CREATE TABLE steps (
run_id text NOT NULL,
step text NOT NULL,
result jsonb NOT NULL,
UNIQUE (run_id, step)
);Check yourself
A 10-step run dies at step 9. With a step helper, which steps run again on restart?
Only step 9: steps 1 to 8 return their saved results from the table.
Step 5 sends an email and the server dies before its result is saved. What stops a second email?
An idempotency key built from the run id and step name, so the provider recognises the retry and skips it.
Why must code between steps not read the clock directly?
It runs again on every resume; a different time can send the run down a different path than the saved steps, which breaks replay.
Sources
Every claim in this video was checked against these pages. Open one to see the claims it backs and the exact words they rest on.
docs.temporal.io/…/understanding-temporal
- Durable execution: when the process running the work crashes, another process rebuilds its state and resumes where it stopped, progress intact (Temporal's definition).
if the process running it crashes, the temporal service hands the work to another process, which rebuilds the state of the execution and resumes at the point where it stopped, with local variables and progress intact.
- Without durable execution, a crash loses the state of an in-flight process.
without that guarantee, a crash loses the state of an in-flight process.
- Resume works by replaying the code against a saved history of what already happened, then continuing from the point of failure.
a new worker fetches the event history, replays the workflow code against it to rebuild local state, and continues from the point of failure as if the failure never happened.
- A durable run can wait on a timer for minutes or months.
wait on a durable timer for minutes or months.
- Temporal is a platform that runs application code as a durable execution.
temporal runs your application code as a durable execution.
- Durable execution: when the process running the work crashes, another process rebuilds its state and resumes where it stopped, progress intact (Temporal's definition).
docs.temporal.io/workflows
- On replay, a finished step's saved result is reused, not recomputed: the step does not run again.
during replay, that result is reused, not recomputed.
- A direct call to Date.now() can return a different value on replay.
for example: a direct call to date.now() could return a different value on replay.
- On replay, a finished step's saved result is reused, not recomputed: the step does not run again.
inngest.com/…/inngest-steps
- Inngest saves the result of each completed step.
inngest saves the result of each completed step.
- A failing step can be retried on its own, without re-running steps that already succeeded.
retries: a failing step can be retried and recovered on its own, without re-running steps that already succeeded.
- Code outside steps can run again on a resumed run.
code outside steps can run again.
- A step does not make an external action exactly once.
a step does not make an external action exactly once.
- If a provider accepts a request but its response is lost, the step can retry the action (so the action can happen twice).
if a provider accepts a request but its response is lost, the step can retry the action.
- Step ids must stay stable across deployments so an in-flight run can find its saved results.
keep each logical step's id stable across deployments so an active run can find its saved result.
- Inngest's step.waitForEvent resumes a run when a matching event arrives (for example a human's approval), or handles the timeout.
step.waitforevent - resume when a matching event arrives, or handle the timeout.
- Step results must be JSON-serializable; return only the data later steps need.
step results must be json-serializable; return only the data later steps need.
- Inngest saves the result of each completed step.
docs.temporal.io/workflow-definition
- Non-deterministic work, including model (LLM/AI) calls, API calls and database queries, belongs in a step (Temporal: an activity), outside the replay path.
to handle non-deterministic operations like api calls, llm/ai invocations, database queries, and other external interactions, put them in activities.
- If replayed code takes a different path than the history recorded, the run fails with a non-determinism error.
if a generated command doesn't match what it needs to in the existing event history, then the workflow execution returns a non-deterministic error.
- Changing the code while runs are in flight can break replay; Temporal recommends versioning.
to alleviate non-deterministic issues that arise from code changes, we recommend using workflow versioning
- Non-deterministic work, including model (LLM/AI) calls, API calls and database queries, belongs in a step (Temporal: an activity), outside the replay path.
developers.cloudflare.com/…/rules-of-workflows
- Cloudflare Workflows can hibernate and lose all in-memory state, so state must not live outside a step.
do not rely on state outside of a step workflows may hibernate and lose all in-memory state.
- Because a step might be retried multiple times, steps should be idempotent.
because a step might be retried multiple times, your steps should (ideally) be idempotent.
- Cloudflare Workflows steps persist state so a workflow can continue from that step after a network or infrastructure failure.
steps may emit (optional) state that allows a workflow to persist and continue from that step, even if a workflow fails due to a network or infrastructure issue.
- Cloudflare Workflows can hibernate and lose all in-memory state, so state must not live outside a step.
docs.temporal.io/…/retry-policies
- Temporal's default retry policy: exponential backoff, coefficient 2.0, starting at 1 second, capped at 100 seconds.
the default retry policy uses exponential backoff with a 2.0 backoff coefficient, starting with a 1-second initial interval and capping at a maximum interval of 100 seconds.
- Temporal's default maximum attempts for a retry policy is unlimited.
maximum attempts = ∞
- Temporal lets you list non-retryable error types in a retry policy.
non-retryable errors
- Temporal's default retry policy: exponential backoff, coefficient 2.0, starting at 1 second, capped at 100 seconds.
inngest.com/…/retries
- Inngest's default is four retries after the first attempt, with backoff and jitter.
the default is four retries after the initial attempt.
- Inngest's default is four retries after the first attempt, with backoff and jitter.
docs.stripe.com/…/idempotent_requests
- An idempotency key is a unique key the server uses to recognise retries of the same request.
a client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request.
- An idempotency key is a unique key the server uses to recognise retries of the same request.
resend.com/…/idempotency-keys
- Resend checks whether an email with the same idempotency key was already sent in the last 24 hours.
when you send an email with an idempotency key, resend checks whether an email with the same idempotency key has already been sent in the last 24 hours.
- Resend checks whether an email with the same idempotency key was already sent in the last 24 hours.
kubernetes.io/…/pod-lifecycle
- Kubernetes gives a stopping pod a grace period that defaults to 30 seconds (then it is killed).
a pod is granted a term to terminate gracefully, which defaults to 30 seconds.
- Kubernetes gives a stopping pod a grace period that defaults to 30 seconds (then it is killed).
platform.openai.com/…/latency-optimization
- Generating tokens is almost always the highest-latency step when using a model; cutting 50% of output tokens may cut about 50% of latency.
generating tokens is almost always the highest latency step when using an llm: as a general heuristic, cutting 50% of your output tokens may cut ~50% of your latency
- Cutting 50% of the prompt may only improve latency by 1-5%.
cutting 50% of your prompt may only result in a 1-5% latency improvement
- Each request adds round-trip latency, which adds up.
each time you make a request, you incur some round-trip latency-this can start to add up.
- Steps that are not strictly sequential can be split into parallel calls.
you can split them out into parallel calls
- Streaming is the single most effective way to cut perceived waiting time, to a second or less.
the single most effective approach, as it cuts the waiting time to a second or less.
- Generating tokens is almost always the highest-latency step when using a model; cutting 50% of output tokens may cut about 50% of latency.
docs.anthropic.com/…/reduce-latency
- Time to first token (TTFT) is the time until the model generates the first token of the response.
time to first token (ttft): this metric measures the time it takes for the model to generate the first token of the response, from when the prompt was sent.
- max_tokens sets a hard limit on output length.
use the max_tokens parameter to set a hard limit on the maximum length of the generated response.
- Time to first token (TTFT) is the time until the model generates the first token of the response.
arxiv.org/…/2406.10279
- In a study of 16 code models and 576,000 code samples, on average at least 5.2% of packages from commercial models and 21.7% from open-source models were hallucinated (do not exist).
the average percentage of hallucinated packages is at least 5.2% for commercial models and 21.7% for open-source models
- The study generated 576,000 code samples with 16 popular code models.
using 16 popular llms for code generation and two unique prompt datasets, we generate 576,000 code samples
- In a study of 16 code models and 576,000 code samples, on average at least 5.2% of packages from commercial models and 21.7% from open-source models were hallucinated (do not exist).
arxiv.org/…/2406.10279v3
- An attacker can publish a real package under a hallucinated name, with malicious code in it.
an adversary can exploit package hallucinations, especially if they are repeated, by publishing a package to an open-source repository with the same name as the hallucinated or fictitious package and containing some malicious code/functionality.
- Hallucinated names repeat: 43% of hallucinated packages came back in all 10 repeats of the same prompt.
43% of hallucinated packages were repeated in all 10 queries
- Checking only that a name exists on the registry isn't enough: an attacker may already have published the hallucinated name.
trivial cross-referencing methods (i.e., comparing a generated package name with a list of known packages) are ineffective for detecting a package hallucination attack, as an adversary may already have published the hallucinated package with malicious code.
- An attacker can publish a real package under a hallucinated name, with malicious code in it.
docs.npmjs.com/…/npm-view
- npm view <package> shows a package's registry information.
as an example, to view information about the connect package from the registry, you would run: npm view connect
- npm view <package> shows a package's registry information.
docs.npmjs.com/…/package-lock-json
- A committed package-lock.json makes teammates, deployments and CI install exactly the same dependencies.
describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.
- A committed package-lock.json makes teammates, deployments and CI install exactly the same dependencies.
docs.anthropic.com/…/working-with-messages
- The Messages API is stateless: each request sends the full conversation history.
the messages api is stateless, which means that you always send the full conversational history to the api.
- The Messages API is stateless: each request sends the full conversation history.
docs.anthropic.com/…/rate-limits
- Anthropic spend limits set a maximum monthly cost an organization can spend on the API.
spend limits set a maximum monthly cost an organization can incur for api usage.
- You can set your own lower limits for individual workspaces.
you can also set user-configurable limits for your organization's workspaces.
- Anthropic spend limits set a maximum monthly cost an organization can spend on the API.
postgresql.org/…/ddl-constraints
- A Postgres unique constraint on a group of columns keeps their combination unique among all rows.
unique constraints ensure that the data contained in a column, or a group of columns, is unique among all the rows in the table.
- A Postgres unique constraint on a group of columns keeps their combination unique among all rows.
postgresql.org/…/sql-insert
- INSERT ... ON CONFLICT DO NOTHING skips the insert when it would break a unique constraint.
on conflict do nothing simply avoids inserting a row as its alternative action.
- INSERT ... ON CONFLICT DO NOTHING skips the insert when it would break a unique constraint.
postgresql.org/…/explicit-locking
- Postgres advisory locks are locks with an application-defined meaning.
postgresql provides a means for creating locks that have application-defined meanings.
- Postgres advisory locks are locks with an application-defined meaning.
postgresql.org/…/functions-admin
- pg_try_advisory_lock takes the lock immediately and returns true, or returns false without waiting if it can't.
this will either obtain the lock immediately and return true , or return false without waiting if the lock cannot be acquired immediately.
- pg_try_advisory_lock takes the lock immediately and returns true, or returns false without waiting if it can't.
Spotted a mistake? Say so in the video's comments. Fixes are listed on corrections.