Choosing between async and sync helps your FastAPI app handle tasks efficiently. Async lets your app do many things at once, while sync does one thing at a time.
Async vs sync decision in FastAPI
async def function_name(): # async code here def function_name(): # sync code here
Use async def to define asynchronous functions.
Use regular def for synchronous functions.
from fastapi import FastAPI app = FastAPI() @app.get("/sync") def read_sync(): return {"message": "This is sync"}
await.from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/async") async def read_async(): await asyncio.sleep(1) return {"message": "This is async"}
This FastAPI app has two endpoints. The /sync endpoint blocks for 1 second, stopping other tasks. The /async endpoint waits 1 second without blocking, letting other tasks run.
from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/sync") def sync_endpoint(): # Simulate a blocking task import time time.sleep(1) return {"message": "Finished sync task"} @app.get("/async") async def async_endpoint(): # Simulate a non-blocking task await asyncio.sleep(1) return {"message": "Finished async task"}
Async is great for waiting on slow tasks like network calls.
Sync is simpler and good for quick or CPU-heavy tasks.
Mixing async and sync incorrectly can cause problems; keep your code consistent.
Async lets your app handle many things at once by waiting without blocking.
Sync runs tasks one after another and can block other work.
Choose async for I/O-bound tasks and sync for CPU-bound or simple tasks.
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
