Bird
Raised Fist0
FastAPIframework~20 mins

Async vs sync decision in FastAPI - Practice Questions

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async vs Sync Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when mixing async and sync endpoints in FastAPI?
Consider a FastAPI app with one async endpoint and one sync endpoint. What happens when both are called concurrently?
FastAPI
from fastapi import FastAPI
import time
import asyncio

app = FastAPI()

@app.get('/sync')
def sync_endpoint():
    time.sleep(1)
    return {'message': 'sync done'}

@app.get('/async')
async def async_endpoint():
    await asyncio.sleep(1)
    return {'message': 'async done'}
ABoth endpoints block independently; sync blocks the server thread, async allows concurrency.
BBoth endpoints run concurrently without blocking each other.
CSync endpoint runs asynchronously, async endpoint runs synchronously.
DBoth endpoints block the server and cause a deadlock.
Attempts:
2 left
💡 Hint
Think about how Python handles time.sleep vs asyncio.sleep in FastAPI.
📝 Syntax
intermediate
2:00remaining
Which FastAPI endpoint definition is correct for async behavior?
Select the correct FastAPI endpoint definition that properly uses async syntax.
A@app.get('/data')\ndef get_data():\n return {'data': await some_async_call()}
B@app.get('/data')\ndef get_data():\n await some_async_call()\n return {'data': 'async'}
C@app.get('/data')\nasync def get_data():\n time.sleep(1)\n return {'data': 'async'}
D@app.get('/data')\nasync def get_data():\n return {'data': 'async'}
Attempts:
2 left
💡 Hint
Remember that 'await' can only be used inside async functions.
❓ state_output
advanced
2:00remaining
What is the output of this FastAPI async endpoint with blocking code?
Analyze the output and behavior of this endpoint when called multiple times concurrently.
FastAPI
from fastapi import FastAPI
import time
import asyncio

app = FastAPI()

@app.get('/block')
async def block_endpoint():
    time.sleep(2)
    return {'status': 'done'}
AThe endpoint raises a RuntimeWarning but returns immediately.
BRequests run concurrently without blocking despite time.sleep usage.
CEach request blocks the event loop for 2 seconds, causing all requests to be processed sequentially.
DThe server crashes due to mixing sync blocking code in async function.
Attempts:
2 left
💡 Hint
Consider what happens when blocking code runs inside an async function.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI async endpoint cause slow responses?
Identify the cause of slow responses in this async endpoint code.
FastAPI
from fastapi import FastAPI
import time
import asyncio

app = FastAPI()

@app.get('/slow')
async def slow_endpoint():
    for _ in range(3):
        time.sleep(1)
    return {'message': 'done'}
AThe for loop is not awaited causing the function to run synchronously.
BUsing time.sleep inside async blocks the event loop causing slow responses.
CMissing await before time.sleep causes the function to hang.
DThe endpoint lacks async keyword causing slow execution.
Attempts:
2 left
💡 Hint
Check which calls block the event loop in async functions.
🧠 Conceptual
expert
2:00remaining
When should you choose sync over async endpoints in FastAPI?
Select the best scenario to use synchronous endpoints instead of asynchronous ones in FastAPI.
AWhen the endpoint performs CPU-bound tasks that do not benefit from async concurrency.
BWhen the endpoint makes many network calls that support async operations.
CWhen you want to maximize concurrency for I/O-bound tasks.
DWhen the endpoint uses async libraries exclusively.
Attempts:
2 left
💡 Hint
Think about the nature of the task: CPU-bound vs I/O-bound.

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