Performance: Async generator dependencies
This affects server response time and resource management during request handling in FastAPI.
async def get_db(): db = await async_create_db_connection() try: yield db finally: await db.aclose()
def get_db(): db = create_db_connection() try: yield db finally: db.close()
| Pattern | Event Loop Blocking | Resource Cleanup | Concurrency Impact | Verdict |
|---|---|---|---|---|
| Sync generator dependency | Blocks event loop | Synchronous cleanup | Reduces concurrency | [X] Bad |
| Async generator dependency | Non-blocking | Async cleanup | Maximizes concurrency | [OK] Good |
async generator dependency in FastAPI?async def with yield to run setup code before yielding and cleanup code after.async def and yield inside the function body.async def and yield, which is correct. Options A and B are synchronous, and C uses return instead of yield.async def resource():
print('Setup')
yield 'data'
print('Cleanup')
@app.get('/')
async def read(resource=Depends(resource)):
print('Inside endpoint')
return resourceasync def resource():
connection = await connect_db()
yield connection
await connection.close()
@app.get('/')
async def read(conn=Depends(resource)):
return {'status': 'ok'}await connection.close() might not run, causing resource leaks.await conn.close() runs after yield, even on exceptions.Pass the test and this pattern moves unknown