AIEP
Reliability & ResilienceValidated in ProductionUpdated 2026-12

Durable LLM Job Queue

Run long model work as jobs that are claimed atomically, leased with a timeout, recovered when a worker dies, capped when they keep crashing, and fenced so a stale worker can't overwrite a result.

Runnable example, tested in CISourceTestsJump to code
$cd examples && pytest reliability/test_durable_llm_job_queue.py
jobsqueuesworkerscrash-recoveryidempotency

What It Is

Model work that takes more than a few seconds (analysing a document, a multi-step pipeline, an agent run) belongs in a background job, not in the HTTP request. The API enqueues a job and returns an ID. A worker claims it, runs it and stores the result, and the client polls or gets a callback.

None of this is new. It's what job queues have always needed. LLM work makes the edge cases common rather than rare: calls are slow, expensive and flaky. So the four rules below stop being nice-to-haves.

The Problem It Solves

A naive worker loop fails in predictable ways once it has real traffic:

  • Double processing. Two consumers (a Redis pop and a "stale job" DB poll, or two replicas) both read status == "queued" and both start the job. You pay twice and write two results.
  • Lost jobs. A worker is killed mid-job by a deploy, the OOM killer or a spot reclaim. The job stays "processing" forever, and the user's page spins.
  • Infinite retries. One document that crashes the parser crashes every worker that picks it up, all night.
  • Stale overwrites. A slow worker whose job was already handed to someone else finishes late and overwrites the fresh result.

How It Works

stateDiagram-v2
    [*] --> queued: enqueue (id is unique)
    queued --> processing: atomic claim, attempts + 1, new token
    processing --> done: complete (only if the token still matches)
    processing --> queued: retryable failure, attempts left
    processing --> queued: watchdog: held longer than stuck timeout
    processing --> failed: invalid input, or attempts used up ("poison job")
    done --> [*]
    failed --> [*]
  1. Claim atomically. Moving a job from queued to processing is one conditional write: UPDATE … SET status='processing' WHERE id=? AND status='queued', or SELECT … FOR UPDATE SKIP LOCKED. If zero rows changed, someone else has it. "Read, check, then write" is never safe with more than one consumer.
  2. Lease, don't own. Each claim records when it started. A watchdog, run by every worker on every poll and not just once at startup, re-queues jobs held longer than the stuck timeout. The job's own hard timeout is shorter than the stuck timeout, so a live job is never mistaken for a dead one.
  3. Count attempts and stop. Every claim increments attempts. A job that has reached the maximum fails with a message a person can read. Invalid input fails straight away, because retrying won't fix it.
  4. Fence completions. Each claim gets a new token. Completing a job requires the token you claimed with, so a worker that lost its lease can't overwrite the attempt that replaced it.
  5. Back it with constraints. A unique result per job ID is a cheap second line of defence against anything that slips through.

When to Use It

  • Model work longer than a typical request timeout, or bursty work that would overwhelm the API if run inline.
  • More than one worker, or workers that restart: deploys, autoscaling, spot instances.
  • Jobs that are expensive enough that running them twice matters.

When NOT to Use It

  • Short interactive calls. A two-second chat reply should stream from the request. A queue adds latency and moving parts.
  • Workflows with many dependent steps. Use a durable workflow engine (Temporal, Restate, Inngest), which gives you this per step, rather than building a queue of queues.
  • Offline jobs with thousands of independent items. Batch Inference is cheaper, and the provider runs the queue.

Trade-offs

  • The timeouts are a judgment call. A stuck timeout that's too short re-queues slow but live jobs. Too long and users wait for a dead worker. Set the job's hard timeout first, then the stuck timeout comfortably above it.
  • At-least-once, not exactly-once. Recovery means a job can run again after a crash. Anything with side effects inside the job must be idempotent (Idempotent Tool Calls).
  • One more system to operate. The queue, its watchdog and its metrics (queue depth, age of oldest job, poison count) need owners and alerts.

Failure Modes

Watchdog only at startup. Recovery runs when a worker boots, so with several replicas, one replica's crash is never noticed by the others. Run the reaper on every poll cycle.

Stuck timeout shorter than the job timeout. Every long job is re-queued while it's still running, and runs two, three, four times. Validate the configuration at startup, as the example does.

Retrying the unfixable. A malformed upload raises the same parse error every attempt. Classify errors, and fail invalid input immediately.

A cache or queue outage takes down status pages. The status endpoint reads from the queue's cache, and when that's down, users see errors for jobs that finished. Read job status from the database of record, with the cache as an optimization.

Implementation Example

An in-memory queue with the four rules (atomic claim, leased processing with a watchdog, attempt caps with poison jobs, fencing tokens) and a one-iteration worker loop that retries timeouts but fails invalid input. The tests race 20 threads for one job, kill a worker mid-job, poison a job, and have a stale worker try to overwrite a fresh result.

