Bird
Raised Fist0
FastAPIframework~20 mins

Background file processing in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Background Processing 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 code snippet that uploads a file and starts a background task to process it. What is the behavior of the endpoint when a file is uploaded?
FastAPI
from fastapi import FastAPI, UploadFile, BackgroundTasks

app = FastAPI()

def process_file(file_path: str):
    # Simulate file processing
    with open(file_path, 'r') as f:
        data = f.read()
    print(f"Processed file with length: {len(data)}")

@app.post('/upload')
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile):
    file_location = f"./temp/{file.filename}"
    with open(file_location, 'wb') as buffer:
        buffer.write(await file.read())
    background_tasks.add_task(process_file, file_location)
    return {"message": "File received, processing started"}
AThe endpoint returns an error because background tasks cannot be used with file uploads.
BThe endpoint waits until the file processing finishes before returning the response.
CThe endpoint immediately returns the response while the file processing runs in the background.
DThe file processing runs synchronously before the file is saved.
Attempts:
2 left
💡 Hint
Think about how FastAPI handles background tasks and response timing.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this FastAPI background task usage
Which option contains a syntax error that prevents the background task from being added correctly?
FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def task(name: str):
    print(f"Hello {name}")

@app.get('/start')
async def start(background_tasks: BackgroundTasks):
    background_tasks.add_task(task, 'User')
    return {"status": "started"}
Abackground_tasks.add_task(task, ['User'])
Bbackground_tasks.add_task(task, 'User')
Cbackground_tasks.add_task(task, name='User')
Dbackground_tasks.add_task(task 'User')
Attempts:
2 left
💡 Hint
Check the syntax of function calls and argument passing.
state_output
advanced
2:00remaining
What is printed when multiple background tasks modify a shared list?
Given this FastAPI code, what will be the final content of the shared list after the endpoint is called once?
FastAPI
from fastapi import FastAPI, BackgroundTasks
import time

app = FastAPI()
shared_list = []

def add_item(item: str):
    time.sleep(0.1)
    shared_list.append(item)

@app.get('/add')
async def add(background_tasks: BackgroundTasks):
    background_tasks.add_task(add_item, 'A')
    background_tasks.add_task(add_item, 'B')
    return {"message": "Tasks started"}
A['B', 'A']
B['A', 'B']
C[]
D['A']
Attempts:
2 left
💡 Hint
Background tasks run after response, but order of execution is preserved.
🔧 Debug
advanced
2:00remaining
Why does this background task fail to process the uploaded file?
This FastAPI code tries to process an uploaded file in the background but fails. What is the cause?
FastAPI
from fastapi import FastAPI, UploadFile, BackgroundTasks

app = FastAPI()

def process_file(file: UploadFile):
    content = file.file.read()
    print(f"File content length: {len(content)}")

@app.post('/upload')
async def upload(background_tasks: BackgroundTasks, file: UploadFile):
    background_tasks.add_task(process_file, file)
    return {"message": "Processing started"}
AThe UploadFile object is closed before the background task runs, so reading fails.
BBackgroundTasks cannot accept functions with parameters.
CThe process_file function must be async to work as a background task.
DThe file content must be saved to disk before processing.
Attempts:
2 left
💡 Hint
Think about the lifecycle of UploadFile and when its file handle is available.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI background tasks and concurrency is true?
Select the correct statement about how FastAPI handles background tasks and concurrency.
ABackground tasks run after the response is sent but share the same event loop, so CPU-bound tasks can block the server.
BBackground tasks run in separate threads and can safely modify shared memory without locks.
CBackground tasks run in separate processes automatically to avoid blocking the main server.
DBackground tasks are executed synchronously before the response is returned.
Attempts:
2 left
💡 Hint
Consider how FastAPI uses async and the Python event loop for background tasks.

Practice

(1/5)
1. What is the main benefit of using BackgroundTasks in FastAPI for file processing?
easy
A. It allows slow tasks to run after sending the response, keeping the app fast.
B. It automatically compresses files before saving.
C. It blocks the request until the file is fully processed.
D. It encrypts files during upload.

Solution

  1. Step 1: Understand the role of BackgroundTasks

    BackgroundTasks in FastAPI lets you run tasks after the response is sent, so the user doesn't wait.
  2. Step 2: Identify the benefit for file processing

    Running slow file processing in the background keeps the app responsive and fast for users.
  3. Final Answer:

    It allows slow tasks to run after sending the response, keeping the app fast. -> Option A
  4. Quick Check:

    BackgroundTasks = run slow tasks after response [OK]
Hint: BackgroundTasks run after response to keep app fast [OK]
Common Mistakes:
  • Thinking BackgroundTasks block the response
  • Assuming BackgroundTasks handle file encryption
  • Believing BackgroundTasks compress files automatically
