Temporal for Durable LLM and Document Pipelines

A document job is long, and every step can fail. Parse a PDF, run OCR, split the text into chunks, call a language model on each section, validate the answer, write the rows. A model endpoint returns a 503 on the fourth section of a hundred. A worker is redeployed mid-run. A plain script restarts from zero and pays for every model call again.

Durable execution means the platform records progress so a crashed program resumes where it stopped. Temporal is an open-source platform built on that idea. In earlier work on a document-intelligence platform for construction, I introduced MLflow and Temporal, making AI evaluation reproducible and observable, and built LLM features including a PDF-to-Excel pipeline for pricing documents. This post is general technique, not a description of that system. The toy example runs without Docker or an API key.

Version notice. Written and run with temporalio 1.37.0 (the latest on PyPI on 1 December 2026, Python 3.11 or later) on Python 3.13. The code ran in the SDK's time-skipping test environment, which downloads a small test server on first use. Check names against the version you install.

In short

  • Temporal splits a job into deterministic workflow code that is replayed from a recorded event history, and activities that do the real work and may run more than once.
  • Retries, timeouts and heartbeats are policy on each activity call, and idempotency keys or upserts make repeated runs safe.
  • Histories are capped at 51,200 events or 50 MB and the toy measured about 7 events per section, so batch large fan-out with child workflows and continue-as-new, and rate-limit the model calls.
  • For short jobs a queue such as Celery or RQ is simpler; Temporal pays off when jobs run long, wait for people or must survive deploys.

Why LLM and document jobs suit durable execution

These jobs run for minutes to hours, call slow, metered, rate-limited services, and fail in the middle. Each model call costs money, so redoing finished work wastes it.

The usual answer is a hand-built state machine: a table of step statuses, a retry cron job, and recovery glue. Durable execution moves that bookkeeping into the platform, which persists each step result so ordinary code can resume.

Workflows and activities

A workflow is the orchestration code: the order of steps, the branching, the waiting. An activity is a function that touches the outside world: an API call, a database query, an LLM invocation, file input and output. The workflow docs draw this line, and the activity docs say an activity may run more than once.

A worker is your process that runs both. It polls a task queue, a named queue held by the Temporal Service, and executes whatever tasks arrive.

A worker polls a task queue on the Temporal Service, which stores the event history; activities call the model and the database Client Temporal Service task queue event history (append-only) Workflow code deterministic Activities may run twice LLM, DB your worker process
Figure 1. The worker pulls tasks from the service and reports results. Only activities reach the model and the database; every result is appended to the event history.

Event history, replay and determinism

The event history is the append-only log of everything that happened in one workflow execution: activity results, timers, received signals. If a worker dies, another worker re-runs the workflow code from the start. It does not restore a memory snapshot. Recorded results are fed back in, so finished activities are not run again. This is replay, described in the workflow docs.

Replay requires workflow code to be deterministic: the same history must always produce the same decisions. The docs list what breaks this: reading the current time directly, generating uncaptured random numbers, making network calls outside an activity. Use the SDK's own time, timers and activities instead.

The Python SDK also runs workflow files in a sandbox and re-imports the file at workflow start and on every replay. Keep top-level code free of side effects.

Retries, timeouts and heartbeats

Retries are policy, not code. The default activity retry policy starts at a 1 second interval, multiplies by 2.0 each time, caps the interval at 100 times the initial one, and allows unlimited attempts. No error type is non-retryable by default, so cap attempts or the total time yourself, and mark bad input as non-retryable.

Per the same page, the wait before retry k is the smaller of the initial interval times the coefficient to the power k minus 1, and the maximum interval. With the default cap and no attempt limit, a dead endpoint is called every 100 seconds for ever, so only a cap on attempts or on schedule-to-close bounds the spend. Exact schedules from retry_table.py (initial 1 second, coefficient 2):

AttemptDefault cap (100 s): wait, startCap 30 s (the example): wait, start
21 s, 1 s1 s, 1 s
44 s, 7 s4 s, 7 s
616 s, 31 s16 s, 31 s
732 s, 63 s30 s, 61 s
9100 s, 227 s30 s, 121 s
10100 s, 327 s30 s, 151 s

