Reliable agent behavior depends on the system around the model.
An agent searches a document, looks up an order, and starts drafting a response. Then the worker restarts. Should the system continue, repeat the lookup, or start the entire conversation again?
A queue moves that question outside your HTTP request. It does not answer it.
This guide develops a practical design for a support agent using FastAPI, Redis, and Celery, with PostgreSQL retaining durable application state. The running example is hypothetical. The configuration illustrates the boundaries; it is not a complete deployable application or a report of production testing.
The goal is straightforward: accepted work should have an owner, a recovery path, and a recorded outcome—even when infrastructure behaves badly.
Give each component a clear job
Consider a support agent that can search approved documentation, inspect an authorized order, and draft an answer. The model decides whether it needs another lookup. That makes it an agent; a fixed sequence of model calls would be a workflow. Anthropic’s architecture guide makes this distinction useful without requiring a particular framework.
Keep the first version read-only. It can recommend a refund, but issuing one belongs behind a separate, explicitly authorized operation.
Split the backend into four responsibilities:
- FastAPI: authenticate, validate, accept runs, and expose status.
- Redis: carry Celery task messages between producers and workers.
- Celery: execute work outside the API process and coordinate configured retries.
- PostgreSQL: retain run ownership, checkpoints, outputs, and action records.
Yes, there is a database in an article about FastAPI, Redis, and Celery. Recovery needs durable application state. A queue message alone cannot explain which customer owns a run or which tool action already happened.

