When to use async in FastAPI: how it works, asyncio, Starlette, Pydantic, Flask, React

When to use async def in FastAPI and why it is async, how it uses asyncio, Starlette and Pydantic, FastAPI vs Flask, mixing it with Django, and using React.

On the mic
On the mic

Key takeaways

  • Use async def when your endpoint awaits async I/O, such as async database drivers, HTTP clients or streaming.
  • Use plain def for blocking code; FastAPI runs it in a thread pool so it does not block the event loop.
  • FastAPI is async because it is built on Starlette and ASGI, which handle many concurrent connections efficiently.
  • Pydantic validates request data, serialises responses and generates the OpenAPI schema.
  • FastAPI suits APIs and AI services; Flask suits simple sync apps; React front ends call FastAPI over HTTP.

Use async in FastAPI when your endpoint spends time waiting on I/O that has async libraries, such as calling AI model APIs with an async HTTP client, querying databases through async drivers, or streaming responses; write async def and await those calls. For blocking libraries, use plain def, and FastAPI runs it in a thread pool. FastAPI powers the back ends of my AI products, including FaceVision's embedding service, so this page covers async decisions, how it works, Starlette and Pydantic, Flask, Django and React.

When should I use async in FastAPI?

Use async when handling many concurrent requests that mostly wait on network or disk I/O: calling external APIs such as language models, querying databases with async drivers, reading from caches, and streaming data. Async lets one process serve many waiting requests efficiently.

Also asked as: when to use async fastapi

Do not use async for CPU-heavy work, such as image processing or running local models, which blocks the event loop; offload that to worker processes, background task queues or thread pools. For simple CRUD apps with low traffic, sync code is fine. Async shines in AI services, where requests often wait seconds for model responses, and in real-time features like WebSockets. FineTune Studio, for example, streams live training loss to the browser over WebSockets, a natural fit for async endpoints.

When should I use async def in FastAPI?

Use async def when everything inside the endpoint that waits is awaitable, for example await client.get() with httpx or await session.execute() with an async database driver. Use plain def when you call blocking libraries, such as the standard requests library or a sync database driver.

Also asked as: when to use async def fastapi

The key mistake is calling blocking code inside async def, which freezes the event loop and slows every request. If you must call blocking code in an async endpoint, use run_in_threadpool or asyncio.to_thread. When unsure, plain def is safe because FastAPI runs it in a thread pool automatically, while still performing well for many applications.

Why is FastAPI async?

FastAPI is async because it is built on Starlette and the ASGI standard, designed for Python's async and await features. This lets a single server process handle thousands of concurrent connections, such as slow API calls, long-polling and WebSockets, without a thread per request.

Also asked as: how fastapi async works

Async matters most for I/O-bound services, which is most web APIs: they spend their time waiting for databases, networks and other services. By switching between requests while each waits, the event loop keeps CPUs busy and latency low. FastAPI still supports sync endpoints, so you can adopt async gradually where it helps.

How does async work in FastAPI?

An ASGI server such as Uvicorn runs an event loop. When an async def endpoint awaits I/O, it yields control, letting the loop process other requests; when the I/O completes, the endpoint resumes. Sync def endpoints run in a thread pool so they do not block the loop.

Dependencies can also be async or sync, and FastAPI resolves them before calling your endpoint. Background tasks run after the response is sent. For streaming, StreamingResponse with an async generator sends data as it is produced, ideal for streaming language model tokens to users, as RAG.NextUpgrad does with cited answers.

Does FastAPI use asyncio?

Yes. FastAPI runs on asyncio by default through Starlette and the AnyIO library, which also supports the Trio event loop. You write standard async and await code, and the ASGI server manages the asyncio event loop.

You can use asyncio features inside endpoints, such as asyncio.gather to run several API calls concurrently, timeouts with asyncio.wait_for, and async libraries like httpx, asyncpg and redis-py's asyncio client. Avoid creating your own event loops inside endpoints; work within the one the server provides. For example, a RAG endpoint can run keyword and vector searches concurrently with asyncio.gather, cutting retrieval latency roughly to that of the slower search rather than the sum of both.

