Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 143/ 160
08. Backend

Async and Await

Non-blocking I/O patterns essential for calling LLM APIs efficiently.

BeginnerEvent Loop · Concurrency3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Async lets a program start a slow task, like asking an AI model a question, and do other work while it waits, instead of standing still until the answer comes back.

Think of it like…

A waiter serving many tables. They take an order, hand it to the kitchen (await) and move on instead of standing at the pass; the kitchen's slowness doesn't stop them serving others, but if the waiter personally cooks a dish (a blocking call) every table waits.

Where you’ve seen it

A RAG endpoint needs five independent look-ups, each about 1.2 seconds (two vector searches, a keyword search, a user profile and a feature flag). Awaiting them one after another takes 5 × 1.2 = 6.0 seconds; running them with asyncio.gather takes about 1.2 seconds, the slowest single call. A nightly job summarises 100 documents at 2 seconds per model call: sequentially that is 200 seconds, but with an asyncio.Semaphore(10) only ten calls run at once, so the job needs ceil(100 / 10) = 10 waves × 2 s = 20 seconds, and the cap keeps it under the provider's rate limit (raising it to 100 would finish in about 2 seconds but trigger throttling and 429 retries). A bug found in review: a handler called requests.get (blocking) inside an async def; each call blocked the loop for 500 ms, so with 300 concurrent requests everything stalled in bursts and p95 latency rose from 3.5 s to 9 s; replacing it with httpx.AsyncClient fixed it, and the few unavoidable blocking functions (PDF parsing) now run through asyncio.to_thread. Each outbound call has an asyncio.timeout(20), and a client disconnect cancels the in-flight model call so tokens aren't paid for after the user leaves. Failures are handled deliberately: gather(..., return_exceptions=True) lets optional look-ups (the feature flag) fail without discarding the results of the required ones, while a TaskGroup cancels siblings when a critical task fails.

Words you’ll hear

Coroutine
A function defined with async def that can be paused at each await.
Event loop
The scheduler that runs ready coroutines while others wait on I/O.
Fan-out
Starting independent tasks together and awaiting all of them.
Semaphore
A counter that limits how many tasks may run at once.

Visual diagram

Loading interactive diagram

Theory & deep dive

How async works and when it helps

A coroutine runs until it hits await, where it hands control back to the event loop; when the awaited operation (a socket read, a sleep) completes, the loop resumes the coroutine. Everything happens on one thread, so there are no data races between awaits, but also no parallel CPU work. Async therefore helps I/O-bound workloads: with a 3.4-second model call that uses a few milliseconds of CPU, one process can interleave hundreds of calls. It does not speed up CPU-bound work such as embedding computation in Python, JSON parsing of huge payloads or PDF rendering; use processes, a worker pool or native libraries for those.

Fan-out is the main performance pattern. Independent calls (two vector searches, a keyword search and a profile look-up at 1.2 seconds each) cost max(1.2, ...) = 1.2 seconds when started together versus 6.0 seconds when awaited serially. Dependent steps (retrieve, then rerank, then generate) stay sequential, so the end-to-end time is the sum along the critical path. Draw the dependency graph before parallelising and measure the improvement; a handler that fans out ten calls but waits on the slowest still has that tail latency.

Critical path

Retrieval fan-out 1.2 s → rerank 0.4 s → generation 3.4 s = 5.0 s end to end. Running the five look-ups serially instead would add 4.8 s to reach 9.8 s. Parallelising generation with retrieval is impossible because it depends on the retrieved chunks.

Key takeaway: Async removes waiting, not computation: fan out independent I/O and keep dependent steps in order.

Concurrency limits, timeouts, cancellation and pitfalls

Cap concurrency with a semaphore or a worker pool: 100 documents at 2 seconds with Semaphore(10) finish in 10 waves of 2 seconds, 20 seconds in total, instead of 200 seconds; an unlimited fan-out of 100 would finish in about 2 seconds but exceed provider rate limits, produce a storm of 429 responses and waste time on retries. Choose the cap from the provider's rate limit and your latency target, and share a single limiter across the process so separate handlers don't each assume they own the budget. Use timeouts on every outbound call (asyncio.timeout(20)), and cancellation to stop work the user no longer needs: when a client disconnects, cancel the model call so you stop paying for tokens.