The database records intent and progress; Redis carries work to Celery workers. Model and tool calls remain inside application-controlled limits.
Accept the run before doing the work
A useful interface is POST /agent-runs, followed by GET /agent-runs/{run_id}. After recording the request durably, return 202 Accepted with the run ID and status URL. Accepted means the system has taken responsibility for processing it; it does not promise successful completion.
Require a client-generated idempotency key for submissions. Scope its uniqueness to the authenticated tenant and operation, and store a hash of the normalized request. A repeated key with the same payload returns the existing run. The same key with different input should produce a conflict.
Derive tenant identity from authentication. Do not trust a tenant ID supplied in the request body. Apply the same ownership check when returning status or results.
An async def endpoint helps with concurrent I/O; it does not preserve a running function through a process restart. FastAPI’s background-task guidance points to tools such as Celery when work needs separate processes or servers. Small in-process jobs can still be perfectly reasonable.
Close the gap between the database and the queue
The obvious implementation saves a run, then calls run_agent.delay(run_id).
Now imagine the API process disappears between those two statements. The database contains an accepted run that no worker will receive.
Use a transactional outbox: insert the run and an outbox event in the same database transaction. A dispatcher publishes committed events to Celery, then marks them dispatched. The API can return once that transaction commits.
The dispatcher should retry publication failures. If it crashes after publishing but before marking the event, it may publish again. That is expected. AWS’s outbox guidance explicitly calls out duplicate handling.
Give each event a stable identifier, but do not mistake a custom Celery task ID for application-level deduplication. The worker must still handle repeated delivery. Add reconciliation for accepted runs that remain unclaimed beyond an operational threshold; even a dispatched message can be lost in a broker failure.
Make execution a recorded state machine
Store business states such as accepted, running, retry_wait, succeeded, failed, and cancelled. These describe the run independently of Celery’s task states.
Before doing work, atomically claim the run using a database lease. A second delivery should exit if another worker holds a valid claim. Renew the lease while executing, and attach a fencing token or version to writes so a stale worker cannot overwrite a newer attempt.
A lease needs a recovery path. Reconcile expired claims, stop jobs past their absolute deadline, and record a terminal outcome when recovery is exhausted. Otherwise, one killed worker leaves a run permanently “running.”
Persist the next step, model-visible tool history, completed tool results, cumulative usage, and relevant model/prompt versions. Resume from the last completed boundary. A checkpoint cannot recover an external action whose outcome was never recorded; that requires separate handling.
Configure Celery around those guarantees
The following is a configuration example, not a complete agent application. It assumes replay-safe tasks, durable state, and the recovery rules above. It targets Celery’s documented 5.6 configuration surface and a Linux prefork worker.
# celery_app.py
import os
from celery import Celery
app = Celery(
"agent_service",
broker=os.environ["CELERY_BROKER_URL"],
)
app.conf.update(
task_serializer="json",
accept_content=["json"],
task_ignore_result=True, # Results live in the application database.
task_default_queue="agents",
worker_prefetch_multiplier=1,
task_acks_late=True,
task_soft_time_limit=180,
task_time_limit=210,
broker_transport_options={"visibility_timeout": 300},
visibility_timeout=300,
broker_connection_retry_on_startup=True,
)
A Redis broker URL could be redis://localhost:6379/0 in local development. Keep deployed credentials in environment configuration.
Late acknowledgement changes when a message is acknowledged; it does not make execution exactly once. A terminated child process can still be acknowledged. Consider task_reject_on_worker_lost only after understanding its possible requeue loops and implementing recovery limits. See the Celery configuration reference.
Here, 300 seconds exceeds the example’s hard task limit. Celery’s Redis transport documentation explains visibility-timeout redelivery. Coordinate timeout settings across applications sharing the broker. If you add a Redis result backend, configure its visibility option consistently too. Larger values delay recovery after a crash; they are not a free reliability upgrade.
Retry the failure that can recover
Retry a temporary model-service outage or a rate-limit response when policy allows. Stop on invalid credentials, forbidden tool access, malformed requests, or exhausted budgets. Invalid model output may deserve a small, separate repair allowance—not an unlimited retry loop.
For explicitly classified transient failures, a task decorator can supply bounded backoff:
# Decorator options for your implemented, replay-safe task:
# autoretry_for=(TransientProviderError,)
# retry_backoff=2
# retry_backoff_max=30
# retry_jitter=True
# max_retries=3
TransientProviderError is an application-defined exception, not a Celery class. Its adapter should classify provider errors and respect retry hints where available. Celery documents automatic retry and backoff, but your code must record the final business outcome when attempts are exhausted.
Avoid autoretry_for=(Exception,). A programming error does not become temporary because it waited thirty seconds. Also avoid stacking several provider SDK retries inside several whole-task retries without counting the combined calls.
Put a budget around the agent loop
For this example, choose a two-minute absolute deadline, six model decisions, and four tool calls. These are illustrative policy limits, not measured recommendations.
Before each step, check the persisted deadline, cancellation flag, cumulative usage, and ownership claim. Reserve budget before issuing work. Recheck after the response before authorizing another action.
Carry those counters across task retries. Restarting a Python loop must not reset the customer’s spending allowance. Cap model output and tool response sizes, and bound network calls by the remaining time. A timeout on each request alone does not necessarily enforce an end-to-end deadline.
Use Celery’s process limits as a final boundary, not the primary timer. Plan for abrupt termination without cleanup. When costs matter, reserve a conservative upper bound before a model call and reconcile actual usage afterward; a disconnected response may leave the billed amount uncertain.
Make tool execution safe to repeat
A model can choose an action. Application code must validate its tool name and arguments, enforce tenant permissions, and decide whether execution is allowed.
Use narrow interfaces such as lookup_order(order_id) instead of arbitrary SQL or shell access. Treat retrieved documents as data, even when they contain instructions telling the agent to ignore its rules.
Record each planned action durably before execution, assigning a stable action ID. Derive an external idempotency key from the run and that action ID, then reuse it on recovery. Never regenerate an action identifier merely because a task retried.
If a write service offers neither idempotency nor a way to reconcile outcomes, a timeout after submission leaves uncertainty: the operation may already have happened. Pause for reconciliation or review instead of blindly repeating it. Start with read-only tools precisely because this failure is easier to contain.
Let the UI reconnect without losing the answer
Polling is a sensible first interface. SSE can later provide progress while a separate status endpoint remains authoritative.
Redis Pub/Sub has at-most-once delivery. A disconnected subscriber can miss a notification. Persist final output and meaningful progress independently, and let a reconnecting client retrieve them. If replayable events are needed, design a retained event log with sequence IDs.
Cancellation should also be persistent and cooperative. Check it before the next model or tool call. Closing the browser does not cancel a job, and recording cancellation cannot undo an external action already submitted.
Operate the queue as part of the product
Route agent work separately from short transactional jobs. Celery supports named queues and dedicated consumers; prefetch tuning should follow task duration and measured load, as described in its optimization guide.
Set tenant admission limits and provider-wide concurrency controls. Adding workers can increase rate-limit failures instead of increasing useful throughput.
Redis durability is a deployment decision. Choose persistence, backups, and a recovery objective deliberately. Its persistence and replication documentation explain why a replica or an enabled persistence option is not a universal zero-loss guarantee.
Track queue age, run duration, retries, expired leases, budget stops, tool failures, and completion quality. Correlate logs by run, task, attempt, and action IDs. Celery’s monitoring tools help with worker behavior; application records explain what happened to the user’s request.
Test recovery before expanding autonomy
Submit the same request twice. Interrupt a worker after a checkpoint. Simulate a provider timeout. Replay an outbox event. Disconnect the UI and reconnect. Try an unauthorized tool argument. Verify each run reaches an explainable outcome without repeating protected actions or resetting its budget.
Begin with one useful, read-only agent and a narrow set of real evaluation questions. Expand its permissions only after you can explain how the system behaves when a step fails halfway through.
A convincing answer is valuable. A backend that can account for how it produced that answer is what makes the agent dependable.
