0Pricing
FastAPI Backend Development Bootcamp · 강의

백그라운드 작업 실행

장시간 실행되는 작업을 백그라운드 작업으로 분리하여 API 차단을 방지하고 사용자 경험을 개선하는 방법을 배웁니다.

백그라운드 작업 실행은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Slow Endpoints & UX

Imagine your API needs to do something time-consuming, like sending an email or processing a large file, after a user request.

If your API waits for these tasks to finish before responding, the user experiences a slow, unresponsive application. This is called a blocking operation.

Bad user experience often leads to users abandoning your app!

Blocking vs. Non-Blocking APIs

Think of it like ordering food:

  • Blocking: You order, and the waiter waits for your food to be cooked, served, and eaten before taking the next order. (Terrible service!)
  • Non-Blocking: You order, the waiter takes your order to the kitchen, and immediately takes the next customer's order. Your food is prepared in the background.

We want our APIs to be non-blocking for a smooth user experience.

Meet FastAPI's BackgroundTasks

FastAPI provides a simple way to run operations in the 'background' after sending the HTTP response to the client. This is done using the BackgroundTasks dependency.

BackgroundTasks lets you add functions to a list that will be executed once the main API route has completed and the response has been delivered.

Injecting BackgroundTasks

To use background tasks, you simply declare a parameter with the type BackgroundTasks in your path operation function. FastAPI will automatically inject an instance of it.

  • Import BackgroundTasks from fastapi.
  • Declare a parameter, e.g., background_tasks: BackgroundTasks.
  • Use background_tasks.add_task() to schedule a function.

First Background Task Demo

Let's see a basic example. This task will print a message after the API response is sent. Remember to run uvicorn main:app --reload.

from fastapi import FastAPI, BackgroundTasks
import time

app = FastAPI()

def write_notification(email: str, message=""):
    time.sleep(2) # Simulate a long operation
    with open("log.txt", mode="a") as email_file:
        email_file.write(f"notification for {email}: {message}\n")
    print(f"Notification written for {email}")

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="Welcome to CoddyKit!")
    return {"message": "Notification sent in background!"}

Understanding Execution Flow

It's crucial to understand when background tasks execute:

  • The path operation function runs.
  • The HTTP response is sent back to the client.
  • Then, the functions added to BackgroundTasks are executed.

This means the client doesn't wait for these tasks to complete, improving perceived performance.

Passing Arguments to Tasks

You can pass any arguments your background function needs to add_task(). The first argument is the function itself, followed by its arguments.

Arguments can be positional or keyword arguments, just like calling a regular Python function.

For example: background_tasks.add_task(my_function, arg1, arg2=value).

Simulating Email Send

A common scenario for background tasks is sending emails. This can take a few seconds, which would block your user if done directly in the API route.

Here, we simulate sending an email to multiple recipients. Try it from the /docs UI!

from fastapi import FastAPI, BackgroundTasks
import asyncio # For async sleep

app = FastAPI()

async def send_email_async(recipients: list, subject: str, body: str):
    print(f"Starting email send to {recipients}...")
    await asyncio.sleep(3) # Simulate network delay for sending email
    print(f"Email '{subject}' sent to {recipients} with body: '{body}'")

@app.post("/send-marketing-email/")
async def marketing_campaign(
    recipients: list[str],
    subject: str,
    body: str,
    background_tasks: BackgroundTasks
):
    # The actual email sending is offloaded
    background_tasks.add_task(send_email_async, recipients, subject, body)
    return {"message": "Marketing email campaign initiated in background!"}

Important Considerations

While powerful, BackgroundTasks are not for everything:

  • Short-lived: Best for tasks that complete relatively quickly (seconds to a few minutes).
  • No persistence: If your FastAPI process crashes, scheduled tasks are lost.
  • No retry: They don't have built-in retry mechanisms for failed tasks.
  • Not for heavy computation: For very long-running, CPU-intensive, or fault-tolerant tasks, consider dedicated task queues like Celery, Redis Queue (RQ), or similar.

Background Task Check

You've learned about using BackgroundTasks. Which of the following statements about FastAPI's BackgroundTasks is true?

Recap: Background Tasks

We've explored how FastAPI's BackgroundTasks help keep your API responsive:

  • They run after the HTTP response is sent.
  • They're great for non-critical, relatively short-lived operations like sending notifications.
  • You declare them as a dependency and use add_task().
  • For truly long-running or critical tasks, consider external task queues.

By using background tasks, you ensure a smoother experience for your API users!

자주 묻는 질문

“백그라운드 작업 실행” 강의는 무료인가요?

네 — “백그라운드 작업 실행” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“백그라운드 작업 실행”에서 뭘 배우나요?

장시간 실행되는 작업을 백그라운드 작업으로 분리하여 API 차단을 방지하고 사용자 경험을 개선하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“백그라운드 작업 실행” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Python 비동기 프로그래밍 복습
  2. FastAPI와 비동기 작업
  3. 백그라운드 작업 실행
  4. 실시간 통신을 위한 WebSockets
← FastAPI Backend Development Bootcamp(으)로 돌아가기