2. Which of the following is the correct way to add a background task for file processing in a FastAPI endpoint?
easy
A. def upload(file: UploadFile, background_tasks: BackgroundTasks): process_file(file)
B. def upload(file: UploadFile): process_file(file) background_tasks.add_task()
C. def upload(file: UploadFile): background_tasks = BackgroundTasks() process_file(file)
D. def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file)

Solution

  1. Step 1: Check function parameters

    To use BackgroundTasks, it must be a parameter in the endpoint function.
  2. Step 2: Add the task correctly

    Use background_tasks.add_task(function, args) to schedule the task after response.
  3. Final Answer:

    def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file) -> Option D
  4. Quick Check:

    Use add_task with BackgroundTasks parameter [OK]
Hint: Add tasks using background_tasks.add_task inside endpoint [OK]
Common Mistakes:
  • Calling process_file directly inside endpoint
  • Not including BackgroundTasks as a parameter
  • Creating BackgroundTasks inside the function without adding tasks
3. Given this FastAPI code snippet, what will be the response behavior when a file is uploaded?
from fastapi import FastAPI, UploadFile, BackgroundTasks
app = FastAPI()

def save_file(file: UploadFile):
    with open(f"saved_{file.filename}", "wb") as f:
        f.write(file.file.read())

@app.post("/upload")
async def upload(file: UploadFile, background_tasks: BackgroundTasks):
    background_tasks.add_task(save_file, file)
    return {"message": "File upload started"}
medium
A. The response returns immediately with message, while file saving happens in background.
B. The response waits until the file is saved, then returns the message.
C. The file is saved before the response, but no message is returned.
D. The code will raise an error because file.file.read() is not allowed.

Solution

  1. Step 1: Analyze background task usage

    The save_file function is added as a background task, so it runs after response.
  2. Step 2: Understand response timing

    The endpoint returns the message immediately, without waiting for save_file to finish.
  3. Final Answer:

    The response returns immediately with message, while file saving happens in background. -> Option A
  4. Quick Check:

    BackgroundTasks run after response = immediate reply [OK]
Hint: BackgroundTasks run after response, so response is immediate [OK]
Common Mistakes:
  • Assuming file saving blocks response
  • Thinking file.file.read() causes error here
  • Believing no message is returned
4. Identify the error in this FastAPI endpoint for background file processing:
from fastapi import FastAPI, UploadFile, BackgroundTasks
app = FastAPI()

def process_file(file: UploadFile):
    content = file.file.read()
    with open(f"processed_{file.filename}", "wb") as f:
        f.write(content)

@app.post("/upload")
async def upload(file: UploadFile, background_tasks: BackgroundTasks):
    background_tasks.add_task(process_file, file.file.read())
    return {"message": "Processing started"}
medium
A. Missing await keyword before background_tasks.add_task call.
B. Passing file.file.read() instead of file causes the file to be read too early.
C. process_file should be async but is defined as sync.
D. File is not saved before background task starts.

Solution

  1. Step 1: Check argument passed to add_task

    The code passes file.file.read() which reads the file immediately, not the file object.
  2. Step 2: Understand why this is a problem

    Reading the file before background task means the task gets raw bytes, not the file to read later, causing errors or empty data.
  3. Final Answer:

    Passing file.file.read() instead of file causes the file to be read too early. -> Option B
  4. Quick Check:

    Pass file object, not file.file.read() to background task [OK]
Hint: Pass file object, not file.file.read(), to background task [OK]
Common Mistakes:
  • Thinking add_task needs await
  • Believing process_file must be async
  • Ignoring file saving order
5. You want to save an uploaded file immediately and then process it in the background. Which FastAPI code snippet correctly implements this pattern?
hard
A. async def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file) return {"message": "Processing started"}
B. async def upload(file: UploadFile): contents = await file.read() with open(f"saved_{file.filename}", "wb") as f: f.write(contents) process_file(f"saved_{file.filename}") return {"message": "File saved and processed"}
C. async def upload(file: UploadFile, background_tasks: BackgroundTasks): contents = await file.read() with open(f"saved_{file.filename}", "wb") as f: f.write(contents) background_tasks.add_task(process_file, f"saved_{file.filename}") return {"message": "File saved and processing started"}
D. async def upload(file: UploadFile, background_tasks: BackgroundTasks): background_tasks.add_task(process_file, file.file.read()) return {"message": "Processing started"}

Solution

  1. Step 1: Save file before background processing

    The file is read and saved immediately using await file.read() and writing to disk.
  2. Step 2: Add background task with saved filename

    The background task processes the saved file path, ensuring file exists before processing.
  3. Final Answer:

    Save file first, then add background task with saved filename. -> Option C
  4. Quick Check:

    Save file first, then background task with filename [OK]
Hint: Save file first, then add background task with filename [OK]
Common Mistakes:
  • Adding background task before saving file
  • Passing file.file.read() instead of file or filename
  • Calling process_file synchronously inside endpoint