Provide a FastAPI + Celery boilerplate using RabbitMQ as the broker. Implement progress tracking where the API returns a task_id, the client polls a status endpoint, and the Celery task updates its state to Redis so the client can show a progress bar.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm preparing a minimal working example with RabbitMQ as Celery broker and Redis as result backend to track task progress using update_state. The FastAPI app will offer a POST /tasks to start a task and GET /tasks/{task_id}/status to report progress as JSON. Celery instance and tasks live in dedicated modules, with instructions on running the worker and app.
Below is a minimal but complete boilerplate showing how to wire up FastAPI + Celery using RabbitMQ as the broker, Redis as the result backend, and a simple progress‑tracking pattern. The FastAPI API exposes two endpoints: one to enqueue a long‑running task (returns a task_id) and another to check progress (pollable by a client for a progress bar).
import time
from .celery_app import celery_app
@celery_app.task(bind=True)
def long_running_task(self, total=100):
"""
Dummy long-running task that sleeps and updates its state.
"""
for i in range(total):
# Simulate work
time.sleep(0.05)
# Update state to show progress
self.update_state(
state="PROGRESS",
meta={
"current": i + 1,
"total": total,
"status": f"Processing {i + 1} of {total}"
}
)
# Return a final result (visible in backend)
return {"current": total, "total": total, "status": "Task completed!"}
FastAPI Application (app/main.py)
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from celery.result import AsyncResult
from .celery_app import celery_app
from .tasks import long_running_task
app = FastAPI()
@app.post("/tasks")
def run_task(total: int = 100):
"""
Enqueues the long_running_task and returns the Celery task id.
"""
task = long_running_task.delay(total)
return {"task_id": task.id}
@app.get("/tasks/{task_id}")
def get_status(task_id: str):
"""
Returns the task state and progress meta (if any).
"""
result: AsyncResult = celery_app.AsyncResult(task_id)
response = {
"task_id": task_id,
"state": result.state,
"meta": result.info if result.info else {}
}
# Optionally derive a percentage if meta has 'current'/'total'
if isinstance(result.info, dict):
current = result.info.get("current", 0)
total = result.info.get("total", 1)
response["progress"] = round((current / total) * 100, 2) if total else 0
else:
response["progress"] = 0
return JSONResponse(response)
Running Everything
Start RabbitMQ & Redis
Either use the docker-compose.yml above (docker-compose up) or make sure RabbitMQ is available on localhost:5672 and Redis on localhost:6379.
Start the Celery worker
From the project root:
bash
celery -A app.celery_app.celery_app worker -l info
(Notice we pass the celery_app object inside app/celery_app.py.)
Start FastAPI
bash
uvicorn app.main:app --reload
Use the API
Enqueue a task: POST /tasks with JSON body like {"total": 200} or query param ?total=200. Response: {"task_id": "..."}
Poll task status: GET /tasks/{task_id} returns state, meta, and progress (computed from current/total in meta). States you’ll see:
PENDING: task is waiting to be run
STARTED: task accepted by worker (if task_track_started=True)
PROGRESS: custom state we set with update_state
SUCCESS: task finished (result in meta)
FAILURE: task failed
Client Progress Bar Example
A front-end (or CLI) can poll GET /tasks/{task_id} every few seconds. Use the progress field to render a progress bar, e.g.:
When state becomes SUCCESS, your UI can stop polling and read the final "meta" as the result.
This setup uses RabbitMQ purely as the Celery broker (queue transport) and Redis as the result backend (where Celery stores states and metadata). The update_state calls write into Redis, allowing the client to poll progress via the FastAPI endpoint.