Celery 작업자를 FastAPI 앱에 연결
Redis 브로커로 Celery를 구성하고 작업을 정의하며, 결과 백엔드를 사용해 엔드포인트에서 작업을 전달합니다.
Celery 작업자를 FastAPI 앱에 연결은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Celery in a FastAPI App?
FastAPI request handlers must return quickly. Work like sending emails, generating reports, resizing images, or calling slow third-party APIs can take seconds, blocking your worker process and hurting throughput.
Celery is a distributed task queue. You push a job onto a queue, and a separate pool of worker processes runs it outside the request/response cycle.
- Broker — the message transport that holds queued jobs (we use Redis).
- Worker — long-running process that pulls and executes tasks.
- Result backend — optional store for return values and task state.
The endpoint stays fast and just answers: "accepted, here is your job id."
Installing the Pieces
Install Celery with the Redis extra, plus a Redis server reachable from both your API and your workers.
celery[redis]pulls in Celery and theredisclient.- Run Redis locally with Docker:
docker run -p 6379:6379 redis.
Both the FastAPI process and the worker process import the same Celery application object, so they must share the same codebase and broker URL.
# requirements.txt
fastapi
uvicorn[standard]
celery[redis]
redis
# install
# pip install -r requirements.txt
# run redis: docker run -p 6379:6379 redis:7Creating the Celery App
Define a single Celery application instance in its own module (commonly worker.py or celery_app.py). It needs a name, a broker URL, and a result backend URL.
broker— where tasks are enqueued (Redis DB 0).backend— where results/state are stored (Redis DB 1, kept separate for clarity).
The first argument ("worker") becomes the default prefix for task names.
# celery_app.py
from celery import Celery
celery_app = Celery(
"worker",
broker="redis://localhost:6379/0",
backend="redis://localhost:6379/1",
)
celery_app.conf.update(
task_serializer="json",
result_serializer="json",
accept_content=["json"],
timezone="UTC",
enable_utc=True,
)Defining Your First Task
A task is just a function decorated with @celery_app.task. When called normally it runs inline; when called with .delay() or .apply_async() it is serialized and pushed to the broker.
- Arguments must be JSON-serializable (use ids and primitives, not ORM objects).
- Give the task an explicit
nameso renaming the function later does not break queued messages.
# tasks.py
import time
from celery_app import celery_app
@celery_app.task(name="tasks.send_report")
def send_report(user_id: int, email: str) -> dict:
# simulate slow work
time.sleep(5)
return {"user_id": user_id, "sent_to": email, "status": "done"}Dispatching a Job from an Endpoint
Inside a FastAPI route, call .delay(...) to enqueue the task. This returns an AsyncResult immediately — it does not wait for the work to finish.
Respond with the task.id and HTTP 202 Accepted, signalling that the request was accepted for processing but is not yet complete.
Never .get() the result inside the request handler — that blocks the event loop until the job finishes, defeating the entire purpose.
# main.py
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
from tasks import send_report
app = FastAPI()
class ReportRequest(BaseModel):
user_id: int
email: EmailStr
@app.post("/reports", status_code=202)
def create_report(req: ReportRequest):
task = send_report.delay(req.user_id, req.email)
return {"task_id": task.id, "status": "queued"}Running the Worker
The FastAPI server only produces messages. You must start a separate worker process to consume and execute them.
celery_appafter-Apoints to the module and instance.--loglevel=infoshows each task as it is received and succeeds.--concurrency=4controls how many tasks run in parallel.
On Windows or macOS forking issues, add --pool=solo for development.
# terminal 1: API
uvicorn main:app --reload
# terminal 2: worker
celery -A celery_app.celery_app worker --loglevel=info --concurrency=4Polling Task Status with the Result Backend
Because we configured a result backend, we can look up a job's state and return value later using its id.
Build an AsyncResult from the id, bound to the same Celery app. Useful states:
PENDING— unknown/not started.STARTED— picked up by a worker.SUCCESS— finished;.resultholds the return value.FAILURE— raised an exception.
Clients poll this status endpoint until the task is ready.
# main.py (continued)
from celery.result import AsyncResult
from celery_app import celery_app
@app.get("/reports/{task_id}")
def get_status(task_id: str):
result = AsyncResult(task_id, app=celery_app)
payload = {"task_id": task_id, "state": result.state}
if result.successful():
payload["result"] = result.result
return payloadapply_async: Countdown, ETA and Retries
.delay(*args) is shorthand for .apply_async(args=...). The longer form unlocks scheduling and routing options:
countdown=10— wait 10 seconds before executing.eta=datetime(...)— run at a specific time.queue="emails"— route to a named queue.retry=Truewithretry_policy— retry on broker errors.
from tasks import send_report
send_report.apply_async(
args=[42, "user@example.com"],
countdown=10,
queue="reports",
)Retrying Failed Tasks
Transient failures (a flaky API, a timeout) should be retried, not lost. Bind the task with bind=True so self is available, then call self.retry().
max_retriescaps the attempts.default_retry_delayorcountdownbacks off between tries.autoretry_forcan retry automatically for specific exceptions.
After exhausting retries, the task ends in the FAILURE state.
from celery_app import celery_app
@celery_app.task(
bind=True,
name="tasks.charge_card",
max_retries=3,
autoretry_for=(ConnectionError,),
retry_backoff=True,
)
def charge_card(self, order_id: int):
try:
process_payment(order_id)
except ConnectionError as exc:
raise self.retry(exc=exc, countdown=5)FastAPI BackgroundTasks vs. Celery
FastAPI ships a lightweight BackgroundTasks helper. It runs work in the same process, after the response is sent. Know when each fits:
- BackgroundTasks — quick, fire-and-forget jobs (send one email, write a log). No retries, no result tracking, lost if the process restarts.
- Celery — heavy, long, retryable, or schedulable jobs that need durability, horizontal scaling across machines, and result/state visibility.
Rule of thumb: if losing the job on a crash is unacceptable, or the work is CPU/time heavy, reach for Celery.
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_log(message: str):
with open("audit.log", "a") as f:
f.write(message + "\n")
@app.post("/click")
def click(bt: BackgroundTasks):
bt.add_task(write_log, "user clicked")
return {"ok": True}A Standalone Queue Simulation
You cannot run a real broker inside an online judge, but the producer/consumer pattern behind Celery is simple. This pure-Python example mirrors the idea: jobs are enqueued, a worker drains the queue, and results are collected by id — exactly the flow Celery automates over Redis.
from collections import deque
queue = deque()
results = {}
def enqueue(task_id, user_id, email):
queue.append((task_id, user_id, email))
results[task_id] = "PENDING"
def worker():
while queue:
task_id, user_id, email = queue.popleft()
results[task_id] = {
"user_id": user_id,
"sent_to": email,
"status": "SUCCESS",
}
enqueue("t1", 42, "a@x.com")
enqueue("t2", 7, "b@x.com")
worker()
for tid in ("t1", "t2"):
print(tid, results[tid])Quick Check
Test your understanding of how a FastAPI endpoint should hand off work to Celery.
Recap
You wired Celery into a FastAPI app end to end:
- Created one
Celeryinstance with a Redis broker and a result backend. - Defined JSON-serializable tasks with
@celery_app.taskand explicit names. - Dispatched jobs from endpoints with
.delay(), returning a task id and 202 Accepted instead of blocking. - Ran a separate
celery ... workerprocess to consume the queue. - Polled job state and results via
AsyncResult. - Used
apply_asyncfor countdowns/queues andself.retry()for resilient retries. - Chose between FastAPI
BackgroundTasks(light, in-process) and Celery (durable, scalable, retryable).
The golden rule: endpoints enqueue and return fast; workers do the heavy lifting.
자주 묻는 질문
“Celery 작업자를 FastAPI 앱에 연결” 강의는 무료인가요?
네 — “Celery 작업자를 FastAPI 앱에 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“Celery 작업자를 FastAPI 앱에 연결”에서 뭘 배우나요?
Redis 브로커로 Celery를 구성하고 작업을 정의하며, 결과 백엔드를 사용해 엔드포인트에서 작업을 전달합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Celery 작업자를 FastAPI 앱에 연결” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- BackgroundTasks를 활용한 경량 오프로딩
- Celery 작업자를 FastAPI 앱에 연결
- 재시도, 멱등성 및 배달 불가 메시지 처리
- Celery Beat를 활용한 예약 및 주기적 작업