# Kill the Worker, Keep the Work: Resumable Background Agent Runs in Django (Part 12)

On November 17, Microsoft announced a public-preview Azure Durable Task integration that lets LangGraph agents [survive worker crashes and restarts](https://techcommunity.microsoft.com/blog/appsonazureblog/introducing-azure-durable-task-for-langgraph-agents/4574019). The post is careful about what that buys you. Completed steps are persisted, and "Interrupted work whose result was not recorded can run again." Then, in one line: "Activities run at least once, not exactly once." The [Pydantic AI version](https://techcommunity.microsoft.com/blog/appsonazureblog/introducing-azure-durable-task-for-pydantic-ai-agents/4571024) says the same: "Durable recovery does not guarantee exactly-once side effects."

That's the honest contract for any background worker. When one dies mid-run (a deploy, an out-of-memory kill), two questions decide the cost: how much finished work do you pay for again, and which side effects happen twice?

This is Part 12 of **Shipping AI Agents in Django**. [Part 11](https://aidevpro.hashnode.dev/per-tenant-llm-rate-limits-token-budgets-django) gave every tenant a fair share of the provider's rate limits, and when a tenant ran out it could wait inside the deadline, get a 429, or get a degraded answer. All three assume someone is waiting on the response. Bulk work doesn't have anyone waiting, so this part moves it off the request. The pieces: a fair queue, steps that resume after a crash, and a status endpoint the client polls.

> **Short version**
>
> - Return `202 Accepted` and a status URL. Accept an `Idempotency-Key` header so a client retrying the POST doesn't start the run twice.
> - Use a Postgres table as the queue. A run becomes visible to workers when its transaction commits, and not before.
> - Claim with `SELECT ... FOR UPDATE SKIP LOCKED`, choosing the tenant that was served least recently and has a free concurrency slot. Workers skip rows another worker holds instead of waiting on them.
> - Each claim comes with a lease. A worker that stops checkpointing loses it, and every write a worker makes checks its lease token first, so a stalled "zombie" worker can't finish a run that someone else now owns.
> - Checkpoint each step. Finished steps replay from the database. A step that was mid-flight runs again, so side effects take a stable idempotency key and the receiver dedupes on it.
> - When a tenant is over its quota, defer the run to a start time. Don't make a worker sleep, and don't count it as a failure.
> - The status endpoint returns progress with an `ETag`, so clients can poll often at low cost.

The demo is Part 11's Django 5.2 app plus a runs module. It has 110 passing tests on PostgreSQL 17.12: the 93 from Part 11, unchanged, plus 17 new. On SQLite, 107 pass and the 3 that need real row locks are skipped.

## What belongs off the request

One post's verdict fits in a request: Part 10 gave the chain an 8-second deadline. Re-checking 4,000 posts after a policy change doesn't fit, and neither does a ten-step agent run that calls tools between model calls. Picture an admin who uploads a film and wants subtitles in four languages, two of the walkthroughs on LyStream's [how-to page](https://lystream.lycore.com/how-to). That kind of job is long, has several steps, and needs to show progress. It doesn't fit in one HTTP request either.

Django's own docs are blunt about streaming as a workaround: "Django, under WSGI, is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response." They add that you'd "generally" do expensive work outside the request-response cycle ([docs](https://docs.djangoproject.com/en/6.1/ref/request-response/)).

## Picking a queue backend

There are real options, and this is a choice of trade-offs:

**Django's Tasks framework** ([added in 6.0](https://docs.djangoproject.com/en/6.0/releases/6.0/); 6.1 shipped August 5, 2026) gives you `@task`, `enqueue()`, priorities and results. Per the [docs](https://docs.djangoproject.com/en/6.1/topics/tasks/), "It does not provide a worker mechanism to run Tasks," and the built-in backends are "for development and testing only." The 6.1 [release notes](https://docs.djangoproject.com/en/6.1/releases/6.1/) added `**kwargs` passthrough and picklable tasks, still with no worker. For a database backend with a worker, there's Jake Howard's [django-tasks-db](https://pypi.org/project/django-tasks-db/) (0.13.0, August 28), which adds a `db_worker` command and supports Django 5.2+.

**Celery** ([5.7.0](https://docs.celeryq.dev/en/latest/changelog.html), November 5) is the mature choice, with a broker and a big ecosystem. Its [docs](https://docs.celeryq.dev/en/stable/userguide/tasks.html) state the same contract as the durable-execution posts: with `acks_late`, "the task may be executed multiple times should the worker crash in the middle of execution. Make sure your tasks are idempotent."

**Procrastinate** ([3.12.0](https://github.com/procrastinate-org/procrastinate/releases), November 19) is a PostgreSQL-based queue with Django integration. Its new `lock_mode="mutex"` "keeps jobs sharing a lock from running at the same time." With the tenant as the lock, that gives you one-at-a-time per tenant.

**A durable-execution engine** ([Temporal](https://temporal.io/news/temporal-cloud-is-now-available-on-microsoft-marketplace), Azure Durable Task, [Dapr workflows via Diagrid](https://www.diagrid.io/blog/diagrid-microsoft-foundry-durable-agents)) records step history for you. The price is new infrastructure, a new programming model and, in Azure's case, activity inputs and outputs that "still pass through" its scheduler.

The demo uses **its own table**, for three reasons. The run, its checkpoints and its status already live in Postgres, so the queue, the progress bar and the audit trail are the same rows. Per-tenant fairness becomes an `ORDER BY` you can read. And there's no new service to run.

The cost: polling adds database load, every claim and heartbeat is an `UPDATE` (and in Postgres "an UPDATE or DELETE of a row does not immediately remove the old version of the row", per the [vacuum docs](https://www.postgresql.org/docs/current/routine-vacuuming.html)), and you own the code. My heuristic, not a benchmark: once the queue table is among your busiest, or you need scheduling, chains and a dashboard, move to one of the libraries above and keep the checkpoint and fairness ideas from this post.

## Step 1: the row is the queue

```python
class AgentRun(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tenant = models.CharField(max_length=50)
    kind = models.CharField(max_length=50)                 # which workflow runs it
    input = models.JSONField()
    idempotency_key = models.CharField(max_length=100, blank=True)
    fingerprint = models.CharField(max_length=64, blank=True)   # of input, for key reuse
    status = models.CharField(max_length=10, choices=Status.choices, default=Status.QUEUED)
    available_at = models.DateTimeField()                  # deferred runs wait until then
    failures = models.PositiveSmallIntegerField(default=0)  # crashes, expired leases, errors
    lease_token = models.CharField(max_length=32, blank=True)   # fences zombie workers
    lease_until = models.DateTimeField(null=True)
    note = models.CharField(max_length=100, blank=True)    # e.g. "tenant_limited"
    result = models.JSONField(null=True)
    # + total_steps, worker, created_at, finished_at; unique (tenant, idempotency_key)
```

Django's tasks docs have a [section on transactions](https://docs.djangoproject.com/en/6.1/topics/tasks/) because, when the queue lives outside your database, a worker can pick up a task "before the Thing is committed." Their fix is `transaction.on_commit()`. When the queue *is* a table in your database, the gap doesn't exist: a row inserted inside a transaction can't be claimed until that transaction commits, and if it rolls back, the row is gone. One test holds a transaction open in another thread and checks that `claim()` returns nothing until it commits.

The view returns [`202 Accepted`](https://www.rfc-editor.org/rfc/rfc9110.html#name-202-accepted). RFC 9110 calls it "intentionally noncommittal," built so the server can accept work "without requiring that the user agent's connection to the server persist until the process is completed." A `Location` header points at the status URL:

```python
run, created = submit(_tenant(request), "remoderate", {"posts": posts},
                      idempotency_key=request.headers.get("Idempotency-Key", ""),
                      total_steps=len(posts) + 1)
resp = JsonResponse(_status_body(run), status=202)
resp["Location"] = f"/runs/{run.pk}/"
```

The `Idempotency-Key` header follows the IETF draft, which reached [draft-09](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) on November 21. A repeated key returns the original run. A key reused "with a different request payload" should get a 422, so `submit()` stores a SHA-256 fingerprint of the input and compares it. Keys are scoped per tenant.

## Step 2: claims that skip, and tenants that take turns

Postgres's [`SELECT` docs](https://www.postgresql.org/docs/current/sql-select.html) explain why `SKIP LOCKED` exists: it "provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table." Django exposes it as [`select_for_update(skip_locked=True)`](https://docs.djangoproject.com/en/6.1/ref/models/querysets/#select-for-update).

A FIFO queue with `SKIP LOCKED` is fast, and it's also unfair. One tenant's 4,000-post job queued at 09:00 holds up everyone who queues at 09:01. So the demo claims in two steps. First it picks the *tenant*: one row per tenant in `TenantLane`, the least recently served first. Then it picks that tenant's oldest ready run:

```python
def claim(worker, max_lanes=5) -> AgentRun | None:
    now, tried = clock(), []
    for _ in range(max_lanes):
        with transaction.atomic():
            ready = AgentRun.objects.filter(tenant=OuterRef("tenant"), status=Q,
                                            available_at__lte=now)
            lane = (TenantLane.objects.select_for_update(skip_locked=True)
                    .filter(Exists(ready)).exclude(tenant__in=tried)
                    .order_by(F("last_claimed_at").asc(nulls_first=True), "tenant").first())
            if lane is None:
                return None
            tried.append(lane.tenant)
            # We hold this tenant's lane lock, so no other worker can claim for it right now:
            # this count can't go stale before we commit.
            if AgentRun.objects.filter(tenant=lane.tenant, status=RUNNING).count() \
                    >= concurrency_cap(lane.tenant):
                continue
            run = (AgentRun.objects.select_for_update(skip_locked=True)
                   .filter(tenant=lane.tenant, status=Q, available_at__lte=now)
                   .order_by("available_at", "created_at").first())
            if run is None:
                continue
            run.status, run.worker, run.lease_token = RUNNING, worker, uuid.uuid4().hex
            run.lease_until = now + timedelta(seconds=settings.RUNS["lease_s"])
            run.save(update_fields=["status", "worker", "lease_token", "lease_until"])
            lane.last_claimed_at = now
            lane.save(update_fields=["last_claimed_at"])
            return run
    return None
```

The lane lock gives round-robin order across tenants and makes the per-tenant concurrency cap hard (1 running run for standard, 2 for pro, 4 for internal, reusing Part 11's tiers). Without it, two workers could each count "1 running, cap 2" at the same moment and both claim. The `nulls_first=True` matters too: Postgres defaults to `NULLS LAST` for ascending order ([docs](https://www.postgresql.org/docs/current/sql-select.html#SQL-ORDERBY)), so a tenant that has never been served would otherwise go to the back of the line.

With a noisy tenant's five runs queued before two quiet tenants' single runs, one worker claims in the order `noisy, quiet1, quiet2, noisy, noisy, noisy, noisy`. FIFO would run all five noisy ones first. On Postgres, 12 threads racing over 18 queued runs claim exactly 7 (1 + 2 + 4), none of them twice. Another test holds one tenant's lane lock in a separate transaction and checks that `claim()` returns the other tenant's run immediately instead of blocking.

Part 11 decides how fast each tenant may call the provider; this decides whose run starts next.

## Step 3: leases, a reaper, and fencing

A worker that gets `kill -9`'d doesn't clean up. Its runs stay `running`. So every claim comes with a lease (60 seconds in the demo), every checkpoint extends it, and `reap()` requeues runs whose lease has expired. That counts as a failure, with backoff (5 s, then 10 s). After three failures the run is marked `failed`, so a run that crashes the worker every time can't loop forever.

The harder case is a worker that's only slow (a long GC pause, a hung socket). The reaper requeues its run, another worker claims it, then the slow one wakes up. Every write therefore checks the lease token first, inside the same transaction as the write:

```python
def _fence(self):
    """Extend our lease, but only if we still hold it. Runs inside the checkpoint's
    transaction, so a zombie's checkpoint rolls back with it."""
    lease = clock() + timedelta(seconds=settings.RUNS["lease_s"])
    if not AgentRun.objects.filter(pk=self.run.pk, status=RUNNING,
                                   lease_token=self.run.lease_token).update(lease_until=lease):
        raise LeaseLost(str(self.run.pk))
```

Finishing or requeuing a run goes through the same `lease_token` filter. In the zombie test, the stale worker wakes up after the second worker has finished. It makes no model calls and sends no webhooks, and `execute()` returns `lease_lost`.

One rule falls out of this: **the lease must outlast your longest step**, because heartbeats only happen at checkpoints. Part 10's 8-second deadline caps a model step, so 60 seconds leaves room. A tool call with no deadline breaks this. Give it a deadline, or heartbeat from a thread.

## Step 4: checkpoints, and the three crash windows

A workflow does work only through `ctx.step()` and `ctx.effect()`:

```python
def step(self, name, fn):
    """Run fn once per run. Its JSON output is checkpointed and replayed on resume."""
    s = self.done.get(name)
    if s and s.status == RunStep.Status.DONE:
        return s.output
    out = fn()
    self._save(name, RunStep.Status.DONE, out)
    return out

def effect(self, name, fn):
    """A side effect outside our database. fn gets a stable idempotency key; the receiver
    must dedupe on it, because a crash after the call but before the checkpoint repeats it."""
    s = self.done.get(name)
    if s and s.status == RunStep.Status.DONE:
        return s.output
    key = f"run:{self.run.pk}:{name}"
    self._save(name, RunStep.Status.STARTED, {"idempotency_key": key})   # intent first
    out = fn(key)
    self._save(name, RunStep.Status.DONE, out)
    return out
```

The demo workflow re-moderates a list of posts, one step per post, then sends the tenant a single summary webhook:

```python
for post in data["posts"]:
    def one(p=post):
        s = decide("moderation", p["text"], p["key"], tenant=ctx.run.tenant, policy=batch)
        return {"action": s.action, "provider": s.provider, "replayed": s.replayed}
    actions[post["key"]] = ctx.step(f"decide:{post['key']}", one)["action"]
hidden = sorted(k for k, a in actions.items() if a == "hide")
ctx.effect("notify", lambda key: notify(ctx.run.tenant, {"run": str(ctx.run.pk),
                                                         "hidden": hidden}, key))
```

"Resumable" only means something once you know where a crash can land. Three places:

**1. During a model call.** The request went out, and the worker died before the response came back. Nothing was recorded, so on resume the call runs again. You pay for it twice. With four posts and a crash during post 3's call, the resumed run calls the model `[1, 1, 2, 1]` times for posts 1 to 4. Checkpoints can't remove this window. They keep it to the one step that was in flight.

**2. After the side effect committed, before the checkpoint.** `decide()` writes the `Decision` and `PostAction` in one transaction, keyed by the post (Part 10). If the worker dies right after that, the step isn't checkpointed, but the decision is already stored. On resume, `decide()` finds the key and replays it with no model call. The test checks that post 2 was called once and that its step output says `"replayed": true`. That's two layers working together: the run checkpoint, and the per-item idempotency key underneath it. My heuristic is that if a side effect lands in your own database, it should commit in the same transaction as something keyed, so a replay can find it.

**3. After an external effect, before the checkpoint.** The webhook was delivered, and the worker died before recording it. On resume the call happens again; nothing can prevent that. What you control is that it carries the same key (`run:<id>:notify`), so a receiver that honours `Idempotency-Key` returns the first result. In the test, the webhook is called twice with the same key, and one delivery exists. The `STARTED` row written *before* the call also leaves a record that the effect may have happened. That's the row you'd reconcile from if the receiver can't dedupe.

This is exactly the boundary the LangGraph post draws: use a durable call id "as a durable idempotency key and enforce deduplication at the external mutation boundary." A library can give you the key. It can't make your payment provider or CRM honour it.

## Step 5: when the quota says "not yet"

Part 11's `wait` policy held a worker in `sleep()`. In a background run nobody is waiting, so the worker shouldn't wait either. The workflow calls `decide()` with `ChainPolicy(on_limit="reject", priority="batch")`, which keeps Part 11's 20% batch headroom for interactive traffic, and `execute()` turns `Limited` into a deferral:

```python
except Limited as e:
    # Out of quota (Part 11). Nobody is waiting on this run, so don't hold a worker:
    # put it back with a start time, and don't count it as a failure.
    ok = _release(run, status=Q, note=f"{e.scope}_limited",
                  available_at=clock() + timedelta(seconds=e.retry_after))
    return Q if ok else "lease_lost"
```

The test uses Part 11's small limits (3 requests of burst for a standard tenant) with four posts. The first three are checkpointed, the fourth hits the tenant bucket, and the run goes back to `queued` with `failures == 0`, `note == "tenant_limited"`, and a start time under 4 seconds away. It can't be claimed before then. Afterwards it finishes, with each post's model called exactly once. This path runs the real Lua scripts, through fakeredis and against Redis 8.0.2.

## Step 6: a status endpoint worth polling

```python
def run_status(request, run_id):
    # Another tenant's run is a 404, not a 403: don't confirm it exists.
    run = AgentRun.objects.filter(pk=run_id, tenant=_tenant(request)).first()
    if run is None:
        return JsonResponse({"error": "not_found"}, status=404)
    body = _status_body(run)
    etag = '"%s"' % hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:16]
    if request.headers.get("If-None-Match") == etag:
        resp = HttpResponseNotModified()
    else:
        resp = JsonResponse(body)
    resp["ETag"] = etag
    resp["Cache-Control"] = "no-store"
    return resp
```

The body has `status`, `steps_done`/`steps_total`, the `result` once the run is done, and `poll_after_s` while it's still running. A deferred run also says why (`waiting_for: "tenant_limited"`) and when it starts. That way the client can show "waiting for capacity" rather than a stuck spinner. The `ETag` is a hash of the body, so a poll where nothing changed costs two small indexed queries and an empty 304.

**What about SSE?** Server-sent events give a smoother progress bar, but each stream is a long-lived response, which that WSGI note warns about. Under ASGI it's cheaper, but something still has to push changes: a loop in the stream, or Postgres `LISTEN/NOTIFY`. Notifications are tied to transactions: "if a NOTIFY is executed inside a transaction, the notify events are not delivered until and unless the transaction is committed" ([docs](https://www.postgresql.org/docs/current/sql-notify.html)), so a listener never sees progress that later rolled back. My default: poll with an ETag, and add SSE only for a screen where someone actually watches the bar. The same `NOTIFY` could also replace the worker's one-second poll.

## Trade-offs I haven't solved

**Fairness is per claim, not per cost.** Round-robin gives every tenant a turn, but a turn running 4,000 posts and a turn running one post count the same. Smaller runs (chunk big jobs into runs of, say, 100 items) bring it closer to fair. Weighting turns by estimated tokens would go further.

**Capped tenants cost scans.** `claim()` tries at most 5 lanes. If more than five tenants ahead of you are at their cap, a claim can come back empty while work waits further down. A real version would filter capped tenants in SQL, for example with a running count kept on the lane row.

**Step outputs are stored.** Part 9 kept post text out of the `Inference` table. Checkpoints undo that if a step returns text, so keep outputs small (keys, verdicts) and give the table a retention rule.

**Workflow code changes between crash and resume.** If a deploy renames steps, old checkpoints stop matching and the work runs again. Treat a step rename like a migration.

## What the tests prove

`pytest -q` with `DEMO_PG=1`: **110 passed** (Python 3.13.5, Django 5.2.19, PostgreSQL 17.12, psycopg 3.3.9, pydantic 2.14.3, pytest 9.2.0, pytest-django 4.14.0, redis-py 8.2.0, fakeredis 2.41.0 with lupa 2.8). The result was stable over 10 runs and also passes against a real Redis 8.0.2. On SQLite: 107 passed, 3 skipped. That's expected: per [Django's docs](https://docs.djangoproject.com/en/6.1/ref/models/querysets/#select-for-update), on SQLite `select_for_update()` "will have no effect."

The 17 new tests cover: 202 plus `Location`, and Idempotency-Key replay and 422; round-robin order; concurrency caps; deferred start times; a crash mid-call (`[1, 1, 2, 1]` model calls); a crash after the decision committed (replayed, no call); a crash after the webhook (same key, one delivery); a zombie worker fenced out; a run failed after three crashes; an exception retried with backoff; quota deferral without a failure; status ETags and the per-tenant 404; the worker command. On Postgres only: no claim before commit, a locked lane skipped rather than waited on, and 12 racing workers claiming 7 runs with no duplicates.

Crashes are a `BaseException` the worker can't catch, and model calls are scripted. These tests prove bookkeeping, not throughput or how your real receivers behave.

## The series so far

1. [Human-in-the-loop AI agents in Django: approval gates](https://aidevpro.hashnode.dev/human-in-the-loop-ai-agents-django-approval-gates)
2. [Least-privilege agent identity in Django](https://aidevpro.hashnode.dev/ai-agent-least-privilege-identity-django)
3. [Your MCP server is a second API](https://aidevpro.hashnode.dev/mcp-server-django-row-level-permissions-agents)
4. [Permission-aware RAG without post-filters](https://aidevpro.hashnode.dev/permission-aware-rag-django-prefilter)
5. [Cost per successful workflow](https://aidevpro.hashnode.dev/llm-cost-per-successful-workflow-django)
6. [Tracing agent runs with OpenTelemetry](https://aidevpro.hashnode.dev/opentelemetry-tracing-ai-agents-django)
7. [Structured outputs that don't break](https://aidevpro.hashnode.dev/structured-llm-outputs-pydantic-django)
8. [AI moderation helpers with appeals](https://aidevpro.hashnode.dev/ai-content-moderation-django-appeals)
9. [Shipping prompt and model changes safely](https://aidevpro.hashnode.dev/llm-prompt-model-changes-shadow-canary-rollback-django)
10. [Provider fallbacks without surprises](https://aidevpro.hashnode.dev/llm-provider-fallback-failover-django)
11. [Per-tenant rate limits and token budgets](https://aidevpro.hashnode.dev/per-tenant-llm-rate-limits-token-budgets-django)
12. Background agent runs: fair queues, checkpoints, status (this post)

**Next, Part 13:** runs that wait for people. Part 1 modelled approvals as data. Part 13 puts them inside a background run: park at the step that needs approval without holding a worker, time out if nobody answers, and resume with the decision.

The demo is the Part 11 app plus `runs.py`, three models and a migration, two views, a `run_agents` worker command, and `tests/test_runs.py`.

## Open question for readers

The trade-off I keep going back and forth on: **one big run, or many small ones?** A 4,000-post re-check as one run, with a step per post, gives the client one status URL, one progress bar and one summary webhook. But it holds a tenant's turn for a long time, and if a lot of its steps crash, they all count against one run's failure budget. Splitting it into 40 runs of 100 makes fairness and retries finer-grained. Then you need a parent object to roll up status, and "send one summary when everything's done" becomes its own coordination problem.

Where do you split? Per item, per fixed-size chunk, or per tenant-visible job with steps inside? And has a durable-execution engine earned its keep for you over a table and a reaper? I'd like to hear what you run.
