- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Advanced Features and Production Readiness
- Background Tasks and Asynchronous Operations
On this page
FastAPI Async Endpoints and Background Tasks
Published on August 16, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A FastAPI application built on asyncio can serve thousands of concurrent connections on a single thread — but only if every piece of code running inside a request actually cooperates with that model. A single blocking call anywhere in an async def function stalls every other request the server is currently handling, not just the one that made the call. Getting this right means understanding two separate things clearly: how to write endpoints that never block the event loop, and how to defer non-critical work — sending an email, writing an audit log — to run only after the response has already gone out to the client.
How FastAPI Handles Concurrency
FastAPI runs on a single-threaded async event loop managed by Uvicorn. Concurrency comes from cooperative multitasking: when a coroutine reaches an await expression, it voluntarily yields control back to the event loop, which can then run a different coroutine while the first one waits.
This model is extremely efficient for I/O-bound work — database queries, HTTP calls, file reads — where most of the actual time is spent waiting on an external system rather than computing anything.
It breaks down entirely the moment code blocks the event loop: any operation that runs without yielding — time.sleep(), a synchronous database driver, CPU-intensive computation, any blocking library call — holds the event loop hostage for its full duration. Every other incoming request queues up and waits during that time. One blocked coroutine is enough to make an entire API appear unresponsive under concurrent load.
async def vs. def endpoints
FastAPI runs async def and def path operation functions through two different mechanisms, and the choice between them has real consequences:
DeclarationHow FastAPI runs itWhen to use itasync defRuns directly in the event loopAny endpoint that awaits I/O — async DB drivers, httpx, aiofiles``defRuns in a thread pool executorEndpoints using synchronous/blocking libraries that cannot be made async
If a path operation is declared async def but contains a blocking call — a synchronous sleep, a synchronous ORM, heavy computation — that call blocks the event loop for every request the server is handling at that moment, not just the one that triggered it. Declaring the function as plain def instead moves it into a thread pool, where the same blocking call only holds up one thread and leaves the event loop itself free.
import time
from fastapi import APIRouter
router = APIRouter(prefix="/blocking", tags=["Blocking Demo"])
# WRONG — blocks the event loop for 3 seconds on every call
@router.get("/bad")
async def bad_endpoint():
time.sleep(3) # synchronous sleep blocks the whole event loop
return {"status": "done"}
# CORRECT for blocking code — FastAPI runs this in a thread pool
@router.get("/good")
def good_endpoint():
time.sleep(3) # runs in a thread; event loop stays free
return {"status": "done"}
# CORRECT for truly async I/O — use async libraries throughout
@router.get("/async")
async def async_endpoint():
import asyncio
await asyncio.sleep(3) # yields to event loop — zero blocking
return {"status": "done"}
Async Endpoints
An async endpoint is an async def function that uses await to call async I/O operations. While it waits for that external call to complete, the event loop remains free to serve other requests.
Non-blocking HTTP calls with httpx
httpx.AsyncClient is the standard async HTTP client for FastAPI applications. It offers the same API as the synchronous requests library, but every network operation yields to the event loop instead of blocking it:
routers/async_demo.py:
from fastapi import APIRouter
import httpx
router = APIRouter(prefix="/async", tags=["Async"])
@router.get("/weather")
async def get_weather():
async with httpx.AsyncClient() as client:
response = await client.get(
"https://api.weatherapi.com/v1/current.json",
params={"key": "demo", "q": "Tokyo"},
timeout=10.0,
)
response.raise_for_status()
return response.json()
async with httpx.AsyncClient() creates the client for the duration of the request and closes it automatically when the block exits. await client.get(...) suspends this coroutine while the network round-trip completes, freeing the event loop to handle other requests in the meantime.
Creating a fresh AsyncClient per request is acceptable at low traffic but wasteful at scale, since it opens and tears down a new TCP connection on every single call. A production setup creates one shared client inside a lifespan context manager and reuses it across every request instead.
Running multiple async calls in parallel with asyncio.gather
When an endpoint needs results from two or more independent async operations, awaiting them one after another wastes time — the second call sits idle waiting for the first to finish even though nothing connects them. asyncio.gather() runs them concurrently and returns every result once all of them have completed:
import asyncio
import httpx
from fastapi import APIRouter
router = APIRouter(prefix="/parallel", tags=["Parallel"])
async def fetch_url(client: httpx.AsyncClient, url: str) -> dict:
response = await client.get(url, timeout=10.0)
response.raise_for_status()
return response.json()
@router.get("/dashboard")
async def get_dashboard():
async with httpx.AsyncClient() as client:
weather, news = await asyncio.gather(
fetch_url(client, "https://api.weatherapi.com/v1/current.json?key=demo&q=Tokyo"),
fetch_url(client, "https://hacker-news.firebaseio.com/v0/topstories.json"),
)
return {"weather": weather, "top_stories": news[:5]}
Two sequential 500ms calls awaited one after another take roughly 1000ms in total. The same two calls through asyncio.gather run concurrently, and the total time drops to approximately the duration of the slower of the two — around 500ms.
asyncio.create_task — fire and continue
asyncio.create_task() schedules a coroutine as an independent task on the event loop and returns immediately with a Task object, without waiting for that coroutine to finish. This fits situations where work should start now and the current coroutine should continue without waiting on the result.
There's a specific, well-documented behavior worth understanding before reaching for this: the event loop only holds a weak reference to a task it's running. If nothing else in the program holds a real reference to that same Task object, Python's garbage collector is free to destroy it at any point — including in the middle of its execution — and the task simply stops running with no error raised anywhere. Assigning the result of create_task() to a local variable inside a function is exactly the situation this affects: once that function returns, the local variable goes out of scope, and if nothing else was holding onto the task, it becomes eligible for collection immediately.
Python's own documentation recommends keeping a strong reference in a module-level collection specifically to avoid this:
import asyncio
import logging
from fastapi import APIRouter
router = APIRouter(prefix="/tasks", tags=["Tasks"])
logger = logging.getLogger(__name__)
# Module-level set — holds a strong reference so tasks aren't garbage collected mid-run
_background_tasks: set[asyncio.Task] = set()
async def index_search(item_id: int):
await asyncio.sleep(2) # simulate search indexing
print(f"Indexed item {item_id}")
def _log_task_result(task: asyncio.Task) -> None:
if not task.cancelled() and task.exception():
logger.error(f"Background task failed: {task.exception()}")
@router.post("/items/{item_id}")
async def create_item(item_id: int):
task = asyncio.create_task(index_search(item_id))
_background_tasks.add(task) # keep a strong reference
task.add_done_callback(_background_tasks.discard) # release it once finished
task.add_done_callback(_log_task_result) # surface any exception
# The endpoint returns immediately; index_search runs in the background
return {"item_id": item_id, "status": "created"}
_background_tasks.add(task) is what keeps the task alive for its full duration regardless of what happens to the local task variable once create_item returns. task.add_done_callback(_background_tasks.discard) removes it from that set the moment it finishes, so the set doesn't grow indefinitely as more requests come in. _log_task_result is the second callback, and it's what surfaces a failure at all — without it, an exception raised inside index_search would be silently discarded, exactly like an unhandled exception inside a BackgroundTasks function.
This distinguishes asyncio.create_task from BackgroundTasks in one more important way beyond error handling: a task created this way runs within the current process's event loop for as long as that process is alive, but it's not tied to the request/response lifecycle the way BackgroundTasks is, and it isn't guaranteed to complete if the server shuts down or the worker process is recycled mid-task.
Background Tasks
BackgroundTasks is FastAPI's built-in mechanism for scheduling work to run after the HTTP response has already been sent to the client. It's injected as a dependency, needs no separate configuration, and supports both def and async def task functions.
How BackgroundTasks works
Once a response is ready, FastAPI sends it to the client first and only then runs every function registered through background_tasks.add_task(). The client never waits for these — it gets the response immediately, and the registered tasks run afterward, in the same server process. Under the hood, BackgroundTasks is Starlette's own BackgroundTasks class, an ASGI-level mechanism that runs after the response closes but still within the same request's lifecycle.
A basic background task
routers/jobs.py:
from fastapi import APIRouter, BackgroundTasks
import logging
router = APIRouter(prefix="/jobs", tags=["Jobs"])
logger = logging.getLogger(__name__)
def write_log(message: str) -> None:
with open("log.txt", "a") as f:
f.write(message + "\n")
logger.info(f"Log written: {message}")
@router.post("/signup")
def signup(username: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"New signup: {username}")
return {"message": f"User {username} created"}
background_tasks.add_task(func, *args, **kwargs) accepts any callable followed by its positional and keyword arguments, and calls it with those exact arguments once the response has already gone out.
def vs. async def task functions
Both work, but the underlying execution differs. A def task function runs inside FastAPI's thread pool executor, keeping the event loop free for the duration of that task — the right choice for synchronous or blocking work. An async def task function is awaited directly on the event loop instead — the right choice for genuine async I/O, sending an email through an async SMTP client, or writing through an async ORM.
import httpx
from fastapi import APIRouter, BackgroundTasks
router = APIRouter(prefix="/combo", tags=["Combo"])
async def notify_admin(user: str) -> None:
async with httpx.AsyncClient() as client:
await client.post(
"https://example.com/notify",
json={"user": user},
timeout=5.0,
)
@router.post("/register")
async def register(user: str, background_tasks: BackgroundTasks):
background_tasks.add_task(notify_admin, user)
return {"message": f"User {user} registered"}
Error handling in background tasks
Exceptions raised inside a BackgroundTasks function are silently swallowed by default. The client already received a successful response, and the failure leaves no trace at all unless it's handled explicitly inside the task function itself — this is the single most consequential characteristic of BackgroundTasks, and the one most often overlooked until something quietly stops working in production.
# WRONG — exception is silently swallowed; client gets 200, email never sent
async def send_welcome_email(email: str) -> None:
async with httpx.AsyncClient() as client:
await client.post("https://mailservice.example.com/send", json={"to": email})
# CORRECT — wrap in try/except and log failures explicitly
async def send_welcome_email(email: str) -> None:
try:
async with httpx.AsyncClient() as client:
response = await client.post(
"https://mailservice.example.com/send",
json={"to": email},
timeout=10.0,
)
response.raise_for_status()
except Exception:
logger.exception(f"Failed to send welcome email to {email}")
# Optionally: push to a dead-letter queue or retry mechanism
Wrapping every background task body in try/except Exception and logging the failure is what makes it visible at all. For work where delivery genuinely matters — payment notifications, account confirmations — a task queue with real retry support is the appropriate tool instead of BackgroundTasks.
Using BackgroundTasks inside dependencies
BackgroundTasks can be injected into a dependency, not only directly into a route function. FastAPI passes the exact same BackgroundTasks instance to a dependency that it passes to the route, so anything scheduled from inside that dependency runs in the same post-response batch — which lets shared infrastructure, a notification service or an audit logger, schedule its own background work without the route needing to know the implementation exists:
from fastapi import Depends, BackgroundTasks
class NotificationService:
def __init__(self, background_tasks: BackgroundTasks):
self.background_tasks = background_tasks
def send(self, user: str, message: str) -> None:
self.background_tasks.add_task(self._send, user, message)
async def _send(self, user: str, message: str) -> None:
try:
async with httpx.AsyncClient() as client:
await client.post(
"https://notify.example.com",
json={"user": user, "message": message},
timeout=5.0,
)
except Exception:
logger.exception(f"Notification failed for {user}")
def get_notification_service(background_tasks: BackgroundTasks) -> NotificationService:
return NotificationService(background_tasks)
@router.post("/complete-task/{task_id}")
async def complete_task(
task_id: int,
session: Session = Depends(get_session),
notifications: NotificationService = Depends(get_notification_service),
user: User = Depends(require_active_user),
):
task = task_service.complete_task(task_id, session, user)
notifications.send(user.username, f"Task '{task.title}' marked complete")
return task
The Production Caveat: When BackgroundTasks Is Not Enough
BackgroundTasks fits lightweight, non-critical, fire-and-forget work well, but it carries three limitations that rule it out for anything production-critical. It has no persistence across restarts — a killed process, a crash, or a routine deployment restart discards any task that was running or queued at that moment, with no record left behind. CPU-bound work still blocks the event loop, since BackgroundTasks runs in the same process and event loop as the application itself — a computationally heavy task degrades every other concurrent request for as long as it runs, exactly like a blocking endpoint would. And there's no retry, no dead-letter queue, and no monitoring built in — a failed task is only visible at all if the code inside it explicitly logs the failure.
For anything where those limitations actually matter — payment processing, transactional email, report generation, ML inference — a dedicated task queue is the right tool instead:
ToolBest forRequiresBackgroundTasksLightweight, non-critical fire-and-forgetNothing extraasyncio.create_taskShort concurrent tasks within a single requestNothing extraCelery + Redis/RabbitMQProduction task queues with retries and monitoringRedis or RabbitMQ brokerARQAsync-native task queue using RedisRedisDramatiqSimple, reliable task queuesRedis or RabbitMQ
Applying This to the Task Manager
Background tasks fit naturally into at least two places in a Task Manager API.
Recording who created or modified a task, without slowing down the response itself:
def write_audit_log(user_id: int, action: str, task_id: int) -> None:
try:
with open("audit.log", "a") as f:
from datetime import datetime, timezone
f.write(f"{datetime.now(timezone.utc).isoformat()} | user={user_id} | {action} | task={task_id}\n")
except Exception:
logger.exception("Audit log write failed")
@router.post("/", status_code=201)
async def create(
task: Task,
background_tasks: BackgroundTasks,
session: Session = Depends(get_session),
user: User = Depends(require_active_user),
):
created = task_service.create_task(task, session, user)
background_tasks.add_task(write_audit_log, user.id, "task_created", created.id)
return created
Sending a welcome email at signup, where the client shouldn't have to wait on the email actually being delivered:
async def send_welcome_email(username: str, email: str) -> None:
try:
async with httpx.AsyncClient() as client:
await client.post(
"https://mailservice.example.com/send",
json={"to": email, "subject": "Welcome", "body": f"Hi {username}!"},
timeout=10.0,
)
except Exception:
logger.exception(f"Welcome email failed for {username}")
@router.post("/signup", status_code=201)
@limiter.limit("3/minute")
def signup(
request: Request,
user: User,
background_tasks: BackgroundTasks,
session: Session = Depends(get_session),
):
existing_user = session.exec(select(User).where(User.username == user.username)).first()
if existing_user:
raise HTTPException(status_code=400, detail="Username already exists")
user.hashed_password = hash_password(user.hashed_password)
session.add(user)
session.commit()
session.refresh(user)
background_tasks.add_task(send_welcome_email, user.username, user.email)
return {"message": "User created", "user_id": user.id}
Common Mistakes to Avoid
Using time.sleep() inside async def blocks the entire event loop for its full duration — await asyncio.sleep() is the async-safe equivalent, or the function can be declared plain def so FastAPI runs it in a thread pool instead. Using a synchronous library — a blocking database driver, requests, plain file I/O — inside an async def endpoint blocks the event loop the same way; the async equivalents (an async ORM driver, httpx.AsyncClient, aiofiles) exist specifically to avoid this. Not handling errors inside a BackgroundTasks function leaves failures completely invisible, since exceptions there are silently discarded by default — wrapping every task body in try/except Exception and logging the failure is what surfaces it at all. Using BackgroundTasks for CPU-bound work doesn't offload anything to a separate process — it runs in the same event loop as everything else and degrades every concurrent request while it runs; ProcessPoolExecutor or Celery are the correct tools for that instead. Creating a task with asyncio.create_task and returning from the route without awaiting it, when the response actually depends on that task's result, means the response goes out before the result exists at all — anything the response needs has to be awaited directly or collected through asyncio.gather. Not keeping a reference to a task created with asyncio.create_task risks the task being garbage collected mid-execution, since the event loop only holds a weak reference to it — a module-level set holding a strong reference, cleared through a done callback, is the documented fix. And assuming BackgroundTasks survives a server restart is incorrect regardless of how it's used — queued tasks live only in memory, and a crash, an out-of-memory kill, or a routine deployment restart discards every pending one permanently, which is exactly the gap a persistent broker like Celery with Redis or RabbitMQ, or ARQ, is built to close.
Quick Reference
Use caseRight toolWrong toolNon-blocking HTTP callasync def + httpx.AsyncClient``requests inside async defMultiple parallel I/O callsasyncio.gather()Sequential await callsFire-and-continue within a coroutineasyncio.create_task() with a kept referenceSequential awaitPost-response lightweight workBackgroundTasksSynchronous blocking inside routePost-response async workBackgroundTasks + async def task—Durable, retriable background jobsCelery / ARQBackgroundTasksCPU-bound background workProcessPoolExecutor / CeleryBackgroundTasks
Frequently Asked Questions
What is the difference between async def and def endpoints in FastAPI?
async def endpoints run directly in the event loop and are the correct choice when the function uses await to call async I/O operations such as async database drivers or httpx. def endpoints are run by FastAPI in a thread pool executor, which keeps the event loop free. This makes def the correct choice for endpoints that use synchronous or blocking libraries that cannot be made async. Using async def with blocking code is worse than using def, because it blocks the entire event loop rather than just one thread.
What happens if I use time.sleep() inside an async def endpoint in FastAPI?
time.sleep() is a synchronous blocking call. Inside an async def function, it blocks the entire event loop for its full duration, preventing every other concurrent request from being served during that time. Use await asyncio.sleep() for delays in async contexts, or declare the function as def so FastAPI runs it in a thread pool where the sleep blocks only that thread and leaves the event loop free.
What is BackgroundTasks in FastAPI and how does it work?
BackgroundTasks is FastAPI's built-in utility for scheduling functions to run after the HTTP response has been sent to the client. It is injected as a dependency into route functions or dependencies. After the response is closed, FastAPI runs all functions registered with background_tasks.add_task(func, *args, **kwargs) in sequence. The client does not wait for these tasks — it receives the response immediately and the tasks execute afterward in the same server process.
How do I add a background task in FastAPI?
Declare BackgroundTasks as a parameter in your route function. FastAPI injects it automatically. Then call background_tasks.add_task(your_function, arg1, arg2) before returning the response. The function will be called with the provided arguments after the response is sent. Both def and async def functions are supported as task functions.
Can I use async def functions as FastAPI background tasks?
Yes. BackgroundTasks supports both def and async def task functions. A def task function is run in FastAPI's thread pool executor, keeping the event loop free. An async def task function is awaited directly in the event loop. Use async def for tasks that perform async I/O such as sending an email via an async SMTP client or writing to a database with an async ORM. Use def for tasks that use synchronous or blocking operations.
Are exceptions in FastAPI BackgroundTasks reported automatically?
No. Exceptions raised inside a BackgroundTasks function are silently swallowed by default. The client receives a successful HTTP response and the failure leaves no trace unless you handle it explicitly inside the task function. Always wrap the body of every background task in a try/except Exception block and log failures. For tasks where delivery is critical, use a task queue with retry support such as Celery or ARQ instead of BackgroundTasks.
What is the difference between BackgroundTasks and asyncio.create_task in FastAPI?
BackgroundTasks is an ASGI-level mechanism that runs registered functions after the HTTP response is sent, within the request lifecycle. asyncio.create_task schedules a coroutine as an independent task on the event loop immediately and returns a Task object, without tying the task to the request lifecycle. BackgroundTasks is the correct choice for post-response work in FastAPI routes. asyncio.create_task is useful for firing off concurrent work within a coroutine and continuing without waiting for the result, but the task must have a reference kept somewhere or it can be garbage collected mid-execution, and it is not guaranteed to complete if the server is shut down.
How do I run multiple async API calls in parallel in FastAPI?
Use asyncio.gather(). Pass the coroutines you want to run concurrently as arguments: results = await asyncio.gather(coroutine_one(), coroutine_two()). asyncio.gather runs all coroutines concurrently and returns a list of their results once all have completed. Without asyncio.gather, sequential await calls execute one at a time — the total time is the sum of all durations. With asyncio.gather, the total time is approximately that of the slowest coroutine.
What is asyncio.create_task and when should I use it in FastAPI?
asyncio.create_task schedules a coroutine as an independent task on the event loop and returns immediately with a Task object, without awaiting the coroutine. Use it when you want to kick off work and continue executing the current coroutine without waiting for the result. A reference to the returned Task must be kept somewhere — for example in a module-level set — since the event loop only holds a weak reference and an unreferenced task can be garbage collected before it finishes. Always attach a done callback with task.add_done_callback() to log or handle exceptions, because unhandled exceptions in create_task coroutines are otherwise silently discarded.
Why should I not use asyncio.create_task for operations that are critical to the response?
asyncio.create_task returns immediately without waiting for the coroutine to complete. If the response depends on the result of that coroutine, the route returns before the result is available and the client receives an incomplete or incorrect response. If an operation is required for the response, it must be awaited directly or collected via asyncio.gather. Use asyncio.create_task only for fire-and-forget work whose result is not needed by the caller.
Can BackgroundTasks handle CPU-bound work in FastAPI?
No. BackgroundTasks runs in the same process and event loop as the main application. A CPU-intensive background task holds the event loop and degrades the performance of every concurrent request for its entire duration, the same as a blocking endpoint would. For CPU-bound background work, use concurrent.futures.ProcessPoolExecutor to run the work in a separate process, or use a dedicated task queue such as Celery that runs workers in separate processes.
Does FastAPI BackgroundTasks survive server restarts or crashes?
No. Queued background tasks exist only in memory within the running server process. If the process is killed, crashes due to an out-of-memory condition, or is restarted during a deployment, all pending background tasks are permanently lost with no record and no retry. For durable task execution where delivery must be guaranteed, use a task queue backed by a persistent broker such as Celery with Redis or RabbitMQ, or ARQ.
How do I make parallel HTTP requests in FastAPI?
Use httpx.AsyncClient combined with asyncio.gather. Create an AsyncClient, define coroutines that each perform one HTTP call with await client.get() or await client.post(), then pass all coroutines to asyncio.gather to run them concurrently. The event loop runs all requests in parallel and the function proceeds once every request has completed. This approach reduces total latency to approximately the duration of the slowest individual request rather than the sum of all durations.
When should I use Celery instead of FastAPI BackgroundTasks?
Use Celery when any of the following apply: the task must survive server restarts or crashes, the task requires automatic retry on failure, the task is CPU-bound and must run in a separate process, you need monitoring and visibility into task status and failures, or you need a dead-letter queue for failed jobs. BackgroundTasks is appropriate only for lightweight, non-critical, fire-and-forget work such as audit logging or sending a non-transactional notification where losing the task occasionally is acceptable.
Can I use BackgroundTasks inside a FastAPI dependency?
Yes. BackgroundTasks can be injected into any dependency, not only route functions. FastAPI passes the same BackgroundTasks instance to the dependency that it uses for the route, so any tasks added inside the dependency are included in the same post-response execution batch. This allows shared services such as notification systems or audit loggers to schedule their own background work without the route needing to know about the implementation.
What is the event loop in FastAPI and why does blocking it matter?
FastAPI runs on a single-threaded async event loop managed by Uvicorn. The event loop achieves concurrency by switching between coroutines at await points — when one coroutine yields control, another can run. Any operation that does not yield — synchronous sleep, blocking I/O, CPU computation — holds the event loop for its entire duration. During that time no other coroutines can run, meaning all other incoming requests queue up and wait. A single blocked coroutine can make the entire API appear unresponsive under concurrent load.
What async HTTP client should I use in FastAPI?
Use httpx.AsyncClient. It provides the same API as the synchronous requests library but every network operation is async and yields to the event loop while waiting for the network round-trip. Use it as an async context manager with async with httpx.AsyncClient() as client to ensure the client is properly closed. For production, create a shared AsyncClient instance in a lifespan context manager and reuse it across requests rather than creating a new client per request.
How do I handle errors in asyncio.create_task in FastAPI?
Attach a done callback using task.add_done_callback(callback_function). The callback receives the completed Task object. Inside the callback, check task.cancelled() to detect cancellation and task.exception() to retrieve any unhandled exception. Log or re-raise the exception as appropriate. Without a done callback, any exception raised inside a create_task coroutine is silently discarded and the failure leaves no trace in logs or monitoring.
Why did my asyncio.create_task work sometimes and silently stop running other times?
This is the asyncio disappearing-task problem. The event loop only holds a weak reference to a Task object — if nothing else in the program references it, the task becomes eligible for garbage collection at any point, even mid-execution, and simply stops running with no error raised. Assigning the task to a local variable that goes out of scope when the function returns is a common way this happens by accident. Keeping a reference in a module-level set, and removing it via a done callback once the task finishes, avoids this.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Advanced Features and Production Readiness
Next
WebSockets and Real-Time Features
-
How FastAPI Handles Concurrency
- async def vs. def endpoints
-
Async Endpoints
- Non-blocking HTTP calls with httpx
- Running multiple async calls in parallel with asyncio.gather
- asyncio.create_task — fire and continue
-
Background Tasks
- How BackgroundTasks works
- A basic background task
- def vs. async def task functions
- Error handling in background tasks
- Using BackgroundTasks inside dependencies
-
The Production Caveat: When BackgroundTasks Is Not Enough
-
Applying This to the Task Manager
-
Common Mistakes to Avoid
-
Quick Reference
-
Frequently Asked Questions