Pitfalls: blocking calls inside async def (requests, time.sleep, synchronous database drivers, heavy parsing) stall the whole loop, so every other request waits (a 500 ms block across 300 concurrent requests lifts p95 from 3.5 s to 9 s in the example); use async clients, or asyncio.to_thread for unavoidable blocking code. A forgotten await leaves a coroutine object that never runs. Fire-and-forget tasks may be garbage collected or lose exceptions, so keep references and log failures. Shared mutable state between awaits still needs care. Exception handling: gather(..., return_exceptions=True) returns exceptions as values for optional work, while TaskGroup cancels siblings on the first failure, which suits all-or-nothing steps. Enable debug mode in tests to detect slow callbacks.

Semaphore arithmetic

100 documents, 2 s each. Limit 1: 200 s. Limit 10: ceil(100 / 10) × 2 = 20 s. Limit 50: 2 waves × 2 s = 4 s but 50 simultaneous calls may exceed a 25-requests-per-second provider limit. Pick the largest limit the provider tolerates.

Key takeaway: Bound concurrency, time out and cancel, and keep blocking code off the event loop.

How it works, step by step

Step 1 of 4
Backend engineer

1. Map dependencies

List which calls are independent and which depend on earlier results; the dependent chain is the critical path.

retrieve 1.2 s → rerank 0.4 s → generate 3.4 s
Key numbers at this step
Parallelise
independent calls

When to use it & trade-offs

What it is

Async/await lets one thread run many I/O-bound tasks by yielding at every wait. An async def function is a coroutine; await suspends it until a network response, a database row or a timer is ready, and the event loop meanwhile runs other coroutines. LLM backends spend almost all of their time waiting (a model call is 3 to 30 seconds of network, almost no CPU), so an async server can hold hundreds or thousands of concurrent calls on one process. The core tools are asyncio.gather and task groups for fan-out, a semaphore to cap concurrency, timeouts and cancellation for control, and asyncio.to_thread for the blocking or CPU-heavy work that must not run on the loop.

Why it matters: Concurrency is the main lever for latency and throughput in AI systems: retrieval, reranking and tool calls that are independent should run together, batch jobs should process many documents at once without breaching provider limits and a web server should not tie up a thread for every slow model call. The same technology has sharp edges: one blocking call freezes every request on the loop, unbounded fan-out triggers provider rate limits and a missing timeout lets a stuck call hold resources indefinitely.

When to reach for it

  • Fan-out retrieval, reranking inputs and profile look-ups
  • Batch summarisation with a concurrency cap
  • Servers that hold many slow model calls open

When to avoid or be careful

  • Blocking calls inside async functions
  • Unbounded fan-out against a rate-limited provider
  • Fire-and-forget tasks with no reference or error handling

Concurrency models

async/await (one event loop)
Best for: Many concurrent I/O waits such as LLM calls

Strengths: Thousands of waits per process; low overhead.

Watch out: No CPU parallelism; blocking calls hurt everyone.

Threads
Best for: Blocking libraries and modest concurrency

Strengths: Simple with sync code.

Watch out: Memory per thread; limited scale.

Processes or workers
Best for: CPU-bound work such as parsing and embedding

Strengths: True parallelism.

Watch out: More memory; inter-process communication.

Interview signals & numbers to know

When this topic comes up

  • “Why is async important for LLM backends?”
  • gather versus sequential awaits
  • Using a semaphore to respect rate limits
  • How blocking calls hurt the event loop
  • Handling timeouts and cancellation

Benchmarks & rules of thumb

6.0 s → 1.2 s -
five 1.2 s calls awaited serially versus concurrently
200 s → 20 s -
100 two-second calls with Semaphore(10)
500 ms -
one blocking call that stalled 300 concurrent requests in the example

Common mistakes & follow-ups

Common interview mistakes

  • Using requests or time.sleep inside an async handler.
  • Launching hundreds of concurrent calls without a limit.
  • Forgetting to await a coroutine.

Likely interviewer follow-ups

  • How would you process 10,000 documents within a provider's rate limit?
  • How do you stop paying for a request after the client disconnects?
  • When would you use threads or processes instead?
Interview tip: Draw the dependency graph and quote the critical path; it shows you know async helps only where calls are independent.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Async and Await with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
HTTP and Status Codes
Next topic
Streaming with SSE