0
0
FastAPIframework~10 mins

Background tasks in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Background tasks
Client sends HTTP request
FastAPI receives request
Start main request handler
Schedule background task
Return HTTP response immediately
Background task runs separately
Background task completes
FastAPI handles the request, schedules a background task to run after response, then immediately returns the response while the task runs separately.
Execution Sample
FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    with open('log.txt', 'a') as f:
        f.write(message + '\n')

@app.post('/send/')
async def send_message(background_tasks: BackgroundTasks, msg: str):
    background_tasks.add_task(write_log, msg)
    return {'message': 'Message received'}
This FastAPI app schedules a background task to write a message to a file after sending the HTTP response.
Execution Table
StepActionBackground Task Scheduled?Response SentBackground Task RunningResult
1Client sends POST /send/ with msg='Hello'NoNoNoRequest received by FastAPI
2FastAPI calls send_message handlerNoNoNoHandler starts
3background_tasks.add_task(write_log, 'Hello') calledYesNoNoTask scheduled to write 'Hello' to log.txt
4Return {'message': 'Message received'}YesYesNoResponse sent to client immediately
5Background task write_log('Hello') startsYesYesYesWriting 'Hello' to log.txt
6Background task write_log('Hello') completesYesYesNoMessage logged in file
7Request cycle endsYesYesNoBackground task done, request fully processed
💡 Background task runs after response sent; request cycle ends when task completes.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
background_tasksemptycontains write_log taskcontains write_log taskcontains write_log task (running)empty after completion
responsenonenone{'message': 'Message received'} sentsentsent
log.txt contentemptyemptyemptycontains 'Hello\n'contains 'Hello\n'
Key Moments - 3 Insights
Why does the HTTP response return before the background task finishes?
Because FastAPI schedules the background task to run after sending the response immediately (see execution_table step 4). This lets the client get a quick reply without waiting.
Is the background task blocking the main request handler?
No, the background task runs separately after the response is sent (execution_table steps 5 and 6). The main handler finishes quickly after scheduling the task.
What happens if the background task fails?
FastAPI does not retry background tasks automatically. The failure happens after response is sent, so client is unaware (not shown in this trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the HTTP response sent to the client?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Check the 'Response Sent' column in execution_table rows.
According to variable_tracker, what is the state of 'background_tasks' after step 5?
AEmpty, no tasks scheduled
BContains write_log task, not started
CContains write_log task, running
DTask completed and removed
💡 Hint
Look at 'background_tasks' row and 'After Step 5' column in variable_tracker.
If the background task took longer, how would the response timing change?
AResponse would still be sent immediately
BResponse would never be sent
CResponse would be delayed until task finishes
DBackground task would run before request handler
💡 Hint
Refer to concept_flow and execution_table steps 4 and 5 about response timing.
Concept Snapshot
FastAPI Background Tasks:
- Use BackgroundTasks parameter in path operation
- Call background_tasks.add_task(func, args) to schedule
- Response returns immediately
- Background task runs after response
- Useful for non-blocking work like logging or sending emails
Full Transcript
In FastAPI, background tasks let you run code after sending the HTTP response. When a client sends a request, FastAPI runs the handler function. Inside, you add a background task using background_tasks.add_task. FastAPI then immediately returns the response to the client without waiting for the task to finish. The background task runs separately, for example writing a message to a file. This keeps the app fast and responsive. The execution table shows each step: receiving request, scheduling task, sending response, running task, and completing. Variables like background_tasks and response state change accordingly. Key points are that the response is sent before the task runs, and the task does not block the main handler. This pattern is great for tasks like logging or sending emails that don't need to delay the client. The visual quiz checks understanding of when response is sent and how background tasks behave.