Bird
Raised Fist0
FastAPIframework~20 mins

Background tasks in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using BackgroundTasks in FastAPI?
easy
A. To handle database connections synchronously
B. To replace the main event loop in FastAPI
C. To block the request until a task finishes
D. To run code after sending the response without delaying the user

Solution

  1. Step 1: Understand what BackgroundTasks do

    BackgroundTasks allow running code after the response is sent, so the user is not delayed.
  2. Step 2: Compare options with this behavior

    Only To run code after sending the response without delaying the user describes running code after response without delay; others describe blocking or unrelated tasks.
  3. Final Answer:

    To run code after sending the response without delaying the user -> Option D
  4. Quick Check:

    BackgroundTasks run code after response = B [OK]
Hint: BackgroundTasks run after response to avoid user wait [OK]
Common Mistakes:
  • Thinking BackgroundTasks block the response
  • Confusing BackgroundTasks with synchronous code
  • Assuming BackgroundTasks replace main event loop
2. Which of the following is the correct way to add a background task in a FastAPI endpoint?
easy
A. Import BackgroundTasks but do not use it
B. Call your_function() directly inside the endpoint
C. Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint
D. Use await your_function() inside the endpoint

Solution

  1. Step 1: Recall how to add background tasks in FastAPI

    You add tasks by calling background_tasks.add_task(function, args) inside the endpoint function.
  2. Step 2: Check each option

    Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint correctly uses add_task. Call your_function() directly inside the endpoint calls function immediately, blocking. Use await your_function() inside the endpoint awaits function, blocking. Import BackgroundTasks but do not use it does nothing.
  3. Final Answer:

    Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint -> Option C
  4. Quick Check:

    Use add_task to schedule background work = D [OK]
Hint: Use add_task method on BackgroundTasks instance [OK]
Common Mistakes:
  • Calling the function directly instead of scheduling
  • Awaiting the function which blocks response
  • Importing BackgroundTasks but not using it
3. Given this FastAPI code snippet, what will be printed after the response is sent?
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    print(f"Log: {message}")

@app.get("/items/{item_id}")
async def read_item(item_id: int, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, f"Item {item_id} accessed")
    return {"item_id": item_id}
medium
A. Log: Item {item_id} accessed is printed after response
B. Log: Item {item_id} accessed is printed before response
C. Nothing is printed because print is not awaited
D. SyntaxError because BackgroundTasks is not imported

Solution

  1. Step 1: Understand background task behavior

    The function write_log is scheduled as a background task, so it runs after the response is sent.
  2. Step 2: Analyze print timing

    Print inside write_log will execute after response, printing the log message with the item_id value.
  3. Final Answer:

    Log: Item {item_id} accessed is printed after response -> Option A
  4. Quick Check:

    Background task runs after response = C [OK]
Hint: Background tasks run after response, so print happens later [OK]
Common Mistakes:
  • Thinking print runs before response
  • Assuming print won't run without await
  • Missing import of BackgroundTasks (actually imported here)
4. Identify the error in this FastAPI code using background tasks:
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def send_email(email: str):
    print(f"Sending email to {email}")

@app.post("/send")
async def send(background_tasks: BackgroundTasks, email: str):
    background_tasks.add_task(send_email)
    return {"message": "Email scheduled"}
medium
A. Missing argument when adding task to background_tasks
B. BackgroundTasks should not be a parameter
C. send_email should be async
D. Email parameter must be inside the function send_email

Solution

  1. Step 1: Check how add_task is called

    The function send_email requires an argument email, but add_task is called without arguments.
  2. Step 2: Identify the missing argument

    The call should be background_tasks.add_task(send_email, email) to pass the email parameter.
  3. Final Answer:

    Missing argument when adding task to background_tasks -> Option A
  4. Quick Check:

    add_task needs function arguments = A [OK]
Hint: Pass all function args in add_task call [OK]
Common Mistakes:
  • Forgetting to pass required arguments to add_task
  • Thinking BackgroundTasks can't be a parameter
  • Assuming send_email must be async
5. You want to log user activity and send a welcome email after a user registers. Which is the best way to do this using FastAPI background tasks?
hard
A. Call logging and email functions directly inside the endpoint synchronously
B. Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task
C. Use await on both logging and email functions inside the endpoint
D. Run logging in background task but send email synchronously

Solution

  1. Step 1: Understand the goal

    We want to run both logging and sending email after response without delaying user.
  2. Step 2: Evaluate options

    Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task schedules both tasks as background tasks, so they run after response. Options B and C block response. Run logging in background task but send email synchronously delays sending email.
  3. Final Answer:

    Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task -> Option B
  4. Quick Check:

    Schedule all post-response tasks with add_task = A [OK]
Hint: Add all post-response jobs as background tasks [OK]
Common Mistakes:
  • Running tasks synchronously blocking response
  • Mixing sync and async incorrectly
  • Scheduling only one task in background
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard