백그라운드 작업과 작업 큐
FastAPI 백그라운드 작업과 Celery 같은 분산 작업 큐를 사용해 요청 처리기에서 느린 작업을 분리하는 방법을 배웁니다.
백그라운드 작업과 작업 큐은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Offload Work?
Some work, like sending email, generating reports, or processing images, is too slow to do inside a request.
Making the user wait hurts latency. Instead, respond fast and do the heavy work in the background.
FastAPI BackgroundTasks
FastAPI ships a lightweight BackgroundTasks tool for work that should run after the response is sent.
from fastapi import BackgroundTasks
def write_log(msg: str):
with open("log.txt", "a") as f:
f.write(msg)
@app.post("/signup")
def signup(bg: BackgroundTasks):
bg.add_task(write_log, "new user")
return {"ok": True}Limits of BackgroundTasks
BackgroundTasks runs in the same process. If the server restarts, the work is lost, and it cannot scale across machines.
For durable, distributed work you need a real job queue.
What is a Job Queue?
A job queue stores tasks in a broker such as Redis or RabbitMQ. Separate worker processes pull tasks and execute them, independent of the web server.
Defining a Celery Task
Celery is the most common Python job queue. You decorate a function as a task.
from celery import Celery
celery_app = Celery("tasks", broker="redis://localhost:6379/0")
@celery_app.task
def send_email(to: str):
# slow work here
return "sent to " + toEnqueuing from FastAPI
Trigger the task with .delay(); it returns immediately while a worker runs it later.
@app.post("/notify")
def notify(email: str):
send_email.delay(email)
return {"queued": True}Running Workers
Workers are separate processes you scale independently of the web tier.
celery -A tasks worker --loglevel=info --concurrency=4Tracking Task Results
With a result backend, you can store and query task status and outcomes.
result = send_email.delay("a@b.com")
print(result.id, result.status)Retries and Reliability
Job queues can automatically retry failed tasks with backoff, something in-process tasks cannot do.
@celery_app.task(bind=True, max_retries=3)
def process(self, item):
try:
do_work(item)
except Exception as exc:
raise self.retry(exc=exc, countdown=10)Scheduling Periodic Jobs
Celery Beat runs tasks on a schedule, like nightly cleanups or hourly syncs.
celery_app.conf.beat_schedule = {
"cleanup": {"task": "tasks.cleanup", "schedule": 3600.0}
}Idempotent Tasks
Because a queued task may be retried, design tasks to be idempotent so running them twice causes no harm, for example by checking if the email was already sent.
Quick Check
Test your background work knowledge.
Recap
You learned to keep request handlers fast:
- BackgroundTasks handles simple in-process after-response work
- Job queues like Celery give durable, distributed, retryable tasks
- Scale workers independently and schedule periodic jobs
Offloading slow work keeps your API responsive under load.
AI 튜터와 함께 FastAPI Backend Development Bootcamp을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 21
- 레슨
- 84
자주 묻는 질문
“백그라운드 작업과 작업 큐” 강의는 무료인가요?
네 — “백그라운드 작업과 작업 큐” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“백그라운드 작업과 작업 큐”에서 뭘 배우나요?
FastAPI 백그라운드 작업과 Celery 같은 분산 작업 큐를 사용해 요청 처리기에서 느린 작업을 분리하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“백그라운드 작업과 작업 큐” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Redis를 활용한 캐싱 전략
- 비동기 데이터베이스 접근
- 부하 분산 및 모니터링
- 백그라운드 작업과 작업 큐