cd examples && pytest reliability/test_durable_llm_job_queue.py
"""Durable LLM Job Queue.
 
Long model calls (document analysis, multi-step pipelines) run as jobs on a
worker, not inside the web request. Four rules keep those jobs from being
lost, run twice, or retried forever:
 
1. Claim atomically: one conditional update moves a job from queued to
   processing. Check-then-set lets two workers take the same job.
2. Every claim has a lease. A job processing longer than the stuck timeout
   was held by a worker that died; a watchdog puts it back in the queue.
   The job's own hard timeout is shorter than the stuck timeout, so a live
   job is never mistaken for a dead one.
3. Count attempts. A job that has crashed workers too many times is a poison
   job: fail it with a message instead of retrying forever.
4. Fence completions. Each claim gets a token; a worker whose lease was taken
   away can't overwrite the result of the attempt that replaced it.
 
The store here is in memory with a lock standing in for the database. In
production each method is one SQL statement (UPDATE ... WHERE status = ...
RETURNING, or SELECT ... FOR UPDATE SKIP LOCKED).
"""
 
from __future__ import annotations
 
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass
 
 
@dataclass
class Job:
    id: str
    payload: dict
    status: str = "queued"  # queued | processing | done | failed
    attempts: int = 0
    claimed_at: float = 0.0
    token: int = 0  # fencing token: changes on every claim
    result: object = None
    error: str = ""
 
 
@dataclass(frozen=True)
class Claim:
    job: Job
    token: int
 
 
class JobQueue:
    def __init__(self, job_timeout_s: float = 120, stuck_after_s: float = 300, max_attempts: int = 3,
                 clock: Callable[[], float] = time.monotonic):
        if job_timeout_s >= stuck_after_s:
            raise ValueError("job timeout must be shorter than the stuck timeout, or live jobs get re-queued")
        self.job_timeout_s, self.stuck_after_s, self.max_attempts = job_timeout_s, stuck_after_s, max_attempts
        self.clock = clock
        self.jobs: dict[str, Job] = {}
        self._lock = threading.Lock()  # the database's job, in production
 
    def enqueue(self, job_id: str, payload: dict) -> None:
        with self._lock:
            self.jobs.setdefault(job_id, Job(job_id, payload))  # same id twice: one job
 
    def claim(self, job_id: str) -> Claim | None:
        """UPDATE jobs SET status='processing', attempts=attempts+1 WHERE id=? AND status='queued'"""
        with self._lock:
            job = self.jobs.get(job_id)
            if job is None or job.status != "queued":
                return None
            job.status, job.attempts, job.claimed_at = "processing", job.attempts + 1, self.clock()
            job.token += 1
            return Claim(job, job.token)
 
    def claim_next(self) -> Claim | None:
        for job_id in [j.id for j in self.jobs.values() if j.status == "queued"]:
            if claim := self.claim(job_id):
                return claim
        return None
 
    def complete(self, claim: Claim, result: object) -> bool:
        """Accepted only if this claim still owns the job."""
        with self._lock:
            job = claim.job
            if job.status != "processing" or job.token != claim.token:
                return False  # lease lost: another attempt owns this job now
            job.status, job.result = "done", result
            return True
 
    def fail(self, claim: Claim, error: str, retryable: bool = True) -> None:
        with self._lock:
            job = claim.job
            if job.token != claim.token or job.status != "processing":
                return
            if retryable and job.attempts < self.max_attempts:
                job.status = "queued"
            else:
                job.status, job.error = "failed", error
 
    def reap_stuck(self) -> list[str]:
        """Run on every poll cycle by every worker, not once at startup."""
        now, changed = self.clock(), []
        with self._lock:
            for job in self.jobs.values():
                if job.status == "processing" and now - job.claimed_at > self.stuck_after_s:
                    if job.attempts >= self.max_attempts:
                        job.status = "failed"
                        job.error = "This job stopped the worker several times and was not retried."
                    else:
                        job.status = "queued"
                    changed.append(job.id)
        return changed
 
 
def work_once(queue: JobQueue, handler: Callable[[dict], object]) -> str | None:
    """One iteration of a worker loop. Returns the job id it handled, if any."""
    queue.reap_stuck()
    claim = queue.claim_next()
    if claim is None:
        return None
    try:
        result = handler(claim.job.payload)
    except TimeoutError as exc:
        queue.fail(claim, f"timed out: {exc}")
    except ValueError as exc:
        queue.fail(claim, f"invalid input: {exc}", retryable=False)  # retrying won't help
    else:
        queue.complete(claim, result)
    return claim.job.id

Tool Landscape

ToolNotes
Postgres (FOR UPDATE SKIP LOCKED), e.g. via Procrastinate, Oban, Solid QueueA queue in the database you already run
Celery, RQ, Sidekiq, BullMQWorker frameworks; check acknowledgement and visibility-timeout settings
Amazon SQS, Google Cloud TasksManaged queues with visibility timeouts (a lease by another name)
Temporal, Restate, InngestDurable workflows when a job is many steps

Further Reading

Spotted something wrong or have a production story? Edit this page on GitHub.