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'}
The sync endpoint uses time.sleep, which blocks the server thread, preventing other requests from running concurrently on that thread. The async endpoint uses await asyncio.sleep, which allows the event loop to switch tasks and handle other requests concurrently.
Option D correctly defines an async function without blocking calls. Option D uses 'await' inside a sync function, causing a syntax error. Option D uses blocking time.sleep inside async, which blocks the event loop. Option D uses 'await' outside async function, causing syntax error.
from fastapi import FastAPI import time import asyncio app = FastAPI() @app.get('/block') async def block_endpoint(): time.sleep(2) return {'status': 'done'}
Using time.sleep inside an async function blocks the entire event loop, so all requests wait for the blocking call to finish, resulting in sequential processing.
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'}
time.sleep is a blocking call and should not be used inside async functions. It pauses the event loop, causing slow responses.
Async endpoints help with I/O-bound tasks by allowing concurrency. CPU-bound tasks block the event loop and do not benefit from async, so sync endpoints are better for CPU-heavy work.