This is a simple FastAPI server to work through blocking and non-blocking background tasks. It simulates a blocking upload (e.g., to S3) and shows how FastAPI’s BackgroundTasks returns a response immediately while work continues in the background.
- FastAPI (standard extras)
- Python 3.13+
- upload_to_s3() simulates a blocking operation using
time.sleep(5). GET /process-filesenqueues upload_to_s3 as a background task viaBackgroundTasks.- The endpoint returns immediately, while the blocking function runs in the background.
- Logs illustrate the timing:
- App: “Before process files” → “After process files”
- Background task: “Before sleep” → “After sleep”
To experiment with non-blocking behavior, compare time.sleep(5) with an async approach (e.g., await asyncio.sleep(5)) and adapt the task accordingly.
- Install dependencies:
uv sync
- Start the dev server:
uv run fastapi dev main.py
- Open the interactive docs:
- Create and activate a virtual environment:
python -m venv .venvsource .venv/bin/activate
- Install dependencies:
pip install "fastapi[standard]>=0.116.1"
- Start the server:
uvicorn main:app --reload
- Open the interactive docs:
GET /process-files- Queues a background task that simulates a blocking upload with
time.sleep(5). - Returns:
{"ok": true}immediately.
- Queues a background task that simulates a blocking upload with
Example:
curl http://127.0.0.1:8000/process-files
- The demo code lives in main.py, with upload_to_s3() as the blocking task and the
/process-filesroute scheduling it in the background. - Switch
time.sleep(5)toawait asyncio.sleep(5)and make the task async if you want to visualize non-blocking behavior end-to-end.