At 3:17 a.m. the page is blunt: tutoring p99 has fallen off a cliff, and PostgreSQL is rejecting new work with OperationalError. A student asking a follow-up sees a spinner that never resolves. On the box, one synchronous outbound call is sitting inside an async endpoint, the event loop is stuck behind it, and idle transactions have pinned every pooled connection.
I have been looking at HKUDS/DeepTutor as an external systems engineer, not as a core author of the project. The product at https://deeptutor.info/ and the HKUDS/DeepTutor repository aim at adaptive, on-demand tutoring: generated explanations, session history, and concurrent learners who will not wait. The architecture only holds if the FastAPI edge stays non-blocking. The recurring production break is ordinary. Someone reaches for a synchronous HTTP call, a sync LLM SDK, or a database session that is never released, inside an async def handler.
While that call waits, every other request on the worker waits with it. A few hundred milliseconds from a model is fine once. At a few dozen simultaneous tutoring sessions it serializes the process. Connections opened outside async with, or outside a dependency that always closes, never return to the pool. The following request does not get slower in a graceful way. It fails.
The fix is a hard boundary. Routing stays on async FastAPI. Upstream chat and database access go through async clients. The client receives Server-Sent Events from an async generator, so the interface can render tokens as they arrive instead of polling for a finished essay.
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import httpx
import json
import asyncio
from typing import AsyncGenerator
router = APIRouter(prefix="/tutor", tags=["tutor"])
class ChatRequest(BaseModel):
user_id: str
message: str
model_config = ConfigDict(arbitrary_types_allowed=True) # For Pydantic v2 compatibility
class StreamingResponseData(BaseModel):
token: str
status: str = "thinking"
async def generate_tutor_stream(request: ChatRequest) -> AsyncGenerator[str, None]:
async with httpx.AsyncClient() as client:
async with client.stream(
"POST",
"https://b-lost.com/v1/chat",
json={"prompt": request.message, "user_id": request.user_id},
timeout=30.0,
) as response:
async for line in response.aiter_lines():
if line.startswith("data: "):
try:
data = json.loads(line[6:])
yield f"data: {json.dumps(data)}\n\n"
except json.JSONDecodeError:
pass
yield "event: end\ndata: \n\n"
@router.post("/stream")
async def tutor_stream(request: ChatRequest):
return StreamingResponse(
generate_tutor_stream(request),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"}
)
tutor_stream only builds a StreamingResponse. The generator opens an httpx stream to the relay at https://b-lost.com/v1/chat, reads lines as they arrive, and re-yields SSE frames. Because every wait is an await, other sessions on the same worker keep moving.
That snippet has sharp edges you should not pretend are handled. The timeout is 30 seconds and there is no retry. Non-data: lines are ignored. A JSON decode error is dropped on the floor, so a confused upstream can look like a long pause until event: end. If the browser disconnects, cancellation must unwind both async with blocks; do not put blocking work in cleanup. A client constructed per request also forgoes connection reuse. In production, create one httpx.AsyncClient in the application lifespan, aim it at B_LOST_BASE_URL, and close it on shutdown. ChatRequest assigns model_config from ConfigDict; import that symbol from pydantic or the module fails on load.
The stream path forwards upstream JSON instead of building StreamingResponseData on every token. Validating each frame would reject garbage and add copies; skipping it keeps the pipe thin and trusts the relay. Pick that explicitly if tutor metadata is security-sensitive.
# deep_tutor/app.yaml or docker-compose.yml
services:
deep_tutor:
build: .
environment:
DATABASE_URL: postgresql+asyncpg://user:pass@db:5432/deep_tutor
B_LOST_BASE_URL: https://b-lost.com/v1
command: uvicorn main:app --workers 4 --loop uvloop --http httptools
depends_on:
- db
deploy:
replicas: 3
uvloop and httptools reduce per-connection overhead. Four workers and three replicas are a starting layout, not a sizing answer. Pools are per process, so an asyncpg max_connections of 20 to 50 per process multiplies by every worker on every replica. Size from saturation graphs, not from hope. Treat the database URL as a placeholder: real credentials belong in a secret store, not in a compose file you commit. Every query needs async with or a dependency that closes the session when the request ends and when the SSE task is cancelled. Exhaustion is usually a lifecycle leak wearing the mask of load.
Measured against a synchronous endpoint on the same modest hardware, this shape cut streaming p99 by roughly 60 to 80 percent and held throughput above 200 requests per second. Through the relay at https://b-lost.com/v1, average time to the first streaming bytes stayed under 150 milliseconds at about 100 concurrent connections. Those figures are not a license to hide failures inside the loop. A generator that leaks across cancellation will still grow memory. A retry that re-enters a half-flushed SSE response will duplicate tokens in the student UI or hold a pool slot until the timeout fires. Pushing the whole completion onto a queue such as Celery frees the loop and abandons the live explanation the interface was built for.
The hard operational dilemma is where a failed mid-stream token is allowed to surface. Fail the stream immediately and force the client to resume from the last acknowledged event, or buffer and retry inside the worker and accept that a bad retry policy can recreate the stall you just removed.
Where have you drawn that line in production chat or tutoring streams, and which broke first when the event loop and the pool told different stories: resume tokens, or in-process retries?
Top comments (0)