Server-sent events
easy 27 minServer-sent events (SSE) is one ordinary HTTP answer that does not end.
See it run
Open one answer that does not end, write events into it, lose the connection and continue without a gap.
Operations
Open a stream
One GET, one answer, many events.
Step 1 of 5
Ask
new EventSource sends a GET with Accept: text/event-stream.
Step 1: Ask
def events(request, response): if not user_of(request): return 401 response.status = 200 response.headers["Content-Type"] = "text/event-stream" response.flush() for e in subscription(): response.write(format_event(e)) response.flush()- Cost
- 1 request
- Gives you
- Push over plain HTTP
Once the 200 is sent, an error can only be told in an event.
In the real world
The same server-sent events doing real jobs. Pick one and step through it.
A question by POST, the answer as a stream, read with fetch.
Step 1 of 5
The question
EventSource cannot send a POST, so the page uses fetch.
Step 1: The question
Common mistakes
The bugs interviewers watch for, with the fix beside each.
One queue for all clients
criticalA queue gives each item to one reader, so each event reaches only one client.
Wrongqueue = Queue()async def client(): e = await queue.get()Rightasync def client(): q = Queue(maxsize=100) clients.add(q) # publish puts into allRandom ids
majorNobody can tell what comes after a random id. An unknown id is often ignored, and the gap stays unseen.
Wrongid = uuid4()Rightid = log.append(event) # 12346, 12347 ...Replay first, then subscribe
criticalAn event published between the two is in neither.
Wrongsend_all(log.after(last))live = log.follow()Rightlive = log.follow()send_all(log.after(last))send_new(live) # skip doublesNo flush
majorFrameworks, compression and proxies wait for more bytes. The page looks frozen.
Wrongresponse.write(event)Rightresponse.write(event)response.flush()# and buffering off on the wayRaw text in a data line
minorAfter a line break the rest is read as an unknown field and lost.
Wrongf"data: {text}\n\n"Rightf"data: {json.dumps(text)}\n\n"
Interview tips
How to explain it
- One GET, an answer that stays open.
- Text events, a blank line after each.
- The browser reconnects and says its last id.
Memory trick: DIER
- Data, id, event, retry.
- Colon first: comment.
- 204: do not come back.
Reach for it when
- Only the server has news.
- It is text.
- You want plain HTTP.
Avoid it when
- The client sends all the time.
- Data is binary.
- The page is closed.