0
0
FastAPIframework~20 mins

Background tasks in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Background Tasks Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a background task is added in FastAPI?

Consider this FastAPI endpoint using BackgroundTasks. What is the behavior of the background task?

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"}
AThe write_log function runs after the response is sent, without blocking the client.
BThe write_log function runs in a separate thread and blocks the response until finished.
CThe write_log function runs only if the client waits for the response.
DThe write_log function runs immediately before the response is sent.
Attempts:
2 left
💡 Hint

Background tasks run after the response is sent to the client.

📝 Syntax
intermediate
1:30remaining
Which option correctly adds a background task in FastAPI?

Given the function def cleanup(): ..., which code snippet correctly adds it as a background task in a FastAPI endpoint?

FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def cleanup():
    print("Cleaning up")

@app.get("/clean")
async def clean(background_tasks: BackgroundTasks):
    # Add cleanup as background task
    pass
Abackground_tasks.add_task(cleanup())
Bbackground_tasks.add_task(cleanup)
Cbackground_tasks.add(cleanup)
Dbackground_tasks.run(cleanup)
Attempts:
2 left
💡 Hint

Remember to pass the function itself, not call it.

🔧 Debug
advanced
2:30remaining
Why does this background task not run as expected?

Examine the code below. The background task is supposed to write to a file, but the file remains empty. What is the cause?

FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log():
    with open("log.txt", "a") as f:
        f.write("Logged\n")

@app.post("/log")
async def log(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log())
    return {"status": "ok"}
AThe endpoint must be synchronous to use background tasks.
BThe file path "log.txt" is invalid, so no write occurs.
CBackgroundTasks cannot run synchronous functions like write_log.
DThe write_log function is called immediately, so the task is None and not scheduled.
Attempts:
2 left
💡 Hint

Check how the function is passed to add_task.

state_output
advanced
2:00remaining
What is the content of the file after calling this endpoint twice?

Given the code below, what will be the content of log.txt after two POST requests to /send with messages "Hello" and "World"?

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(background_tasks: BackgroundTasks, msg: str):
    background_tasks.add_task(write_log, msg)
    return {"status": "sent"}
A
log.txt contains:
Hello
World
B
log.txt contains:
World
Hello
C
log.txt contains:
HelloWorld
Dlog.txt is empty because background tasks run asynchronously.
Attempts:
2 left
💡 Hint

Background tasks append messages in order of requests.

🧠 Conceptual
expert
3:00remaining
What is a key limitation of FastAPI BackgroundTasks compared to Celery or other task queues?

Choose the correct statement about FastAPI's BackgroundTasks compared to external task queues like Celery.

ABackgroundTasks run in a separate worker process managed by FastAPI.
BBackgroundTasks automatically retry failed tasks with exponential backoff.
CBackgroundTasks run in the same process and will be lost if the server restarts.
DBackgroundTasks support distributed task scheduling across multiple servers.
Attempts:
2 left
💡 Hint

Think about persistence and reliability of tasks.