A flaky activity that failed five times and then succeeded, run in the time-skipping environment, started its attempts at 0, 1, 3, 7, 15 and 31 seconds. This matches the formula to within about 10 ms (measured with ActivityInfo.started_time; production jitter was not measured). The workflow history of that run held 11 events in total. Retries are not written to it as they happen: the retry docs say “the ActivityTaskStarted Event will not show up in the Workflow Execution Event History” while attempts are pending. Retries do not grow histories, but they are invisible there; use the Describe API for pending attempts.

Start times of six attempts of a failing activity under a retry policy with initial interval 1 second and coefficient 2: 0, 1, 3, 7, 15 and 31 seconds #1 0 s #2 1 s +1 #3 3 s +2 #4 7 s +4 #5 15 s +8 #6 31 s +16 Spacing not to scale. +n is the wait before that retry, in seconds. Attempts 1 to 5 failed.
Figure 2. Attempt start times of the flaky toy activity (synthetic, time-skipping server, measure.py). The retry waits double: 1, 2, 4, 8 and 16 seconds.

Timeouts say how long to wait before declaring an attempt lost. The activity timeout docs define four.

TimeoutBoundsDefault
Start-to-closeOne attemptNone; set this or schedule-to-close
Schedule-to-closeAll attempts, including waits between retriesUnlimited
Schedule-to-startTime queued before a worker picks it upUnlimited
HeartbeatGap between heartbeatsOff

Start-to-close is the one to set for model calls. A lost worker is noticed only through a timeout, so this one triggers the retry. Set it above the slowest legitimate call.

A heartbeat is a signal from a running activity that it is still alive, and it can carry progress. An OCR job over three hundred pages should heartbeat the page number, so a retry resumes from the last page, as ocr_pages does in the last code block. Set a heartbeat timeout as well, so a stalled attempt is declared lost before start-to-close expires.

Idempotency: why and how

An activity is at-least-once. The activity docs say a function may run several times and partly complete each time, for example when a worker finishes the work but crashes before reporting it. An idempotent operation gives the same end state however often it runs.

Two patterns cover most pipelines. First, an upsert keyed by a stable identifier, such as document and section, so a second write replaces the first. Second, an idempotency key sent to a downstream service that deduplicates. The docs suggest the workflow run ID combined with the activity ID, which is constant across retries and unique per execution. That key changes for a new execution of the same document, so to store a result once, key on the business identifier.

An LLM call is not idempotent: a retry may return different text and cost again. Replay does not regenerate the call: the recorded activity result is reused. Validate the output before it is recorded or written, as described in Trustworthy LLM Table Extraction: Layered Validation; on a validation failure, raise a non-retryable error or retry with a different prompt rather than repeating the identical call.

A runnable pipeline with a flaky model

The toy example below parses a document into four sections, calls a fake model per section in parallel, and writes results to an in-memory store. Section s2 fails twice with a transient error. Section s4 raises a non-retryable error. When any section fails, the workflow waits up to 24 hours for a reviewer's signal. A signal is a message sent to a running workflow. The time-skipping environment fast-forwards the retry delays and the 24 hour timer, so the whole run takes under a second.

"""Toy document pipeline on Temporal with a fake, flaky LLM. No network, no API keys."""
import asyncio
from dataclasses import dataclass
from datetime import timedelta

from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

@dataclass
class Section:
    doc_id: str
    section_id: str
    text: str


# Stand-in for a database table; the key makes writes idempotent (an upsert).
STORE: dict[str, dict] = {}
ATTEMPTS: dict[str, int] = {}


@activity.defn
async def parse_document(doc_id: str) -> list[Section]:
    return [Section(doc_id, f"s{i}", f"text of section {i}") for i in range(1, 5)]


@activity.defn
async def extract_section(section: Section) -> dict:
    """Fake LLM call. Section s2 fails twice with a transient error, s4 is empty."""
    attempt = activity.info().attempt  # 1 on the first try
    ATTEMPTS[section.section_id] = attempt
    if section.section_id == "s2" and attempt < 3:
        raise ConnectionError("fake 503 from the model endpoint")
    if section.section_id == "s4":
        raise ApplicationError("empty section", type="BadInput", non_retryable=True)
    return {"section": section.section_id, "summary": section.text.upper()}


@activity.defn
async def write_result(doc_id: str, section_id: str, payload: dict) -> str:
    key = f"{doc_id}:{section_id}"  # stable across retries
    STORE[key] = payload  # upsert: running twice leaves the same row
    return key


