Bird
Raised Fist0
FastAPIframework~10 mins

Async vs sync decision in FastAPI - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Async vs sync decision
Request arrives
↓
Is handler async?
No→Run sync handler
↓
Process request
↓
Run async handler
↓
Send response
↓
Await async tasks
↓
End
↓
Send response
↓
End
When a request comes, FastAPI checks if the handler is async or sync. It runs async handlers with await, sync handlers directly, then sends the response.
Execution Sample
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/sync")
def sync_handler():
    return {"message": "sync response"}

@app.get("/async")
async def async_handler():
    return {"message": "async response"}
Defines two routes: one sync handler and one async handler, showing how FastAPI handles each.
Execution Table
StepRequest PathHandler TypeActionResponse Sent
1/syncsyncCall sync_handler directly{"message": "sync response"}
2/asyncasyncAwait async_handler coroutine{"message": "async response"}
3/syncsyncCall sync_handler directly{"message": "sync response"}
4/asyncasyncAwait async_handler coroutine{"message": "async response"}
5--No more requests-
💡 Execution stops when no more requests are received.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
request_path-/sync/async/sync/async-
handler_type-syncasyncsyncasync-
response-{"message": "sync response"}{"message": "async response"}{"message": "sync response"}{"message": "async response"}-
Key Moments - 2 Insights
Why does FastAPI await async handlers but call sync handlers directly?
Because async handlers return coroutines that must be awaited to run, while sync handlers run immediately. See execution_table steps 1 and 2.
Can a sync handler use await inside it?
No, sync handlers cannot use await. They run like normal functions. Async handlers can use await. This is shown by the different actions in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response sent at Step 2?
ANo response sent
B{"message": "async response"}
C{"message": "sync response"}
DError
💡 Hint
Check the Response Sent column at Step 2 in execution_table.
At which step does FastAPI await the async handler?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the Action column in execution_table for when 'Await async_handler coroutine' happens.
If the /sync handler was changed to async, what would change in the execution_table?
ANo change, it would still be sync
BThe response would be different
CThe handler_type would be 'async' and action would be 'Await async_handler coroutine' for /sync requests
DFastAPI would throw an error
💡 Hint
Refer to variable_tracker and execution_table showing handler_type and action per request path.
Concept Snapshot
FastAPI decides handler type by function definition:
- sync def: called directly
- async def: awaited
Async handlers allow non-blocking operations.
Sync handlers run immediately.
Use async for I/O-bound tasks.
Use sync for simple, fast operations.
Full Transcript
When FastAPI receives a request, it checks if the handler function is async or sync. If sync, it calls the function directly and returns the response. If async, it awaits the coroutine to complete before sending the response. This allows async handlers to perform non-blocking operations like waiting for database calls without blocking the server. Sync handlers run immediately and block until done. The execution table shows requests to /sync and /async paths, with FastAPI calling or awaiting handlers accordingly. Variables track the request path, handler type, and response sent at each step. Key moments clarify why async handlers must be awaited and why sync handlers cannot use await. The visual quiz tests understanding of these execution steps. This helps beginners see how FastAPI manages async vs sync decisions in real time.

Practice

(1/5)
1. In FastAPI, when should you choose an async function over a def synchronous function?
easy
A. When the task is CPU-heavy and requires intense calculations
B. When the task involves waiting for external resources like databases or APIs
C. When you want the function to run slower
D. When you want to block other tasks until this finishes

Solution

  1. Step 1: Understand async purpose in FastAPI

    Async functions let your app wait for external tasks like database calls without stopping other work.
  2. Step 2: Match task type to function type

    Waiting for external resources is I/O-bound, so async is best to avoid blocking.
  3. Final Answer:

    When the task involves waiting for external resources like databases or APIs -> Option B
  4. Quick Check:

    Async = I/O-bound tasks [OK]
Hint: Use async for waiting tasks, sync for CPU tasks [OK]
Common Mistakes:
  • Choosing async for CPU-heavy tasks
  • Thinking async makes code slower
  • Using sync for I/O-bound tasks
2. Which of the following is the correct way to define an asynchronous route handler in FastAPI?
easy
A. async get_data def(): return {'msg': 'Hello'}
B. def async get_data(): return {'msg': 'Hello'}
C. def get_data() async: return {'msg': 'Hello'}
D. async def get_data(): return {'msg': 'Hello'}

Solution

  1. Step 1: Recall Python async function syntax

    Async functions start with async def followed by the function name and parentheses.
  2. Step 2: Check each option's syntax

    Only async def get_data(): return {'msg': 'Hello'} uses the correct async def syntax; others are invalid Python syntax.
  3. Final Answer:

    async def get_data(): return {'msg': 'Hello'} -> Option D
  4. Quick Check:

    Async function syntax = async def [OK]
Hint: Async functions start with 'async def' in Python [OK]
Common Mistakes:
  • Placing async keyword after def
  • Using 'def async' instead of 'async def'
  • Incorrect order of keywords
3. Consider this FastAPI code snippet:
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?
medium
A. Both block other requests equally
B. /async blocks other requests; /sync allows concurrency
C. /sync blocks other requests during sleep; /async allows concurrent handling
D. Both allow full concurrency without blocking

Solution

  1. Step 1: Understand sync endpoint behavior

    The sync_endpoint uses time.sleep(2), which blocks the thread and stops handling other requests during that time.
  2. Step 2: Understand async endpoint behavior

    The async_endpoint uses await on an async task, allowing the server to handle other requests while waiting.
  3. Final Answer:

    /sync blocks other requests during sleep; /async allows concurrent handling -> Option C
  4. Quick Check:

    Sync blocks, async allows concurrency [OK]
Hint: Sync blocks during wait; async frees server to handle others [OK]
Common Mistakes:
  • Assuming sync allows concurrency
  • Thinking async blocks like sync
  • Confusing await with blocking
4. You wrote this FastAPI route:
@app.get('/data')
async def get_data():
    result = time.sleep(1)
    return {'result': result}

What is the problem with this code?
medium
A. Using time.sleep inside async blocks the event loop, causing delays
B. Missing await keyword before time.sleep
C. Function should not be async if it returns a dictionary
D. No problem; code works fine

Solution

  1. 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.
  2. Step 2: Understand async best practices

    In async functions, use non-blocking calls like await asyncio.sleep(1) to avoid blocking the event loop.
  3. Final Answer:

    Using time.sleep inside async blocks the event loop, causing delays -> Option A
  4. Quick Check:

    Blocking calls in async cause delays [OK]
Hint: Never use time.sleep in async; use await asyncio.sleep instead [OK]
Common Mistakes:
  • Trying to await time.sleep
  • Ignoring blocking effect of time.sleep
  • Thinking async auto makes code non-blocking
5. You have a FastAPI app that fetches data from a slow external API and then processes it heavily with CPU calculations. How should you design your endpoint for best performance?
hard
A. Make the endpoint async to await the API call, then run CPU work in a separate thread or process
B. Make the endpoint fully async and run CPU work directly inside it
C. Make the endpoint synchronous and run both API call and CPU work sequentially
D. Use synchronous endpoint but call the API asynchronously

Solution

  1. 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.
  2. 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.
  3. 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.
  4. Final Answer:

    Make the endpoint async to await the API call, then run CPU work in a separate thread or process -> Option A
  5. Quick Check:

    Async for I/O + thread/process for CPU [OK]
Hint: Async for waiting; thread/process for CPU work [OK]
Common Mistakes:
  • Running CPU work directly in async code
  • Making endpoint fully sync causing blocking
  • Mixing async and sync calls incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard