Designing a Multi-Agent Task Queue That Survives Failures
AI agents are useful precisely because they can act on instructions that do not map to a single deterministic function. A research agent may discover new documents, a coding agent may split a task into smaller changes, and a reviewer may request another pass. Once those agents share a queue, however, their unpredictability makes an old distributed-systems problem harder: who owns each piece of work, what happens when that owner disappears, and which actions are safe to repeat?
A robust design does not promise that every task runs exactly once. It promises that the system can discover unfinished work, assign a new executor, preserve completed progress, and prevent an expired executor from corrupting durable state. The hard part is not retrying an LLM call. It is distinguishing a call that certainly failed from an external action that may already have succeeded.
Companion project: Agent Queue Lab is an open-source, runnable implementation of the architectural patterns discussed in this article. Built with Python, PostgreSQL and Docker Compose, it includes reproducible failure scenarios, simulated agents and an operational dashboard. No external API keys are required for the default experiments.
Separate work orchestration from the agents
An agent is an executor. The queue is a durable contract about work that should happen. Do not make an agent's process memory the authoritative record of either the task graph or its completion.
A practical architecture has four responsibilities:
- Task store: immutable identifiers and inputs; mutable status, retries, deadlines, ownership and result references.
- Scheduler: identifies eligible tasks, respects dependencies and quotas, and chooses when a task may run.
- Workers: claim an execution attempt, invoke an agent and its tools, heartbeat and report outcomes.
- Effect boundary: records or reconciles interactions with external systems such as Git hosting, cloud APIs, payment services and messaging.
The fourth responsibility matters because a task can fail locally after successfully changing a remote resource. The queue can roll back its own transaction; it cannot roll back a commit already accepted by another service.
The following architecture illustrates how these responsibilities are separated in Agent Queue Lab. PostgreSQL holds the authoritative workflow state, while independent workers execute tasks and interact with external services.
This distinction also prevents an attractive architectural mistake: confusing a message broker with a workflow engine. A broker transports work and provides delivery mechanisms. It does not automatically maintain a dependency graph, persist an agent's intermediate decisions, or verify whether a tool side effect happened.
Define the task state machine first
Use explicit statuses rather than relying on a collection of loosely related flags. A useful starting model is:
pending -> ready -> leased -> succeeded
| |
| +-> retry_wait -> ready
+----------> failed_terminal
+----------> needs_review
+----------> cancelled
A dependency-blocked task remains pending; it becomes ready only after all required predecessors have reached the right terminal state. leased means that one attempt currently has a valid claim, not that only one process can possibly be executing. retry_wait prevents a repeatedly failing tool from saturating workers. needs_review captures ambiguity that automation should not resolve blindly.
Persist both a stable task ID and a distinct attempt ID. The stable identity supports deduplication and dependency references. An attempt identifies one lease and its logs. A retry should not overwrite historical evidence about why an earlier attempt failed.
A minimal task row could contain:
task_id, workflow_id, task_type, input_ref, input_version,
state, priority, available_at, deadline_at,
attempt_count, max_attempts, lease_owner,
lease_expires_at, lease_generation,
result_ref, last_error_class, created_at, updated_at
Keep payloads and tool outputs in versioned storage if they are large or sensitive; keep durable references, content hashes and access controls in the task store. For every transition record who requested it and why. This audit trail is useful when a human approval resumes a workflow after a long pause.
Claim tasks atomically
Two workers must not independently turn the same ready row into their own valid lease. With PostgreSQL, select and update the row within one transaction. PostgreSQL explicitly describes SKIP LOCKED as suitable for avoiding contention among consumers of queue-like tables, while warning that it produces an inconsistent view. It is a useful claim primitive, not a general-purpose reporting query.
An illustrative claim query is:
WITH picked AS (
SELECT task_id
FROM tasks
WHERE state = 'ready'
AND available_at <= clock_timestamp()
ORDER BY priority DESC, created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE tasks AS t
SET state = 'leased',
lease_owner = $1,
lease_generation = t.lease_generation + 1,
lease_expires_at = clock_timestamp() + $2::interval,
attempt_count = t.attempt_count + 1,
updated_at = clock_timestamp()
FROM picked
WHERE t.task_id = picked.task_id
RETURNING t.*;
Treat this as a design sketch, not a drop-in production migration. A production schema needs types, indexes, constraints and a transaction boundary. Define the lease interval through a validated parameter, keep tasks indexed by eligibility, and avoid arbitrary user-provided SQL in a worker. For weighted fairness, tenant isolation or worker capabilities, the scheduler may need additional selection constraints.
A successful claim returns a token containing the task ID, owner and lease generation. Every heartbeat, result commit and state transition must check that generation. Never permit completion simply because the requester knows the task ID.
Recover expired leases without trusting old workers
Suppose worker A claims a task, calls an external model, and then loses network access to the database. The lease expires. Worker B claims a new attempt. A later regains connectivity and tries to report success.
If the completion endpoint checks only task_id, worker A can overwrite B's result or advance the workflow using stale output. A monotonically increasing generation acts as a fencing token:
UPDATE tasks
SET state = 'succeeded',
result_ref = $3,
lease_owner = NULL,
lease_expires_at = NULL
WHERE task_id = $1
AND state = 'leased'
AND lease_generation = $2
AND lease_expires_at > clock_timestamp()
RETURNING task_id;
Zero updated rows means this attempt no longer owns the task. Do not treat it as success. Store its logs separately for diagnosis without letting it alter the canonical result.
The following illustration shows the moment at which an expired worker loses ownership of a task and another worker acquires a new execution lease.
The expired worker may still be running, but it no longer has the authority to commit a result. In the Agent Queue Lab, this behaviour is demonstrated by deliberately pausing a worker beyond its lease duration, allowing another worker to complete the task, and verifying that the stale completion is rejected.
Fencing the database alone does not fence an external API. If worker A is still executing a tool when B starts, both may perform a remote action. Where a downstream resource supports a conditional revision, idempotency key or fencing token, use it. Otherwise design a reconciliation step that checks whether the action already occurred before issuing it again. The Temporal guidance on locking shared resources explicitly calls out fencing for external resources vulnerable to overlapping holders.
Heartbeat intervals and lease durations are workload-specific. A lease long enough for an ordinary tool call may be too short for an approval wait, while an excessively long lease delays recovery. Keep external calls bounded, heartbeat during long-running operations, and represent human approval as a persistent waiting state rather than a worker holding a lease indefinitely.
Build for at-least-once execution, not assumed exactly once
AWS documents that SQS standard queues can deliver a message more than once, including situations where a visibility timeout has not eliminated duplicate delivery. This is a useful mental model for multi-agent workers even when the underlying queue is a database.
Consider an agent instructed to open a pull request. The hosting API creates it, but the worker crashes before recording success. When the task is retried, a second pull request may appear. No internal queue transaction can make the remote API and the local database commit atomically.
Give each logical effect a stable key, such as workflow_id + task_id + effect_name. Before attempting the effect, create an effect-ledger entry; on retry, reuse the same key and inspect its state. If the remote API supports idempotency keys, send that stable key. If it does not, use a unique marker or remote lookup to reconcile ambiguity. Persist the remote identifier after confirmation.
An effect ledger can distinguish planned, in_flight, confirmed, uncertain and reconciled. The uncertain state is a deliberate feature, not an implementation embarrassment. Automatically repeating an uncertain financial transaction or destructive operation may be worse than pausing for an operator.
The Agent Queue Lab companion project demonstrates this failure mode by running the same scenario against two execution profiles: naive and durable. In both cases, the remote service creates a pull request before the worker crashes.
Both workflows report success, but only the durable implementation preserves the intended invariant. This difference was reproduced in the companion project's automated acceptance tests using an independent mock Git service.
SQS FIFO queues offer deduplication and ordering mechanisms, but the documented deduplication interval is five minutes. That transport feature does not replace end-to-end protection for side effects that can be retried after a longer disruption.
Make retries a policy, not a catch-all
An agent failure can mean different things. A rate limit may clear. A malformed tool argument will not clear by waiting. A lost connection after sending a request is ambiguous. A revoked credential requires intervention. A cancellation should not be retried as an error.
Classify outcomes before choosing the next state:
| Outcome | Typical handling |
|---|---|
| Transient service error | Exponential backoff with jitter and a bounded attempt budget |
| Rate limit | Respect a valid retry hint and shared provider limits |
| Invalid input or policy rejection | Terminal failure, or corrective task with explicit provenance |
| Worker crash or expired lease | Reclaim work, with dedupe/reconciliation at the effect boundary |
| Unknown remote result | Reconcile before reissuing the action |
| Human approval required | Suspend durably; resume on authenticated decision |
| Workflow cancelled | Stop new work and request cooperative cancellation of active attempts |
A retry budget should combine maximum attempts, elapsed-time deadline and an expenditure ceiling. Model calls are not free, and a failed agent can continue to incur cost while creating no useful output. Do not bury provider SDK retries inside larger task retries without accounting for their multiplication.
Amazon SQS dead-letter queue guidance describes how repeated receives can move messages for separate handling. In an agent platform, terminal and quarantined tasks need a comparable operator path: inspect an error, repair inputs or credentials, and explicitly replay with a new attempt. A dead-letter queue by itself does not explain the failure.
Preserve dependency progress across restarts
Multi-agent workflows are often directed acyclic graphs. A planner creates research and coding branches; a synthesis agent waits for both; a reviewer may create a revision branch. Durable dependency edges matter more than the process that first constructed them.
Store edges with the workflow. When a predecessor succeeds, atomically record the result and release successors whose prerequisites are satisfied. If two predecessor completions race, successor readiness must be calculated from durable, unique completion records. Otherwise the join can schedule twice.
The software-team workflow in Agent Queue Lab provides a concrete example. A planner creates two parallel branches: one generates the implementation, while the other generates tests. The reviewer becomes eligible only after both branches have completed. Publication requires an explicit human approval.
Because the task graph and completed artifacts are persisted, an interrupted worker does not require the entire workflow to restart. Recovery resumes from the remaining unfinished work.
Treat branch results as versioned inputs. A reviewer that asks for another implementation pass should not silently overwrite the accepted research result. A new task generation or revision should reference the precise artifacts it is meant to consume.
Not every graph is static. Agents may spawn sub-tasks. Gate that ability with maximum depth, fan-out, budget and permissions, and make spawn requests idempotent. Persist the new child rows and dependency edges in a transaction before telling the parent that expansion succeeded. Without a durable spawn record, a retried planner can create the same work repeatedly.
One useful pattern is a parent task that completes only after durable child creation, followed by a separate join task. Parent attempts never wait inside a worker process for every child to finish. This separates scarce execution slots from potentially long workflow lifetimes.
Record nondeterministic agent decisions at the right boundary
An LLM call is not a deterministic pure function. Different outputs can arise from retries, model configuration changes or external context. A recovery design must distinguish recomputing a failed step from replaying orchestration history.
Temporal's event history records workflow progress so a restarted worker can reconstruct state. Its workflow definition guidance requires deterministic orchestration, with failure-prone external operations delegated to Activities. Temporal Activities support retries and heartbeats, but tool side effects still require their own correctness controls.
For an agent system, that means recording the model, configuration, input artifact references, prompt version, tool permissions, structured response and usage metadata for each completed step. Store sensitive prompts and outputs only as permitted by the system's data policy. Replay should load a completed result rather than quietly asking the model again and pretending the same decision occurred.
A graph-based framework may use a different persistence model. LangGraph's documented approach describes checkpointing around node boundaries and resumable human interrupts. The trade-off is checkpoint granularity: if a node performs several remote side effects before its checkpoint commits, those operations may need independent idempotency protection.
Do not confuse replayability with repeatability. A recorded workflow can reconstruct decisions that have already committed. A failed, unrecorded attempt may still need fresh inference and may produce different results. Design downstream validation around that uncertainty.
Design cancellation and approval as durable transitions
An agent may be in the middle of generating text when a user cancels the workflow. Mark the workflow cancelled or cancellation-requested in durable state, block downstream scheduling and notify active workers. A worker should check cancellation before each tool operation and when it heartbeats.
A cancellation signal cannot retract an already accepted remote side effect. Record whether compensation is possible, authorized and safe. A compensating action is a new effect with its own idempotency key and error handling, not a magical rollback.
For approval steps, persist the exact proposed operation, its input hash, the approver's scope, an expiry and the final decision. When approval arrives, revalidate that the proposal is still current. Do not let an old approval authorize a later, materially different agent plan.
These transitions also support governance: a task that can read source code should not automatically inherit privileges to deploy production changes. An executor's tool permissions should derive from the task contract and current authorization, not from whatever the model happens to request.
Add fairness, quotas and resource boundaries
A failure-recovering queue can still become unusable when one workflow consumes every worker slot. Partition or schedule by tenant, priority and capability. Establish per-tenant concurrency limits, provider rate budgets and a separate lane for recovery or high-priority control tasks.
Do not treat priority alone as fairness. Strict priority may starve older low-priority work. Aging, weighted scheduling or explicit quotas can create a better policy, but their values must be tested against real traffic rather than copied from an unrelated benchmark.
Keep individual task execution bounded and distinguish CPU workers, browser workers and high-cost model workers where their resource profiles differ. Concurrency quotas should be evaluated at claim time and released on successful completion, failure or lease recovery. Use durable accounting so that crashing workers do not hold capacity forever.
A queue dashboard should show both system-wide and tenant-specific backlog. High throughput is not a sufficient success metric if some tenants wait indefinitely or retries dominate the workload.
Test failures where transactions meet the outside world
A happy-path test proves only that the queue works when no recovery is required. Build fault injection into the worker harness. Kill a worker after it claims a task, after it calls a tool but before it records the response, and after it records the response but before the acknowledgement. Pause it beyond its lease and allow a second worker to claim the task.
For every scenario, assert durable invariants: one canonical accepted result per logical task; a stale generation cannot commit; confirmed external effects are not blindly repeated; unresolved effects are surfaced; dependency joins release a successor once; and exhausted retry or execution budgets result in a defined terminal or waiting state.
Measure queue wait time, attempt duration, retries by error class, expired leases, stale completion rejections, uncertain effects, reconciliation outcomes, time spent awaiting approval, and total cost per successfully completed workflow. Alerts should target a growing age of oldest ready work or unresolved uncertainty, not merely a large queue depth.
The Agent Queue Lab companion project makes these failure and recovery mechanisms observable through a dashboard that exposes task states, execution attempts, external effects and fault-injection controls.
The selected workflow demonstrates successful recovery: the developer task completed on its second execution attempt, with generation 2 becoming the authoritative result.
A useful operational runbook explains how to inspect a task, recover an expired claim, reconcile an external effect, replay a quarantined item and stop a repeatedly failing workflow. Audit every manual intervention; changing a task state directly in the database without preserving provenance defeats the reliability model.
Choose a queue or workflow engine deliberately
A PostgreSQL-backed scheduler can be enough when tasks are short, dependency graphs are simple, the team already operates PostgreSQL and careful state-machine design is acceptable. The PostgreSQL locking documentation gives an efficient atomic-claim building block, but developers still own reaping, backoff, dead-letter handling, graph transitions and operational tools.
A managed message queue such as Amazon SQS moves message delivery infrastructure outside the application. The application still needs its own workflow state, agent artifacts and effect ledger. A message being acknowledged does not prove that a multi-agent goal completed correctly.
A durable workflow engine such as Temporal becomes attractive when workflows live a long time, contain many dependent steps, require approvals or need audited replay. That reduces custom orchestration logic, but introduces runtime operation, deployment constraints and deterministic workflow programming rules. It does not make non-idempotent tools safe by default.
The decision is less about which framework supports the largest number of agents and more about where the authoritative history resides. If the system cannot explain which attempt owned a task, which decisions were durably recorded and whether an external action already occurred, adding more agents will increase uncertainty rather than resilience.
A practical implementation sequence
Start with durable task IDs, an explicit state machine and atomic claims. Next add finite leases, generation fencing and bounded retry classification. Then introduce the effect ledger and ambiguity reconciliation before allowing agents to perform externally visible mutations. Only after those invariants hold should the system add dynamic sub-tasks, human approvals, tenant scheduling and high concurrency.
Design the system so that a crash never requires guessing from a worker's missing process. The durable record should show what work was intended, what work was confirmed, who held the last valid claim and what remains uncertain. Recovery follows from those facts—not from the hope that the same agent will run the same way twice.
From concept to implementation: Agent Queue Lab
Understanding failure modes theoretically is useful. Being able to reproduce them makes the architectural trade-offs much clearer.
To accompany this article, I built Agent Queue Lab, an open-source laboratory for failure-resilient multi-agent orchestration using Python, PostgreSQL and Docker Compose.
Rather than introducing another general-purpose agent framework, the project focuses on the mechanics that make execution recoverable: durable task state, atomic claims, lease renewal, generation fencing, dependency management and external effect reconciliation.
It includes two execution profiles — naive and durable — allowing the same failure scenario to be executed against both implementations and their outcomes to be compared.
Experiments you can reproduce
- Kill a worker after it claims a task and observe lease recovery.
- Pause a worker beyond its lease duration and verify that stale completion is rejected.
- Crash a worker after a successful external mutation and compare duplicate creation across execution profiles.
- Simulate an ambiguous remote outcome and observe when human intervention becomes necessary.
- Restart the application or interrupt PostgreSQL and verify that completed progress is preserved.
The initial release passed 53 local acceptance checks, covering unit tests, PostgreSQL integration, resilience scenarios, comparative experiments and actual service interruptions. The acceptance suite also passed on GitHub Actions.
Run the laboratory
The default configuration requires Docker Compose but no external AI services or API keys.
git clone https://github.com/ricjcosme/agent-queue-lab.git
cd agent-queue-lab
cp .env.example .env
docker compose up --build -d --wait
Open the dashboard at http://localhost:8080, or run the comparative failure experiments:
make compare
The project is intentionally educational rather than production-ready. Its purpose is to make failure mechanisms observable, reproducible and independently testable.
Source code, documentation and experiments:
github.com/ricjcosme/agent-queue-lab
Initial release: Agent Queue Lab v0.1.0