Skip to main content

Stream LLM tokens over SSE with disconnect detection

Implement a FastAPI StreamingResponse endpoint emitting Server-Sent Events and stopping upstream LLM generation if the client disconnects.

Official Reference

Model Answer & Explanation

@app.post("/chat/stream")
async def chat_stream(request: Request):
    async def events():
        try:
            async for chunk in stream_llm():
                if await request.is_disconnected():
                    break
                yield f"data: {chunk}\n\n"
            yield "data: [DONE]\n\n"
        except asyncio.CancelledError:
            pass
    return StreamingResponse(events(), media_type="text/event-stream")

Return StreamingResponse(event_stream(), media_type='text/event-stream') with Cache-Control: no-cache and X-Accel-Buffering: no. Inside the async generator, poll await request.is_disconnected() or cancel on asyncio.CancelledError inside a try/finally block so the upstream LLM stream is closed immediately when the user stops generation.

Follow-up Interview Question · How do you persist the partial or final assistant message and token usage after the stream finishes?

Module Context & References

Python & FastAPI · Practice questions & drills High-frequency coding, FastAPI, concurrency and testing exercises
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.