@workflow.defn
class ProcessDocument:
    def __init__(self) -> None:
        self.approved = False

    @workflow.signal
    def approve(self) -> None:
        self.approved = True

    @workflow.run
    async def run(self, doc_id: str) -> dict:
        sections = await workflow.execute_activity(
            parse_document, doc_id, start_to_close_timeout=timedelta(seconds=30)
        )
        retry = RetryPolicy(
            initial_interval=timedelta(seconds=1),
            backoff_coefficient=2.0,
            maximum_interval=timedelta(seconds=30),
            maximum_attempts=5,
            non_retryable_error_types=["BadInput"],
        )

        async def one(s: Section):
            try:
                payload = await workflow.execute_activity(
                    extract_section, s,
                    start_to_close_timeout=timedelta(seconds=60),
                    schedule_to_close_timeout=timedelta(minutes=10),
                    retry_policy=retry,
                )
            except Exception:
                return s.section_id, None
            await workflow.execute_activity(
                write_result, args=[doc_id, s.section_id, payload],
                start_to_close_timeout=timedelta(seconds=10),
            )
            return s.section_id, payload

        results = dict(await asyncio.gather(*(one(s) for s in sections)))
        failed = sorted(k for k, v in results.items() if v is None)
        # Human review of failures: wait up to 24 hours (a durable timer).
        reviewed = None
        if failed:
            try:
                await workflow.wait_condition(
                    lambda: self.approved, timeout=timedelta(hours=24)
                )
                reviewed = True
            except asyncio.TimeoutError:
                reviewed = False
        return {
            "done": sorted(k for k, v in results.items() if v),
            "failed": failed,
            "reviewed": reviewed,
        }


async def main() -> None:
    async with await WorkflowEnvironment.start_time_skipping() as env:
        async with Worker(
            env.client, task_queue="docs",
            workflows=[ProcessDocument],
            activities=[parse_document, extract_section, write_result],
            max_concurrent_activities=2,
        ):
            result = await env.client.execute_workflow(
                ProcessDocument.run, "doc-1", id="wf-doc-1", task_queue="docs"
            )
            # Second run: a reviewer approves by signal before the 24 h timer.
            handle = await env.client.start_workflow(
                ProcessDocument.run, "doc-2", id="wf-doc-2", task_queue="docs"
            )
            await handle.signal(ProcessDocument.approve)
            reviewed = await handle.result()
    print("result:", result)
    print("with signal:", reviewed)
    print("attempts:", dict(sorted(ATTEMPTS.items())))
    print("stored keys:", sorted(STORE))


if __name__ == "__main__":
    asyncio.run(main())

Output, from running the file as is (toy example, fake model, no network):

result: {'done': ['s1', 's2', 's3'], 'failed': ['s4'], 'reviewed': False}
with signal: {'done': ['s1', 's2', 's3'], 'failed': ['s4'], 'reviewed': True}
attempts: {'s1': 1, 's2': 3, 's3': 1, 's4': 1}
stored keys: ['doc-1:s1', 'doc-1:s2', 'doc-1:s3', 'doc-2:s1', 'doc-2:s2', 'doc-2:s3']

Section s2 needed three attempts and still produced one stored row. Section s4 was tried once, because BadInput is non-retryable. The first run waited out the 24 hour timer and ended with reviewed: False. The second run received the signal and ended with reviewed: True.

Rate limits and fan-out

Providers cap requests per minute, so unbounded parallelism turns into a stream of 429 errors. Three settings limit it, all visible in the SDK's Worker signature. max_concurrent_activities bounds how many activities one worker runs at once (the example uses 2). max_activities_per_second is a worker-side rate limit. max_task_queue_activities_per_second is the server-side limit for the whole task queue, described in the task queue tuning docs. Put model calls on their own task queue so the limit does not throttle other steps.

Fan-out has its own risk. One workflow that spawns an activity per section grows its history with every call. The limits page gives a warning at 10,240 events or 10 MB and a cap of 51,200 events or 50 MB. The child workflow docs advise starting with activities and adding child workflows when needed, since children produce more events. A parent should not spawn more than 1,000 children. For a big corpus, process documents in batches of child workflows and call continue-as-new, which closes the execution and starts a fresh one with a clean history and the same workflow ID, carrying only the arguments you pass. Await the children first; they do not carry over. The continue-as-new docs say to check “Continue-As-New Suggested” in the workflow; the Python SDK exposes it as workflow.info().is_continue_as_new_suggested(). Per the message-passing docs, call it from the main workflow method, not from an update handler, after workflow.all_handlers_finished.

