Streaming Responses and Server-Sent Events
Implement high-performance Server-Sent Events streaming in FastAPI with event IDs, reconnect replay via Last-Event-ID, keepalive heartbeats, and client disconnect detection.
Contentsand lesson path
On this page
- Why it matters
- The text/event-stream wire protocol
- Worked example: a resilient SSE endpoint in FastAPI
- Relaying an upstream stream, such as LLM tokens
- Check your understanding
- Apply it
- Review prompt
Lessons of Real-Time APIs & Webhooks
- Polling, Push or Callback? Choosing a Delivery Channel Concept · 20 min
- Streaming Responses and Server-Sent Events Worked example · 25 min
- Lab: An Authenticated WebSocket Feed Across Workers Lab · 30 min
- Webhooks Others Can Trust: Sign, Retry, Verify Worked example · 25 min
- Long-Lived Connections in Production: Proxies, Limits and Deploys Concept · 15 min
- Check: Choose and Defend a Real-Time Design Knowledge check · 8 questions
What you will learn
- Stream incremental results over server-sent events or a chunked response, including relaying an upstream stream such as LLM tokens, with heartbeats, resume via Last-Event-ID and cleanup when the client disconnects.
Prerequisites: Async I/O in Python
01. Why it matters
When building modern web applications that demand live progress updates—such as monitoring continuous deployment pipelines, live stock price movements, collaborative task status changes, or streaming LLM text generations—Server-Sent Events (SSE) is often the simplest reliable choice.
Defined in the WHATWG HTML Living Standard Server-Sent Events uses standard HTTP connections configured with the Content-Type: text/event-stream media type. Unlike polling, it does not ask the database for news on a timer, and unlike WebSockets, it needs no separate framing protocol or ping/pong of its own: browsers support it natively through the EventSource JavaScript API.
The browser's EventSource implementation gives you three useful capabilities out of the box:
- Automatic reconnection: If the network drops or the server closes the stream, the browser waits its reconnection time (a few seconds by default, or the server's
retry:value) and connects again, with no client code. An answer other than200withtext/event-streamstops it for good, so a server that wants a client to stop sends204 No Content. - Event resumption: When the server tags each outgoing event with an
id: <identifier>line, the browser tracks the latest received ID. Upon reconnecting, the browser automatically sends theLast-Event-IDHTTP request header, allowing the server to replay missed events. - HTTP/2 multiplexing: Under HTTP/1.1, browsers allow about six connections per origin, so a few tabs with open SSE streams can stall the page's other requests for images and API calls. Under HTTP/2 and HTTP/3, many SSE streams share one TCP or QUIC connection, up to the server's limit on concurrent streams (commonly 100 or more), so in practice the stall goes away.
However, streaming long-lived HTTP responses in Python requires careful backend engineering: handling reverse proxy buffering, sending heartbeat keepalives, and actively listening for client disconnections.
02. The text/event-stream wire protocol
The SSE wire protocol is plain UTF-8 text structured into blocks delimited by two consecutive newline characters (\n\n). Each line within a block consists of a field name, a colon, and the field value:
event: <name>: Specifies the custom event type (e.g.event: task_updated). If omitted, the client dispatches the defaultonmessageevent handler.data: <payload>: The body of the message, typically serialized JSON. For multi-line payloads, multiple consecutivedata:lines can be sent, which the browser concatenates with newline characters before passing to the event handler.id: <string>: Sets the event identifier. The browser stores this identifier and transmits it as theLast-Event-IDrequest header upon reconnecting.retry: <milliseconds>: Informs the browser how long to wait before attempting to reconnect if the connection drops (default is typically 3000 ms).: <comment>: Any line starting with a colon is a comment. Servers use comment lines (such as: keepalive\n\n) to transmit periodic heartbeats that reset proxy idle timeouts without triggering client-side message events.
Because SSE is strictly text-based, binary data (such as image buffers or audio frames) must be base64-encoded or serialized into JSON strings before transmission.
03. Worked example: a resilient SSE endpoint in FastAPI
A resilient SSE endpoint in FastAPI needs three things:
- Replay of missed events: Every event is stored with an id that the store issues in increasing order. On reconnect, the server reads
Last-Event-ID, replays the events after it from a ring buffer (here adeque; in production a Redis Stream withXADDandXRANGE), and then continues with live events. Each id carries the store's epoch, a random value chosen when the store is created, followed by a sequence number (3f9a1c07-42). If the id is malformed, comes from another epoch (any id issued before a server restart), or points before the start of the buffer, the server sends anevent: resetso the client reloads its state instead of silently missing events. The header is client-controlled, so it is parsed with a strict ASCII pattern and a length limit rather thanint(), which would raise on input such as²or a 5,000-digit number. When the replay reaches the job'sdoneevent, the stream ends there instead of idling with keepalives. Ids that survive restarts, such as Redis Stream ids, let you replay across restarts instead of resetting. - Periodic keepalives: Emitting an empty comment line (
: keepalive\n\n) every 15 to 30 seconds to prevent edge reverse proxies (such as NGINX, Cloudflare, or AWS Application Load Balancers) from terminating idle connections. - Cleanup on disconnect: When the client goes away, Starlette cancels the
StreamingResponsegenerator: at once on servers such as uvicorn 0.54 (ASGI spec 2.3), or at the next write on servers that implement ASGI spec 2.4. Either way the generator stops, so put cleanup intry/finally: unsubscribe, close upstream streams, cancel helper tasks.await request.is_disconnected()is still useful before you start expensive work.
FastAPI 0.135.0 and later also ship a built-in SSE response, fastapi.sse.EventSourceResponse with ServerSentEvent, which formats the fields, sets Cache-Control: no-cache and X-Accel-Buffering: no, and sends a : ping comment after 15 seconds without events (FastAPI SSE tutorial). Use it in your own services. This lesson writes the frames by hand with StreamingResponse so you can see every line on the wire; the replay, reset and cleanup logic is the same with either.
Below is a complete implementation using FastAPI and StreamingResponse. Live events go into the same buffer that replay reads from, so a client that reconnects after event 5 receives event 6 next, with no duplicates:
import asyncio
import itertools
import json
import re
import secrets
from collections import deque
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
app = FastAPI()
SSE_HEADERS = {
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no", # disable nginx response buffering
}
# Event ids look like "3f9a1c07-42": the store's epoch, then a sequence number
EVENT_ID = re.compile(r"([0-9a-f]{8})-([0-9]{1,18})", re.ASCII)
class JobEvents:
"""Recent events of one job (a ring buffer) plus its live subscribers."""
def __init__(self, size: int = 1000):
self.epoch = secrets.token_hex(4) # new store (or restart), new epoch
self.buffer: deque[tuple[int, str, dict]] = deque(maxlen=size)
self.subscribers: set[asyncio.Queue] = set()
self.seq = itertools.count(1) # monotonic within this epoch
def publish(self, event: str, data: dict) -> None:
item = (next(self.seq), event, data)
self.buffer.append(item) # kept for replay...
for queue in self.subscribers: # ...and fanned out live
queue.put_nowait(item) # bound these queues in production
def newest(self) -> int:
return self.buffer[-1][0] if self.buffer else 0
def resume_point(self, last_event_id: str | None) -> int | None:
"""Sequence number to resume after, or None if the client must reload."""
if last_event_id is None:
return 0 # first connection: replay what the buffer holds
match = EVENT_ID.fullmatch(last_event_id)
if match is None or match.group(1) != self.epoch:
return None # malformed, or issued by an earlier process
return int(match.group(2))
def since(self, last: int | None) -> list | None:
"""Events after last, or None when the client must reload."""
if last is None or last > self.newest():
return None
if self.buffer and last < self.buffer[0][0] - 1:
return None # some events already left the buffer
return [item for item in self.buffer if item[0] > last]
JOBS: dict[str, JobEvents] = {}
def frame(job: JobEvents, seq: int, event: str, data: dict) -> str:
return (f"id: {job.epoch}-{seq}\nevent: {event}\n"
f"data: {json.dumps(data)}\n\n")
async def job_stream(job: JobEvents, last_event_id: str | None):
queue: asyncio.Queue = asyncio.Queue()
job.subscribers.add(queue) # subscribe before replaying: no gap
try:
last = job.resume_point(last_event_id)
missed = job.since(last)
if missed is None: # unknown or stale id: the client must reload
yield "event: reset\ndata: {}\n\n"
missed, last = [], job.newest()
if job.buffer and job.buffer[-1][1] == "done":
return # the job has finished: nothing more will come
for item in missed:
yield frame(job, *item)
last = item[0]
if item[1] == "done":
return # replayed the end of the job: close the stream
while True:
try:
item = await asyncio.wait_for(queue.get(), timeout=15)
except TimeoutError:
yield ": keepalive\n\n" # resets proxy idle timers
continue
if item[0] > last: # skip anything already replayed
yield frame(job, *item)
last = item[0]
if item[1] == "done":
return
finally:
job.subscribers.discard(queue) # also runs when the client leaves
@app.get("/api/v1/jobs/{job_id}/stream")
async def stream_job_updates(job_id: str, request: Request):
job = JOBS.setdefault(job_id, JobEvents())
last_id = request.headers.get("Last-Event-ID")
return StreamingResponse(job_stream(job, last_id),
media_type="text/event-stream", headers=SSE_HEADERS)04. Relaying an upstream stream, such as LLM tokens
A common SSE job is relaying a stream from another service, for example tokens from a language model API. Open the upstream request inside the generator with async with. When the browser disconnects, the cancellation reaches the async with block, which closes the upstream connection, and the model stops generating tokens nobody will read:
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
LLM_URL = "http://127.0.0.1:8001" # any upstream that streams lines of text
@asynccontextmanager
async def lifespan(app: FastAPI):
# No overall limit for a long stream, but give up on a silent upstream
timeout = httpx.Timeout(10.0, read=60.0)
app.state.http = httpx.AsyncClient(base_url=LLM_URL, timeout=timeout)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
@app.get("/api/v1/chat/stream")
async def relay_tokens(prompt: str):
async def relay():
# The upstream request lives inside the generator: when the browser
# disconnects, Starlette cancels the generator, `async with` exits and
# the upstream connection is closed, so the model stops generating.
async with app.state.http.stream(
"POST", "/generate", json={"prompt": prompt}) as upstream:
async for line in upstream.aiter_lines():
if line:
yield f"data: {line}\n\n"
yield "event: done\ndata: {}\n\n"
return StreamingResponse(relay(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache"})To see both apps work, save check_sse.py next to them. It starts sse_app on port 8000, a fake model that streams 20 tokens on port 8001 and relay_app on port 8002, all with uvicorn in one process, then acts as the browser:
"""Check sse_app.py and relay_app.py against real uvicorn servers, in one process."""
import asyncio
import httpx
import uvicorn
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import relay_app
import sse_app
from sse_app import JOBS, JobEvents
fake_llm = FastAPI()
sent = [] # tokens the fake model has produced
@fake_llm.post("/generate")
async def generate():
async def tokens():
try:
for i in range(20):
sent.append(i)
yield f"token-{i}\n"
await asyncio.sleep(0.2)
finally:
print(f"fake LLM: stream closed after {len(sent)} of 20 tokens")
return StreamingResponse(tokens(), media_type="text/plain")
SERVERS = []
async def serve(app, port):
server = uvicorn.Server(uvicorn.Config(app, port=port, log_level="warning"))
SERVERS.append((server, asyncio.create_task(server.serve())))
while not server.started:
await asyncio.sleep(0.05)
async def read(url, last_id=None, n=None, during=None):
"""Return (event ids or names, closed by the server?); stop after n events."""
got, headers = [], {} if last_id is None else {"Last-Event-ID": last_id}
async with httpx.AsyncClient(timeout=5) as client:
async with client.stream("GET", url, headers=headers) as resp:
if during:
asyncio.get_running_loop().call_later(0.2, during)
async for line in resp.aiter_lines():
if line.startswith("id: "):
got.append(line.split("-")[-1]) # the sequence part only
elif line == "event: reset":
got.append("reset")
elif line.startswith("data: token"):
got.append(line[6:])
if n and len(got) == n:
return got, False # the client leaves
return got, True
async def main():
base = "http://127.0.0.1:8000/api/v1/jobs"
await serve(sse_app.app, 8000)
job = JOBS["build"] = JobEvents()
for i in range(5):
job.publish("progress", {"step": i})
print("first connection got:", (await read(f"{base}/build/stream", n=5))[0])
await asyncio.sleep(0.2)
print("subscribers after disconnect:", len(job.subscribers))
job.publish("progress", {"step": 5})
job.publish("progress", {"step": 6})
got, closed = await read(f"{base}/build/stream", f"{job.epoch}-5",
during=lambda: job.publish("done", {}))
print("reconnect after 5 got:", got, "| closed by server:", closed)
small = JOBS["small"] = JobEvents(size=3)
for i in range(5):
small.publish("progress", {"step": i})
small.publish("done", {})
got, closed = await read(f"{base}/small/stream", f"{small.epoch}-1")
print("id older than the buffer:", got, "| closed by server:", closed)
got, closed = await read(f"{base}/build/stream", f"{job.epoch}-7")
print("finished job, resume after 7:", got, "| closed:", closed)
old_epoch = job.epoch
JOBS["build"] = restarted = JobEvents() # as after a restart: a new epoch
for i in range(4):
restarted.publish("progress", {"step": i})
got, _ = await read(f"{base}/build/stream", f"{old_epoch}-2", n=1)
print("old epoch id 2 after restart:", got, "(reset, not 3 and 4)")
for bad in (b"57", b"\xb2", b"9" * 5000):
got, _ = await read(f"{base}/build/stream", bad, n=1)
print(f"Last-Event-ID {bad[:6]!r} ({len(bad)} bytes): {got}")
await serve(fake_llm, 8001)
await serve(relay_app.app, 8002)
got, _ = await read("http://127.0.0.1:8002/api/v1/chat/stream?prompt=hi", n=3)
print("browser received:", got, "then disconnected")
await asyncio.sleep(1)
for server, task in SERVERS: # stop the servers cleanly
server.should_exit = True
await task
asyncio.run(main())uv pip install "fastapi==0.165.0" "starlette==1.10.0" "uvicorn==0.54.0" "httpx==0.28.1"
python check_sse.pyfirst connection got: ['1', '2', '3', '4', '5']
subscribers after disconnect: 0
reconnect after 5 got: ['6', '7', '8'] | closed by server: True
id older than the buffer: ['reset'] | closed by server: True
finished job, resume after 7: ['8'] | closed: True
old epoch id 2 after restart: ['reset'] (reset, not 3 and 4)
Last-Event-ID b'57' (2 bytes): ['reset']
Last-Event-ID b'\xb2' (1 bytes): ['reset']
Last-Event-ID b'999999' (5000 bytes): ['reset']
browser received: ['token-0', 'token-1', 'token-2'] then disconnected
fake LLM: stream closed after 3 of 20 tokensThe first nine lines check sse_app.py (the client prints only the sequence part of each id). It reads events 1 to 5, disconnects, and reconnects after event 5 once events 6 and 7 were published; the subscriber count shows the finally block ran, and the stream closes after done. It then reconnects with an id that has left the buffer, and after event 7 of the finished job, which gets done and a closed stream. Next it simulates a restart: the new store issues ids 1 to 4 again under a new epoch, and the client's old id 2 gets a reset rather than events 3 and 4. A bare number, a non-ASCII byte and a 5,000-digit id also get a reset, and the server logged no traceback. The last lines come from the relay: the browser read three tokens and left, and the upstream stream was closed after three of its twenty tokens.
05. Check your understanding
06. Apply it
Implement a live notification or progress endpoint in your backend service using Server-Sent Events:
- Headers: Set
Content-Type: text/event-stream,Cache-Control: no-cacheandX-Accel-Buffering: no. Do not setConnectionyourself: HTTP/2 forbids it, and the server handles it on HTTP/1.1. - Event IDs and replay: Attach a monotonic ID to every event. Read the
Last-Event-IDheader on request entry and replay missed events from an in-memory ring buffer or Redis Stream. - Keepalives: Yield a comment line (
: keepalive\n\n) every 15 seconds, so that load balancers (AWS ALB, Cloudflare, NGINX) with idle timeouts of 60 seconds or more do not close the connection as idle. - A disconnect test: Start an active stream from a browser or curl client, disconnect the client mid-stream, and verify in your server logs that the generator's
finallyblock ran and any upstream request was closed. - HTTP/2 multiplexing: Open browser developer tools, navigate to the Network tab, and verify that multiple concurrent SSE streams to the same origin share a single underlying HTTP/2 connection without blocking standard REST API calls.
In the next lesson, you will build an authenticated bidirectional WebSocket service that fans out messages across multiple worker instances using Redis Pub/Sub.
07. Review prompt
Detail the wire format of Server-Sent Events, including event, data, id, and comment lines. Explain how the browser EventSource client uses Last-Event-ID to recover from network drops without data loss. Contrast the server-side memory footprint and connection concurrency of SSE under HTTP/2 against WebSockets, and explain why X-Accel-Buffering: no and keepalive heartbeats are critical when deploying SSE behind edge reverse proxies.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.