Real-time APIs
medium 27 minHTTP lets the client ask and the server answer.
See it run
Polling, long polling, server-sent events and WebSocket: who speaks first, what stays open and how you catch up.
Operations
Short polling
Ask every second. Most answers say nothing new.
Step 1 of 4
0:00 ask
Requests
1
304
GET /messages answers 304: nothing changed.
Step 1: 0:00 ask
while True: r = GET("/messages", after=last) if r.status == 200: show(r.body) sleep(1)- Delay
- Up to 1 s
- Requests
- 86,400 a day
- Average delay
- half the interval
Polling is not shameful. For a page that changes every few minutes it is the cheapest thing to run.
In the real world
The same real-time apis doing real jobs. Pick one and step through it.
Prices only flow one way, so server-sent events are enough.
Step 1 of 3
Open once
price $42.50
The page opens /events and shows $42.50.
Step 1: Open once
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No way to catch up
criticalEvery phone loses its connection many times a day. Messages sent in the gap are gone unless they are numbered and saved.
Wrongsocket.on("open", listen)Rightconnect(after=last_seen)# server: send history first, then liveTaking messages out of one shared queue
criticalWith long polling, the first client to poll empties the queue and the others never see those messages. Each client needs its own cursor.
Wrongmessages = queue.take(10)Rightmessages = log.after(client_cursor, 10)Reconnecting at once, all together
majorAfter a restart every client returns in the same second and takes the server down again.
Wrongon_close(connect)Rightsleep(random(0, min(30, 2 ** tries)))connect()Letting a slow client fill the memory
majorIf one client reads slowly, its messages pile up in the server. Give each client a limited buffer and close it when full: it can catch up.
Wrongclient.buffer.append(m) # no limitRightif len(client.buffer) >= 256: client.close() # it will catch up
Interview tips
How to explain it
- Short polling asks often. Long polling asks and waits.
- SSE is one long answer: server to client.
- WebSocket is a two-way connection.
- All of them need a way to catch up.
Memory trick: WSL
- W: WebSocket, two ways, for chat and games.
- S: server-sent events, one way, for feeds and logs.
- L: long polling, the fallback that works everywhere.
Reach for it when
- People wait for each other: chat, editing, games.
- A value changes while someone watches.
- Seconds matter. If minutes are fine, poll.
Say in an interview
- How many connections, and memory per connection.
- How a message finds the right server.
- What a client does after a drop.
- What happens on a deployment.