Task State Machines and Resuming from Checkpoints
A complete AI business pipeline covers ingestion, orchestration, output and traceability. The core of the orchestration layer: every step is retryable, failures can resume, and the whole run can be replayed.
Core concepts
| Concept | Description |
|---|---|
| Task | One complete unit of business processing, e.g. "review a contract" |
| Step | One stage of a task: parse → classify → extract → validate → risk_check → review → deliver |
| State machine | Defines exactly which states a task can be in and which transitions are allowed; illegal transitions are rejected |
| Resume from checkpoint | After a step fails, re-run from that step rather than from the start |
| Idempotency | Running the same step several times has the same result and side effects as running it once |
| Task queue | Moves tasks out of the web request into async workers (Celery, arq, Dramatiq, a Postgres queue, Temporal) |
How it works
Why long tasks can't run inside the request
Requests have timeouts (gateway, browser, load balancer), a deploy restart interrupts them, and you can't retry them or track progress. So: the endpoint only creates the task and returns a task_id, a worker executes it, and the frontend polls or subscribes to progress.
State model
queued → running → succeeded
│ ├─→ waiting_review → (human approves/edits) → running → …
│ └─→ failed_retryable → (automatic retry) → running
└─→ failed (retries exhausted / non-retryable error) → can be "re-run from the failed step" by a humanThe key to resuming: persist step results
After each step completes, write its output to task_step. On a re-run, skip the steps that already succeeded and read their outputs directly. This also satisfies the traceability requirement.
In practice: data model + executor skeleton
sql
CREATE TABLE task_step (
id bigserial PRIMARY KEY,
task_id bigint NOT NULL REFERENCES task(id),
name text NOT NULL, -- parse / extract / ...
status text NOT NULL, -- running / succeeded / failed / skipped
input jsonb,
output jsonb,
error text,
attempt int NOT NULL DEFAULT 1,
started_at timestamptz, finished_at timestamptz,
UNIQUE (task_id, name, attempt)
);python
PIPELINE = ["parse", "classify", "extract", "validate", "risk_check", "deliver"]
async def run_task(task_id: int):
ctx = await load_succeeded_outputs(task_id) # outputs of completed steps
for name in PIPELINE:
if name in ctx:
continue # resume: skip steps that already succeeded
step = await start_step(task_id, name)
try:
out = await STEPS[name](ctx) # every step must be idempotent
except NeedHumanReview as e:
await mark_waiting_review(task_id, name, reason=str(e))
return # suspend; run_task is called again after human handling
except RetryableError as e:
await fail_step(step, e, retryable=True)
raise # hand over to the queue's retry mechanism
except Exception as e:
await fail_step(step, e, retryable=False)
await mark_failed(task_id, name, e)
return
await finish_step(step, out)
ctx[name] = out
await mark_succeeded(task_id)Home-grown vs a workflow engine
| Home-grown state machine + queue | An engine such as Temporal | |
|---|---|---|
| Getting started | Fast, few concepts | Need to understand Workflow/Activity and the determinism constraints |
| Long waits (a human reviews days later) | Implement suspend and wake-up yourself | Native support (Signals / timers) |
| Retries, timeouts, version upgrades | Implement yourself | Built in |
| Good for | Few steps, small team, early-stage projects | Many steps, long waits, high reliability requirements |
Common pitfalls
- Steps with external side effects that aren't idempotent: retries push to the ERP twice or charge twice. See Retries and Idempotency.
- Tasks stuck in running forever after a worker crashes: add a "heartbeat / lease" and re-queue tasks that haven't updated within the timeout.
- Step outputs not persisted: you can neither resume nor trace.
- State transitions scattered everywhere: validate legal transitions in one central function.
Common interview questions
- How would you model state for an "ingest → parse → extract → validate → output" pipeline?
- How do you resume from the checkpoint after a step fails?
- If a worker process crashes, how do you make sure tasks aren't lost or stuck?
- Where is the line between a home-grown state machine and using Temporal?
- How do you show the progress of a long task to the frontend?
How it relates to my projects
- AI Document Review Pipeline W2: a home-grown state machine with resume from checkpoint; W5 migrates to Temporal for comparison.
Sources
- Temporal Docs: Workflows — the basis for comparing durable execution with a home-grown approach
- PostgreSQL Docs: SELECT FOR UPDATE SKIP LOCKED — claiming tasks via the database
- Celery Docs: Tasks (acks_late, retries, idempotency advice)
- Anthropic Engineering: Building effective agents (Prompt chaining) — inserting programmatic checks into chained flows
