Skip to content
Goal: Architecture-level✓ Sources verified 2026-11-24State MachinePipelineTask QueueIdempotency

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 ​

ConceptDescription
TaskOne complete unit of business processing, e.g. "review a contract"
StepOne stage of a task: parse → classify → extract → validate → risk_check → review → deliver
State machineDefines exactly which states a task can be in and which transitions are allowed; illegal transitions are rejected
Resume from checkpointAfter a step fails, re-run from that step rather than from the start
IdempotencyRunning the same step several times has the same result and side effects as running it once
Task queueMoves 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 human

The 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 + queueAn engine such as Temporal
Getting startedFast, few conceptsNeed to understand Workflow/Activity and the determinism constraints
Long waits (a human reviews days later)Implement suspend and wake-up yourselfNative support (Signals / timers)
Retries, timeouts, version upgradesImplement yourselfBuilt in
Good forFew steps, small team, early-stage projectsMany steps, long waits, high reliability requirements

Common pitfalls ​

  1. Steps with external side effects that aren't idempotent: retries push to the ERP twice or charge twice. See Retries and Idempotency.
  2. Tasks stuck in running forever after a worker crashes: add a "heartbeat / lease" and re-queue tasks that haven't updated within the timeout.
  3. Step outputs not persisted: you can neither resume nor trace.
  4. State transitions scattered everywhere: validate legal transitions in one central function.

Common interview questions ​

  1. How would you model state for an "ingest → parse → extract → validate → output" pipeline?
  2. How do you resume from the checkpoint after a step fails?
  3. If a worker process crashes, how do you make sure tasks aren't lost or stuck?
  4. Where is the line between a home-grown state machine and using Temporal?
  5. How do you show the progress of a long task to the frontend?

How it relates to my projects ​

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section