Repository navigation
Run /search in the threadpool instead of blocking the event loop - #9
Merged
Merged
Conversation
/search and the /mcp tool handler were `async def` but did blocking I/O (psycopg2 queries + a ~1s OpenAI embedding call). Blocking calls in an async route run on the event loop, so each instance processed these requests one at a time. Under AWS App Runner's per-instance concurrency (default MaxConcurrency=100) this serialization is what produced the 502/503/504 (health-check failures, recycling, request-timeout) and the rare 429 (scale-out load-shedding). Make `search` a plain sync `def` so FastAPI runs it in its worker threadpool (concurrent requests run in parallel), and have the async /mcp handler offload to the threadpool via run_in_threadpool. Measured: 16 concurrent /search calls went from ~17s wall (p50 12s, serialized) toward threadpool-parallel behavior matching /graph/embedding (already a sync def), which stays ~1s flat under the same load. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This was referenced Jun 5, 2026
There was a problem hiding this comment.
Pull request overview
This PR addresses App Runner 502/503/504/429s caused by blocking I/O inside async request handlers by ensuring /search work runs in FastAPI’s worker threadpool instead of the event loop.
Changes:
- Converted
/searchfromasync defto syncdefso blocking psycopg2 + embedding calls execute in FastAPI’s threadpool. - Updated the async
/mcphandler to offload the search call viarun_in_threadpool(...). - Added a lock around lazy OpenAI client initialization to avoid concurrent cold-start races.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| api/routes/search.py | Makes /search synchronous (threadpool execution) and adds thread-safe OpenAI client lazy-init. |
| api/routes/mcp.py | Offloads search execution to the threadpool to keep the MCP handler non-blocking. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @@ -10,14 +11,21 @@ | |||
| router = APIRouter() | |||
|
|
|||
| _openai_client: OpenAI = None | |||
Comment on lines
234
to
236
| try: | ||
| with rds_conn() as conn, conn.cursor() as cur: | ||
| cur.execute( |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The core fix for the 502/503/504/429 errors
/searchand the/mcptool handler wereasync defbut did blocking I/O (psycopg2 queries + a ~1s OpenAI/Nebius embedding call). Blocking calls inside anasyncroute run on the event loop, so each container instance processed these requests one at a time.The API runs on AWS App Runner, which routes up to
MaxConcurrency(default 100) concurrent requests to a single instance. With the handlers serialized, that backlog produced exactly the reported errors — all emitted by App Runner/Envoy, never by the app (whose only failure path is HTTP 500):Change
searchis now a syncdef, so FastAPI runs it in its worker threadpool (concurrent requests run in parallel) — matching/graph/embedding, which was already a syncdefand does not exhibit the bug./mcphandler offloads viarun_in_threadpool(search, …).get_openai_client()global init with athreading.Lock(double-checked locking), since it can now be called from several threadpool threads at once on a cold instance.Evidence (measured against prod)
16 concurrent
/searchcalls: ~17s wall, p50 12s (serialized). The identical-workload sync/graph/embeddingstays ~1s flat under the same concurrency.Review
Reviewed by a multi-agent adversarial pass (FastAPI async semantics, call-site regressions, concurrency) plus a focused second pass on the lock — no outstanding issues.
Companion infra guidance:
docs/apprunner-scaling-runbook. Independent of the other PRs; recommend merging this one first.