Why Your FastAPI Endpoint Looks Fine Locally but Collapses Under Concurrency: Catching N+1 Queries and Event-Loop Blocking with OpenTelemetry
One of the most frustrating performance bugs in Python web services is the endpoint that feels completely fine when you hit it with curl during development, then falls off a cliff the moment 20 users hit it at once.
In FastAPI, this usually happens when two quiet mistakes stack on top of each other inside an async def route:
- An N+1 query pattern using a synchronous database driver that blocks the asyncio event loop on every iteration.
- Synchronous CPU work (hashing, signing, PDF/JSON crunching) executed directly on the event loop thread.
In this post, we will build a small, zero-Docker FastAPI service instrumented with OpenTelemetry, reproduce the concurrency collapse locally, inspect the trace waterfall, and verify the fix with both unit tests and a 20-request concurrent benchmark.
All code in this article is runnable locally with Python 3.12 and SQLite. Repository: https://github.com/ruiheng903-ux/fastapi-otel-latency-lab
The Setup: One Endpoint, Two Implementations
Our service exposes a user billing summary endpoint (GET /users/summary?limit=40). Given a SQLite database seeded with 200 users and 4,000 orders, it returns each user's paid order count, total spend, and a per-record SHA-256 PBKDF2 audit digest.
We will implement two routes that return the exact same JSON payload:
-
GET /v1/users/summary— the naiveasync defroute with blockingsqlite3N+1 queries and inline PBKDF2 hashing. -
GET /v2/users/summary— a singleaiosqliteLEFT JOIN ... GROUP BYquery combined withasyncio.to_thread()for the digest batch.
Wiring Up Local OpenTelemetry Tracing
You do not need a full Jaeger or SigNoz cluster just to inspect span waterfalls while debugging locally. OpenTelemetry's InMemorySpanExporter lets you capture spans inside your process, assert on span counts in pytest, and summarize trace waterfalls in your benchmark script:
# app/telemetry.py from opentelemetry import trace from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter _exporter = InMemorySpanExporter() _configured = False def configure_telemetry(service_name: str = "fastapi-latency-lab") -> trace.Tracer: global _configured if not _configured: resource = Resource.create({"service.name": service_name}) provider = TracerProvider(resource=resource) provider.add_span_processor(SimpleSpanProcessor(_exporter)) trace.set_tracer_provider(provider) _configured = True return trace.get_tracer(service_name) In production, you swap SimpleSpanProcessor(_exporter) for BatchSpanProcessor(OTLPSpanExporter()) pointing at SigNoz, Honeycomb, or Grafana Tempo—none of the route instrumentation changes.
The Naive Route (/v1/users/summary)
Here is a pattern that slips into production codebases all the time—often because an existing synchronous data-access module gets called from a newly written async def FastAPI handler:
@app.get("/v1/users/summary") async def get_users_summary_v1(limit: int = Query(default=40, ge=1, le=200)): with tracer.start_as_current_span("db.fetch_users_sync") as span: span.set_attribute("db.system", "sqlite") span.set_attribute("db.query.pattern", "select_users") users = fetch_users_sync(limit) span.set_attribute("app.users.count", len(users)) results = [] for user in users: with tracer.start_as_current_span("db.fetch_user_orders_sync") as span: span.set_attribute("db.system", "sqlite") span.set_attribute("db.query.pattern", "n_plus_one") span.set_attribute("app.user.id", user["id"]) stats = fetch_user_order_stats_sync(user["id"]) with tracer.start_as_current_span("cpu.compute_audit_digest_blocking"): digest = compute_audit_digest( user["id"], stats["total_cents"], stats["order_count"] ) results.append({**user, **stats, "audit_digest": digest}) return {"version": "v1", "count": len(results), "items": results} Why Single-Request Testing Hides the Problem
When you hit /v1/users/summary?limit=40 once on localhost, the request completes in ~227 ms. That rarely triggers alarm bells during code review.
Look at the OpenTelemetry waterfall for that single trace, however:
[ { "name": "GET /v1/users/summary", "offset_ms": 0.0, "duration_ms": 227.07 }, { "name": "db.fetch_users_sync", "offset_ms": 0.98, "duration_ms": 0.98 }, { "name": "db.fetch_user_orders_sync", "offset_ms": 2.93, "duration_ms": 0.98 }, { "name": "cpu.compute_audit_digest_blocking", "offset_ms": 3.91, "duration_ms": 2.93 }, { "name": "db.fetch_user_orders_sync", "offset_ms": 6.84, "duration_ms": 1.96 }, { "name": "cpu.compute_audit_digest_blocking", "offset_ms": 8.79, "duration_ms": 3.91 } ] Every single request generates 84 spans (1 ASGI root span, 2 HTTP send spans, 1 user list query, 40 per-user SQL queries, and 40 blocking PBKDF2 spans). Worse, because the route is declared async def and never yields to the event loop (await), FastAPI executes the entire 227 ms synchronously on the main event loop thread.
When 20 clients arrive simultaneously, request #20 sits in line behind 19 other requests—turning a 227 ms endpoint into a 5-second tail latency spike.
The Fix (/v2/users/summary)
We fix both bottlenecks in two targeted changes:
1. Collapse 41 Blocking Queries into 1 Async LEFT JOIN
Instead of looping over users in Python, let SQLite aggregate the rows in a single non-blocking aiosqlite query:
async def fetch_user_summaries_batched(limit: int, db_path: Path = DB_PATH): async with aiosqlite.connect(db_path) as conn: conn.row_factory = aiosqlite.Row async with conn.execute( """ SELECT u.id, u.name, u.tier, COUNT(o.id) AS order_count, COALESCE(SUM(o.amount_cents), 0) AS total_cents FROM users u LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid' WHERE u.id IN ( SELECT id FROM users ORDER BY id ASC LIMIT ? ) GROUP BY u.id, u.name, u.tier ORDER BY u.id ASC """, (limit,), ) as cursor: rows = await cursor.fetchall() return [dict(r) for r in rows] 2. Offload CPU-Bound Digest Work Off the Event Loop
hashlib.pbkdf2_hmac runs in C/OpenSSL and releases Python's GIL while hashing. Moving the batch computation into asyncio.to_thread() frees the event loop to accept and serve other requests while worker threads run the digests in parallel across CPU cores:
@app.get("/v2/users/summary") async def get_users_summary_v2(limit: int = Query(default=40, ge=1, le=200)): with tracer.start_as_current_span("db.fetch_user_summaries_batched") as span: span.set_attribute("db.system", "sqlite") span.set_attribute("db.query.pattern", "batched_join") rows = await fetch_user_summaries_batched(limit) span.set_attribute("app.users.count", len(rows)) with tracer.start_as_current_span("cpu.compute_audit_digests_offloaded") as span: span.set_attribute("app.batch.size", len(rows)) results = await asyncio.to_thread(compute_digests_batch, rows) return {"version": "v2", "count": len(results), "items": results} Guarding Against Regressions with pytest
Before benchmarking, we write two tests: one proving /v1 and /v2 return byte-for-byte identical business records, and another asserting on OpenTelemetry span counts so an N+1 query cannot silently sneak back in during a future refactor:
def test_v2_eliminates_n_plus_one_span_explosion() -> None: with TestClient(app) as client: clear_spans() client.get("/v1/users/summary?limit=20") v1_spans = [s for s in get_finished_spans() if s.name.startswith(("db.", "cpu."))] clear_spans() client.get("/v2/users/summary?limit=20") v2_spans = [s for s in get_finished_spans() if s.name.startswith(("db.", "cpu."))] assert len(v1_spans) == 41 assert len(v2_spans) == 2 Running pytest -v:
tests/test_api.py::test_v1_and_v2_return_identical_payloads PASSED [ 50%] tests/test_api.py::test_v2_eliminates_n_plus_one_span_explosion PASSED [100%] ======================== 2 passed in 1.60s ========================= Real Concurrent Benchmark Results
Running python benchmark.py launches Uvicorn locally and fires 20 concurrent requests (limit=40) against each version using httpx.AsyncClient:
=== Concurrent Benchmark Results (20 concurrent requests, limit=40) === Metric v1 (Naive) v2 (Optimized) Improvement -------------------------------------------------------------------------- Total Wall Time (ms) 5145.43 1190.65 4.32x p50 Latency (ms) 2582.41 808.80 3.19x p95 Latency (ms) 5064.40 1146.24 4.42x Max Latency (ms) 5064.40 1146.24 4.42x Throughput (req/s) 3.89 16.80 4.32x Avg Spans / Trace 84.00 5.00 - Look closely at the /v2 trace waterfall as well:
[ { "name": "db.fetch_user_summaries_batched", "offset_ms": 0.0, "duration_ms": 5.26 }, { "name": "GET /v2/users/summary", "offset_ms": 0.0, "duration_ms": 257.33 }, { "name": "cpu.compute_audit_digests_offloaded", "offset_ms": 5.26, "duration_ms": 251.08 } ] Notice two practical takeaways here:
- Concurrent throughput jumped 4.32x and p95 latency dropped 4.42x (from 5.06 seconds down to 1.15 seconds), even though an individual request's compute time stayed around ~250 ms. Removing event-loop blocking unlocked parallel execution across threads.
- Telemetry volume dropped by 94% (from 84 spans per trace down to 5). If you pay per ingested span or per GB of trace storage in your observability backend, fixing N+1 queries cuts your APM bill at the same time it cuts p95 latency.
Key Takeaways
- Never trust single-request latency in an
async defFastAPI endpoint. Always test with at least 10–20 concurrent clients so event-loop starvation shows up in p95/max latency. - Assert on OpenTelemetry span counts in CI. Using
InMemorySpanExporterinpytestturns distributed tracing from a post-incident forensics tool into an automated N+1 regression guard. - Know when
asyncio.to_threadhelps. It works well for blocking I/O and C-extension CPU work that releases the GIL (likehashlib,zlib, or NumPy). For pure-Python CPU loops, reach forProcessPoolExecutoror an external worker queue instead.