A 202 Accepted Response Is Not a Completed Job: Building Durable Background Workflows in FastAPI
In backend development, there are operations that should not force a user to wait until everything has finished. Processing large Excel files, generating reports, importing production records, synchronizing data, or communicating with hundreds of devices are some common examples.
We often solve this by moving the work into the background and immediately returning a response to the client.
But there is a difference between running something in the background and building a reliable background workflow.
A request can be accepted, a background function can start running, and everything can appear to work perfectly until the application restarts, a worker crashes, or a message is never processed.
That is where the design of background processing becomes more important than simply making an API asynchronous.
1. Returning a Response Does Not Mean the Work Is Finished
Imagine a production management application where a user uploads an Excel file containing thousands of records.
The API receives the file, validates it and starts processing the records. Instead of making the user wait several minutes, the application immediately returns:
HTTP/1.1 202 Accepted
This is a reasonable approach because the request has been accepted for processing, but the operation is not yet complete.
The problem starts when the application treats accepting the request as equivalent to successfully completing the operation.
For example, a developer might implement this using FastAPI's BackgroundTasks:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
@app.post("/imports")
async def create_import(
background_tasks: BackgroundTasks,
):
background_tasks.add_task(process_import)
return {
"message": "Import started"
}
For small, best-effort tasks, this can be perfectly reasonable. FastAPI provides background tasks that run after the response is returned, and its documentation recommends considering larger external task systems for heavier work that needs to run independently or across multiple processes and servers.
However, this implementation does not provide a durable job record or a recovery mechanism if the process terminates during execution.
If the operation is business-critical, I would not rely on an in-process background task alone.
2. Treat Long-Running Operations as Resources
Instead of treating an import as a function that happens to run in the background, I would treat it as a resource with its own lifecycle.
For example, when a user submits an import request, the application could create a job record:
{
"job_id": "7b22d840-8e53-4f2a-a112-10f12d99a123",
"job_type": "EXCEL_IMPORT",
"status": "QUEUED",
"progress": 0,
"total_records": 2500,
"processed_records": 0,
"created_at": "2026-11-27T00:30:00Z"
}
The API would return something like this:
HTTP/1.1 202 Accepted
Location: /jobs/7b22d840-8e53-4f2a-a112-10f12d99a123
{
"job_id": "7b22d840-8e53-4f2a-a112-10f12d99a123",
"status": "QUEUED",
"status_url": "/jobs/7b22d840-8e53-4f2a-a112-10f12d99a123"
}
Now the client has a reference to the actual operation rather than simply receiving a message that processing has started.
The job can be monitored, retried according to policy, investigated when it fails, and eventually marked as completed.
A possible database structure could look like this:
Field | Purpose |
|---|
id
| Unique job identifier |
job_type
| Type of operation |
status
| Current execution state |
total_records
| Total items to process |
processed_records
| Number of processed items |
successful_records
| Number of successful items |
failed_records
| Number of failed items |
created_by
| User who submitted the job |
created_at
| Submission time |
started_at
| Execution start time |
completed_at
| Completion time |
error_summary
| Failure information |
The job record becomes the source of truth for the operation's lifecycle.
3. Persist the Job Before Dispatching It
This is where a background workflow can become more complicated than it initially appears.
Suppose the application performs these two operations:
Saves a job record in the database.
Publishes a message to RabbitMQ or Redis for a worker to process.
Both operations are necessary, but they do not automatically happen atomically.
Consider this sequence:
API
|
| Save job record
v
Database
|
| Publish message
v
Message broker
What happens if the database transaction commits successfully but the application crashes before publishing the message?
The job exists in the database, but nobody may process it.
Now consider the opposite approach. The application publishes the message first, but the database transaction fails. A worker may receive a message for a job that was never successfully persisted.
This is a dual-write problem.
One approach I prefer for important workflows is the transactional outbox pattern.
Instead of saving the job and publishing the message directly as two independent operations, the application writes both the job record and an outbox event within the same database transaction.
Database Transaction
+----------------------+
| |
| Create Job Record |
| |
| Create Outbox Event |
| |
+----------+-----------+
|
v
Transaction
Commit
|
v
Outbox Dispatcher
|
v
Message Broker
|
v
Worker
If the transaction commits, both the job record and the outbox event exist.
A separate dispatcher reads pending outbox events and publishes them to the message broker. After successful publishing, it marks the event as dispatched.
The dispatcher may publish the same event more than once if it crashes after publishing but before recording the dispatch status. This is expected in a reliable delivery design, so the worker must be prepared to handle duplicates.
The transactional outbox does not magically guarantee exactly-once delivery. It makes the database-to-message dispatch process recoverable without relying on two independent operations succeeding together.
4. Build Workers That Can Recover
Once a job is placed in a queue, the worker becomes responsible for executing it.
I would avoid assuming that a worker will always finish its operation in one attempt.
A worker might crash because of:
A temporary database connection failure.
A deployment or process restart.
A malformed record inside the imported file.
A timeout from an external API.
Memory exhaustion during a large operation.
For this reason, job processing should be designed around recoverable execution.
A basic lifecycle could look like this:
QUEUED
|
v
RUNNING
|
+---------> SUCCEEDED
|
+---------> FAILED
|
+---------> RETRY_WAIT
|
v
QUEUED
A worker should not simply mark a job as RUNNING and assume it will eventually finish.
In a production system, I would consider using a lease or heartbeat mechanism. A worker claims the job, records that it is processing it, and periodically updates its lease while executing.
If the worker crashes and the lease expires, another worker or recovery process can identify the abandoned job and decide whether it should be retried.
However, a lease alone is not enough to prevent duplicate execution. A worker that loses its lease might still be running, especially if it is experiencing network problems. If multiple workers can act on the same resource, fencing tokens or other concurrency controls may be necessary.
The retry policy should also distinguish between temporary and permanent failures.
For example:
Temporary database failure: retry.
External service timeout: retry according to policy.
Invalid input record: record the failure and continue if partial processing is supported.
Invalid file structure: fail the job.
Repeated failure: stop retrying and mark the job for investigation.
Retries should have limits and backoff rather than running indefinitely.
5. Design a Job Status API That Is Actually Useful
Once the operation has a lifecycle, the client needs a way to inspect it.
I would keep the API simple:
POST /imports
GET /jobs/{job_id}
GET /jobs/{job_id}/errors
POST /jobs/{job_id}/cancel
The job status endpoint could return:
{
"job_id": "7b22d840-8e53-4f2a-a112-10f12d99a123",
"status": "RUNNING",
"progress": 64,
"total_records": 2500,
"processed_records": 1600,
"successful_records": 1572,
"failed_records": 28,
"started_at": "2026-11-27T00:35:00Z"
}
The progress value should be derived from actual processing data rather than arbitrarily incremented.
For example, if 1,600 records have been processed out of 2,500, the progress is 64%.
A simple FastAPI endpoint could look like this:
from fastapi import APIRouter, status
from pydantic import BaseModel
from uuid import UUID
router = APIRouter()
class JobAccepted(BaseModel):
job_id: UUID
status: str
status_url: str
@router.post(
"/imports",
status_code=status.HTTP_202_ACCEPTED,
response_model=JobAccepted,
)
async def submit_import(payload: ImportRequest):
job = await import_service.submit(payload)
return JobAccepted(
job_id=job.id,
status="QUEUED",
status_url=f"/jobs/{job.id}",
)
The import_service.submit() method is assumed to persist the job and its outbox event transactionally. The endpoint itself does not provide that guarantee.
For the client, polling the status endpoint is a simple starting point. If the application needs real-time updates, WebSockets or Server-Sent Events can be introduced later.
I would not add real-time communication simply because a job runs in the background. A status endpoint is often sufficient and much easier to maintain.
Cancellation also needs careful handling. A cancellation request does not mean the worker instantly stops. The worker may need to check for cancellation between processing steps and cooperate with the cancellation mechanism.
6. What I Would Consider Before Putting It Into Production
A background workflow is not complete simply because a worker can process a message.
Before deploying a critical job-processing system, I would consider the following:
Durability: Can the job survive application restarts?
Idempotency: Can the worker safely process the same job more than once?
Concurrency: Can multiple workers claim the same job incorrectly?
Retries: Are temporary failures handled without retrying forever?
Recovery: Can abandoned jobs be detected and recovered?
Observability: Can developers identify stuck, failed or slow jobs?
Authorization: Can users access only the jobs and results they are permitted to see?
Partial failures: Can the application report which records failed without losing the successful ones?
Resource limits: Can a large import overwhelm workers, memory or the database?
Cancellation: Can the application stop work safely where cancellation is supported?
I would also monitor queue depth, job execution time, retry counts, worker availability, failure rates and the age of the oldest pending job.
A job that remains in QUEUED for 30 minutes may be just as important to investigate as one that fails immediately.
Conclusion
Background processing is often introduced to improve API responsiveness, but responsiveness is only one part of the problem.
The moment an operation becomes important enough that users expect it to finish even after a restart, it deserves a proper lifecycle, persistent state, reliable dispatch, recoverable execution and meaningful observability.
FastAPI's BackgroundTasks is useful for small, best-effort work. For durable business workflows, I would separate the API, job persistence, message dispatch and worker execution.
Returning 202 Accepted is the beginning of the workflow, not the guarantee that the workflow will succeed.
And that distinction is what separates a background function from a reliable background processing system.
Join the conversation! Your thoughts help the community grow.