AlgoViz

Server-sent events

easy 27 min

Server-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

GET /eventsBrowserreadyState 0SSE serverchecks user

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

POST /answerBrowserfetchSSE serverstarts

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

    critical

    A queue gives each item to one reader, so each event reaches only one client.

    Wrong
    queue = Queue()async def client():    e = await queue.get()
    Right
    async def client():    q = Queue(maxsize=100)    clients.add(q)          # publish puts into all
  • Random ids

    major

    Nobody can tell what comes after a random id. An unknown id is often ignored, and the gap stays unseen.

    Wrong
    id = uuid4()
    Right
    id = log.append(event)   # 12346, 12347 ...
  • Replay first, then subscribe

    critical

    An event published between the two is in neither.

    Wrong
    send_all(log.after(last))live = log.follow()
    Right
    live = log.follow()send_all(log.after(last))send_new(live)           # skip doubles
  • No flush

    major

    Frameworks, compression and proxies wait for more bytes. The page looks frozen.

    Wrong
    response.write(event)
    Right
    response.write(event)response.flush()# and buffering off on the way
  • Raw text in a data line

    minor

    After a line break the rest is read as an unknown field and lost.

    Wrong
    f"data: {text}\n\n"
    Right
    f"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.