Skip to content

How do live updates work?

Open GET /api/v1/stream with EventSource. The server starts with a connection event. It then sends invalidate events when stocks or alerts change.

const api = 'https://api.squeeze.plus/api/v1';
const events = new EventSource('https://api.squeeze.plus/api/v1/stream');
const timers = new Map();
events.addEventListener('invalidate', (event) => {
const { entity } = JSON.parse(event.data);
clearTimeout(timers.get(entity));
timers.set(entity, setTimeout(async () => {
const route = entity === 'alerts' ? 'alerts' : 'stocks';
const response = await fetch(`${api}/${route}`);
if (!response.ok) return;
console.log(entity, await response.json());
}, 150));
});

Both event kinds have version: 1, entity, serverTs, and revision. A connection event uses entity: "connection". A change note uses stocks or alerts. Each event has an ID. The retry wait is 3,000 ms.

The stream sends a comment every 20 seconds.

It closes when the service stops. A slow client is closed too. Its write queue went past 256 KB.

An invalidate event is a change note. It is not the new full data set. Join close notes and reload one bounded REST route. EventSource will try to reconnect. Do not open a new stream for each retry.

Three stock notes can land in one short burst. Reload /api/v1/stocks once after the burst.

Fix a lost connection.