To see how fast histories grow, the same work was run two ways in the time-skipping environment: one workflow with two activities per section (an extract and a write), and one parent starting a child workflow per section, each child running the same two activities. Event counts came from fetch_history(). The core of measure.py, with trivial activities (extract, write) and a SectionChild workflow that runs them in turn:

@workflow.defn
class FlatFanOut:                      # two activities per section, one workflow
    @workflow.run
    async def run(self, n: int) -> int:
        async def one(i: int) -> None:
            await workflow.execute_activity(extract, i, start_to_close_timeout=timedelta(seconds=60))
            await workflow.execute_activity(write, i, start_to_close_timeout=timedelta(seconds=60))
        await asyncio.gather(*(one(i) for i in range(n)))
        return n


@workflow.defn
class ChildFanOut:                     # the same work, one child workflow per section
    @workflow.run
    async def run(self, n: int) -> int:
        await asyncio.gather(*(workflow.execute_child_workflow(SectionChild.run, i) for i in range(n)))
        return n


async def n_events(client, wf_id: str) -> int:
    hist = await client.get_workflow_handle(wf_id).fetch_history()
    return len(hist.events)
SectionsEvents, activities in one workflowEvents, parent of child workflows
11714
108353
50389209
100770395
2001,448785

A least-squares line through the seven measured sizes (the table shows five of them) gives about 7.2 events per section in the flat workflow and 3.85 in the parent; one child alone has 17 events of its own. A second run gave 7.3 and 3.4. The parent count at 200 sections moved from 785 to 677 while the flat count stayed within 12 events, so the numbers are indicative, and the parent figures especially so. Extending the straight line (an extrapolation; nothing above 200 sections was run), the flat workflow reaches the 10,240 event warning near 1,400 sections and the 51,200 cap near 7,100. The parent reaches them near 2,700 to 3,000 and 13,300 to 15,100 (the first run gave the lower figures, the second the higher). The figure plots the first run. The child docs advise at most 1,000 children, so that limit comes first. Width is limited too: the limits page describes a maximum of incomplete activities, child workflows, signals and cancellation requests per execution, with 2,000 as the default for each, so a flat fan-out should be chunked well below that. Real histories grow faster than the toy: every signal, timer and extra activity adds events.

Measured event-history length against number of sections for activity fan-out and child-workflow fan-out, with straight-line extrapolation to the 10,240 and 51,200 event thresholds 10 100 1,000 10,000 100,000 1 10 100 1,000 10,000 Sections per document (log scale) Events in one history (log) 10,240 events: warning 51,200 events: cap Activities in one workflow Parent of child workflows Extrapolated
Figure 3. Event-history length against sections per document, on log axes. Points are measured (synthetic toy, two activities per section, measure.py); dashed lines are straight-line extrapolations beyond 200 sections.

Up to roughly a thousand sections per document, plain activities in one workflow stay under the warning and are simpler. Beyond that, or when each section needs its own timers, signals or retry history, use child workflows in batches with continue-as-new.

import asyncio
from datetime import timedelta

from temporalio import activity, workflow
from pipeline import ProcessDocument


async def run_ocr(path: str, page: int) -> None:  # stand-in for the real OCR call
    await asyncio.sleep(0)


@activity.defn
async def ocr_pages(path: str, n_pages: int) -> int:
    """Long activity: resume from the last heartbeat after a retry."""
    details = activity.info().heartbeat_details
    start = details[0] if details else 0
    for page in range(start, n_pages):
        await run_ocr(path, page)
        activity.heartbeat(page + 1)  # recorded for the next attempt
    return n_pages


@workflow.defn
class DocumentBatch:
    @workflow.run
    async def run(self, doc_ids: list[str], done: int = 0) -> int:
        size = 100
        chunk = doc_ids[done : done + size]
        await asyncio.gather(*(
            workflow.execute_child_workflow(
                ProcessDocument.run, d, id=f"doc-{d}"
            )
            for d in chunk
        ))
        done += len(chunk)
        if done < len(doc_ids):
            workflow.continue_as_new(args=[doc_ids, done])  # fresh history
        return done


@workflow.defn
class Patched:
    @workflow.run
    async def run(self, doc_id: str) -> str:
        if workflow.patched("validate-v2"):
            # New code path: only executions started after the deploy take it.
            return await workflow.execute_activity(
                "validate_v2", doc_id, start_to_close_timeout=timedelta(seconds=30)
            )
        return await workflow.execute_activity(
            "validate_v1", doc_id, start_to_close_timeout=timedelta(seconds=30)
        )

