FastAPI interview question · Most asked
Can you use synchronous SQLAlchemy with FastAPI? What are the trade-offs?
Summary
Yes: use plain def endpoints and a sync session dependency, and FastAPI runs them in a threadpool. It's simpler and mature, but concurrency is limited by the threadpool size (about 40 by default via AnyIO) and the DB pool.
Longer Answer
Never call a sync session from async def, because it blocks the loop. Mixing styles is fine per endpoint. You can raise the AnyIO thread limiter if needed. For high-concurrency, I/O-heavy services, async drivers scale better.
Key Points
- Sync DB →
defendpoints - Threadpool capacity limits concurrency
- Never use sync sessions in
async def
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?