Does FastAPI use Starlette?

Yes. FastAPI is built on top of Starlette, a lightweight ASGI framework that provides routing, requests and responses, middleware, WebSockets, background tasks and static files. FastAPI adds data validation, dependency injection and automatic API documentation on top.

Because of this, Starlette features work directly in FastAPI: custom middleware, StreamingResponse, FileResponse and WebSocket endpoints. Knowing Starlette helps when you need lower-level control, such as custom middleware for logging or authentication. Performance largely comes from Starlette and the ASGI server underneath.

How does FastAPI use Pydantic?

FastAPI uses Pydantic models to validate and parse request data, such as JSON bodies, query parameters and headers, converting types automatically and returning clear 422 errors for invalid input. It also uses Pydantic for response models, filtering and serialising output.

From the same models, FastAPI generates the OpenAPI schema, which powers the interactive documentation at /docs. Pydantic version 2, with its Rust-based core, made validation much faster. Use separate models for input, database records and output, so internal fields such as password hashes never leak into API responses.

When should I use FastAPI vs Flask?

Choose FastAPI for APIs needing validation, automatic documentation, async I/O, high concurrency or streaming, including AI and machine learning services. Choose Flask for simple, synchronous web apps, quick prototypes, or projects relying on Flask's large extension ecosystem.

Also asked as: when to use fastapi vs flask

FastAPI's type-hint-driven design reduces boilerplate and catches errors early, and its generated docs help front-end teams. Flask is minimal and flexible, with many tutorials and extensions for templates, authentication and admin panels. For new API-first projects, especially those calling language models, FastAPI is usually the better default. Flask has added async support, but FastAPI was designed around it from the start.

Can I use Django and FastAPI together?

Yes. Common patterns include running Django for the admin panel, ORM and traditional pages, and FastAPI for high-performance or async API endpoints, either as separate services sharing a database, or by mounting both under one ASGI application.

Also asked as: can you use django and fastapi together

Using Django's ORM inside FastAPI requires care, since it is mostly synchronous; run ORM calls in a thread pool or use its async query methods where available. Many teams find it simpler to keep them as separate services. A gradual migration is also common: keep existing Django pages running and build new API features in FastAPI, sharing authentication through tokens. Alternatively, Django Ninja offers a FastAPI-like API style within Django itself.

Can I use FastAPI with React?

Yes, it is a popular stack: FastAPI serves a JSON API, and a React front end, built with Vite or Next.js, calls it over HTTP. Enable CORS in FastAPI for your front-end origin during development and in production if domains differ.

Practical setup: define Pydantic models for API contracts, generate TypeScript types from FastAPI's OpenAPI schema, use authentication with tokens or cookies, and deploy the front end to a static or Next.js host and FastAPI to a server or container platform. For AI features, stream responses from FastAPI to React to show answers as they generate.

Sources

  1. FastAPI, Concurrency and async / awaitfastapi.tiangolo.com
  2. FastAPI, documentationfastapi.tiangolo.com
  3. Pydantic, documentationdocs.pydantic.dev
  4. Python Docs, asynciodocs.python.org
  5. Flask, documentationflask.palletsprojects.com
Pranjul Rathour
Pranjul Rathour
GenAI Engineer · India

GenAI engineer and AI product builder with 2+ years shipping production-grade AI systems: RAG pipelines, fine-tuned LLMs, hybrid retrieval and multi-modal apps across vision, speech and OCR, architected end to end from ingestion to deployment. Leads engineering for SCULT INDIA's 14-member team, founded the 500+ member TechVerse Enclave community and has mentored 200+ students. Three hackathon first prizes: Changethon 2025 (IIT Roorkee), Product Genesis at Vividhotsava 2025 (CSJMU) and BYTEBATTLE (MeetKats).

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way. Email pranjulrathour41@gmail.com.

Keep reading

More on Shipping AI apps

All Shipping AI apps guides →
Campus talks · hackathon judging · mentoring

Want this as a live session at your college?

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way.

Pranjul Rathour, GenAI engineer in India