Unlike the toy example above, this file was only compiled and imported, not run. It shows heartbeat with resume, batched fan-out with continue-as-new, and a patch.

Humans and versioning

Review steps are where durable timers earn their place. The message-passing docs define three handler types. A query reads state and must not change it. A signal changes state and returns nothing. An update changes state, returns a result, and can reject bad input with a validator. Use a signal for a plain approve button, an update when the caller needs an answer, and a query to list pending sections. workflow.wait_condition waits for a flag with an optional timeout, as the example does.

Versioning is the hard part of long-lived workflows: a running execution replays against new code, and any change in the order of commands breaks determinism. The Python versioning docs describe patching: workflow.patched("name") records a marker, so new executions take the new branch and old ones keep the old. Once executions started before the patch have left retention, replace the old code with deprecate_patch, and remove that call when no open executions of the old code remain. Replay tests against saved histories confirm a change is safe.

The alternative is Worker Versioning. A pinned workflow runs to completion on the build it started on, so it needs no patch. Auto-upgrade workflows move to new code and still need patching. For a pipeline that continues-as-new, you can stay pinned and move to the new build at the continue-as-new boundary.

When Temporal is worth it, and when it is not

Temporal has costs. You run or buy a service, learn the determinism rules, and own versioning. The self-hosting guide lists deployment, visibility storage, security, monitoring and upgrades as tasks you take on. The alternative is Temporal's hosted service, which is not priced here.

OptionStrength for this jobCost or gap
Celery or RQ queueSimple, familiar; retries and backoff are opt-in per task; rate limit is per workerCrash redelivery needs acks_late and idempotent tasks; multi-step state is yours to store
PrefectPython flows and tasks with retries; crashed runs are marked CrashedThe flow docs do not say a crashed run resumes mid-flow; check before relying on it
AirflowScheduling, backfills, a mature UI; describes itself as orchestrating batch workflowsFits scheduled pipelines with a clear start and end, less a per-upload workflow that waits for a person
AWS Step Functions StandardManaged, up to one year, exactly-once state execution, no serversLogic lives in a state language; billed per state transition; tied to AWS
TemporalCode-first, resumes mid-run, signals, durable timers, replayService to operate, determinism and versioning discipline

This rule of thumb comes from the table, not from a benchmark. If a job finishes in seconds, has one or two steps and can be rerun safely, use a queue and keep a results table. If it runs for minutes or hours, has many paid steps, waits for people, or must survive deploys, durable execution removes code you would otherwise write and debug.

A checklist

  1. Put every model, OCR and database call in an activity; keep workflow code free of time, randomness and I/O.
  2. Set start-to-close on every activity, cap attempts or schedule-to-close, and list non-retryable error types.
  3. Heartbeat anything long, and resume from the heartbeat details.
  4. Log each run’s settings and scores so a regression is traceable, as in Making LLM Evaluation Reproducible with MLflow.
  5. Make writes upserts keyed by a business identifier.
  6. Put model calls on a dedicated task queue with worker and queue rate limits.
  7. Batch fan-out with child workflows and continue-as-new before histories near 10,240 events (about 1,400 sections of two activities each in the toy), and keep pending activities well below the 2,000 default limit.
  8. Add replay tests before the first production deploy, and decide between patching and Worker Versioning up front.

What this does not cover

  • Only the downloaded test server was used. Temporal Cloud and self-hosted clusters were not run, and throughput and cost were not measured. History sizes were measured up to 200 sections only, and event counts depend on timing and on what the workflow does.
  • The time-skipping test server printed a warning that it did not advertise the capability to preserve the latest heartbeat details when an activity fails. Test heartbeat resume against start_local() or a dev server instead. The SDK README also notes that the time-skipping server has no ARM build, with macOS using the x64 binary under emulation.
  • Retry jitter, rate-limit responses from real providers and history size in bytes were not measured. Payload limits, search attributes, payload encryption, schedules and the OCR and chunking steps are out of scope. The model is fake.
  • Worker Versioning reached general availability on 30 March 2026 (announcement). The same post puts Upgrade on Continue-as-New in Public Preview at that date; its current status was not checked. Workflow Update and Nexus were not tested, and the docs pages read do not state their status.

Sources