Lesson 6 / 32
Writing an SSE Endpoint
Build SSE endpoints in Node.js and FastAPI with the right headers, flushing and disconnect cleanup.
By Rahul Agarwal · 15 years in web development
The three jobs of an SSE handler
An SSE endpoint has three jobs. First, send the right headers: Content-Type: text/event-stream, Cache-Control: no-cache so no proxy caches a live stream, and, on HTTP/1.1, keep the connection alive. Second, write events as they happen in the exact format: fields, then a blank line. The bytes must actually leave the process; frameworks that buffer or compress responses can hold events back, so streaming must be explicit. Third, clean up on disconnect. When the user closes the tab, the server learns about it through the request's close event (Node.js) or request.is_disconnected() (Starlette/FastAPI). Every timer, database subscription or queue listener you started for that client must be stopped there, or each visitor leaks resources until the process runs out of memory. A periodic comment line such as : ping also stops idle-timeout proxies from cutting a quiet stream.
SSE with plain Node.js
No framework needed. The demo at the bottom starts the server, reads the stream with fetch and prints what arrived.
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.url !== '/events') {
res.writeHead(404).end();
return;
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
let n = 0;
const timer = setInterval(() => {
n += 1;
res.write(`id: ${n}\nevent: tick\ndata: ${JSON.stringify({ n })}\n\n`);
if (n === 3) {
clearInterval(timer);
res.end();
}
}, 100);
req.on('close', () => clearInterval(timer));
});
server.listen(3000, async () => {
const resp = await fetch('http://localhost:3000/events');
console.log(resp.headers.get('content-type'));
console.log(await resp.text());
server.close();
});
Output:
text/event-stream
retry: 3000
id: 1
event: tick
data: {"n":1}
id: 2
event: tick
data: {"n":2}
id: 3
event: tick
data: {"n":3}The same idea in FastAPI
An async generator yields events; StreamingResponse sends each chunk as it is produced. X-Accel-Buffering: no asks nginx not to buffer this response. Run it with uvicorn app:app.
import asyncio
import json
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
app = FastAPI()
async def ticks(request: Request):
n = 0
while not await request.is_disconnected():
n += 1
yield f"id: {n}\nevent: tick\ndata: {json.dumps({'n': n})}\n\n"
await asyncio.sleep(1)
@app.get("/events")
async def events(request: Request):
return StreamingResponse(
ticks(request),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Do not compress or buffer the stream
Gzip middleware and reverse-proxy buffering wait for "enough" bytes before sending, which can delay small events by seconds or hold them until the stream ends. Exclude text/event-stream from compression and disable buffering for SSE routes.
Quick check: A Node.js SSE handler starts a `setInterval` per client. What must happen when `req` emits `close`?
- Nothing, Node.js stops timers automatically
- Send a `retry: 0` field
- Call `res.writeHead(204)`
- Clear the interval and release anything else started for that client
Answer
Clear the interval and release anything else started for that client — The server only learns about the disconnect through the close event. Timers and subscriptions keep running unless the handler stops them, which leaks memory and CPU.