What if your app could serve hundreds of users at once without making anyone wait?
Async vs sync decision in FastAPI - When to Use Which
Imagine your web app needs to handle many users at once, but each request waits for slow tasks like database calls or external APIs before responding.
Using only synchronous code means each request blocks the server until it finishes, making users wait longer and the server handle fewer requests at a time.
Async code lets the server start a task, then switch to handle other requests while waiting, making your app faster and able to serve many users smoothly.
def get_data(): data = slow_database_call() return data
async def get_data(): data = await slow_database_call() return data
It enables your FastAPI app to handle many requests efficiently without making users wait unnecessarily.
A chat app where many users send messages simultaneously, and the server quickly processes each without delays.
Synchronous code waits and blocks, slowing down your app.
Asynchronous code lets your app do many things at once, improving speed.
Choosing async or sync affects how well your FastAPI app handles multiple users.
Practice
async function over a def synchronous function?Solution
Step 1: Understand async purpose in FastAPI
Async functions let your app wait for external tasks like database calls without stopping other work.Step 2: Match task type to function type
Waiting for external resources is I/O-bound, so async is best to avoid blocking.Final Answer:
When the task involves waiting for external resources like databases or APIs -> Option BQuick Check:
Async = I/O-bound tasks [OK]
- Choosing async for CPU-heavy tasks
- Thinking async makes code slower
- Using sync for I/O-bound tasks
Solution
Step 1: Recall Python async function syntax
Async functions start withasync deffollowed by the function name and parentheses.Step 2: Check each option's syntax
Only async def get_data(): return {'msg': 'Hello'} uses the correctasync defsyntax; others are invalid Python syntax.Final Answer:
async def get_data(): return {'msg': 'Hello'} -> Option DQuick Check:
Async function syntax = async def [OK]
- Placing async keyword after def
- Using 'def async' instead of 'async def'
- Incorrect order of keywords
from fastapi import FastAPI
import time
app = FastAPI()
@app.get('/sync')
def sync_endpoint():
time.sleep(2)
return {'message': 'Done'}
@app.get('/async')
async def async_endpoint():
await some_async_task()
return {'message': 'Done'}What is the main difference in behavior between
/sync and /async endpoints?Solution
Step 1: Understand sync endpoint behavior
Thesync_endpointusestime.sleep(2), which blocks the thread and stops handling other requests during that time.Step 2: Understand async endpoint behavior
Theasync_endpointusesawaiton an async task, allowing the server to handle other requests while waiting.Final Answer:
/sync blocks other requests during sleep; /async allows concurrent handling -> Option CQuick Check:
Sync blocks, async allows concurrency [OK]
- Assuming sync allows concurrency
- Thinking async blocks like sync
- Confusing await with blocking
@app.get('/data')
async def get_data():
result = time.sleep(1)
return {'result': result}What is the problem with this code?
Solution
Step 1: Identify blocking call in async function
time.sleep(1)is a blocking call that pauses the whole thread, including the async event loop.Step 2: Understand async best practices
In async functions, use non-blocking calls likeawait asyncio.sleep(1)to avoid blocking the event loop.Final Answer:
Using time.sleep inside async blocks the event loop, causing delays -> Option AQuick Check:
Blocking calls in async cause delays [OK]
- Trying to await time.sleep
- Ignoring blocking effect of time.sleep
- Thinking async auto makes code non-blocking
Solution
Step 1: Separate I/O-bound and CPU-bound tasks
Fetching data from an external API is I/O-bound and benefits from async to avoid blocking.Step 2: Handle CPU-heavy work properly
CPU-heavy processing blocks the event loop if run directly in async code, so it should run in a separate thread or process.Step 3: Combine async I/O with offloaded CPU work
Use async endpoint to await API call, then offload CPU work to thread/process to keep responsiveness.Final Answer:
Make the endpoint async to await the API call, then run CPU work in a separate thread or process -> Option AQuick Check:
Async for I/O + thread/process for CPU [OK]
- Running CPU work directly in async code
- Making endpoint fully sync causing blocking
- Mixing async and sync calls incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
