Real-time Events
Ostrakon supports real-time event streaming through Server-Sent Events (SSE).
What is SSE?
Section titled “What is SSE?”Server-Sent Events is a technology that lets the server push updates to the client over a persistent HTTP connection. It is simpler than WebSockets and perfect for one-way flows.
Named messages
Section titled “Named messages”The server sends named messages (event: <name>), not anonymous ones. In the browser, onmessage therefore never fires: listen to each name with addEventListener.
| Name | When |
|---|---|
connected |
Once, when the stream opens |
event |
Events were recorded on a followed trigger |
heartbeat |
Every 30 seconds, to keep the connection open |
You can see it by hand with curl -N:
curl -N https://ostrakon.example.com/api/v1/events/stream/{triggerId} \ -H "X-API-Key: sk_votre_cle"event: connecteddata: {"type":"connected","client_id":"...","subscriptions":["<trigger id>"]}
event: eventdata: {"id":"...","type":"batch_event","trigger_id":"<trigger id>","event_count":1,"event_time":"2024-01-15T10:30:00Z","source":{"type":"authenticated","account_id":"...","auth_type":"api_key"}}
event: heartbeatdata: {"type":"heartbeat","timestamp":"2024-01-15T10:30:30Z"}Connect to the stream
Section titled “Connect to the stream”Public stream (no auth)
Section titled “Public stream (no auth)”For a public trigger, the native EventSource is enough (by ID, or by slug with /public/events/stream/trigger/{slug}):
const eventSource = new EventSource( `https://ostrakon.example.com/api/v1/public/events/stream/${publicTriggerId}`);
eventSource.addEventListener('connected', (e) => { console.log('Connected:', JSON.parse(e.data));});
eventSource.addEventListener('event', (e) => { const message = JSON.parse(e.data); console.log('New events:', message.event_count ?? 1);});
eventSource.addEventListener('heartbeat', () => { console.log('Connection alive');});Authenticated streams
Section titled “Authenticated streams”EventSource cannot send a header, yet private streams expect Authorization: Bearer <JWT> or X-API-Key: <key>. Use a client that sends headers, for example @microsoft/fetch-event-source (the one used by the web app). The message name arrives in msg.event:
import { fetchEventSource } from '@microsoft/fetch-event-source';
const controller = new AbortController();
fetchEventSource('https://ostrakon.example.com/api/v1/events/stream', { headers: { Authorization: `Bearer ${accessToken}` }, // or { 'X-API-Key': apiKey } signal: controller.signal, onmessage(msg) { const data = JSON.parse(msg.data); if (msg.event === 'connected') console.log('Subscribed to', data.subscriptions); if (msg.event === 'event') console.log('New events:', data.event_count ?? 1); // msg.event === 'heartbeat': nothing to do },});
// Later: controller.abort();The routes:
| Route | Required scope |
|---|---|
GET /events/stream: all the triggers you can read |
trigger:stats:* |
GET /events/stream/{triggerId}: one trigger |
trigger:stats:<id> |
GET /public/events/stream/{triggerId} or /public/events/stream/trigger/{slug}: public trigger |
none |
The scope is trigger:stats (not trigger:read). A JWT has it by default on your triggers.
Message contents
Section titled “Message contents”connected
Section titled “connected”{ "type": "connected", "client_id": "9b2e3a52-...", "subscriptions": ["550e8400-e29b-41d4-a716-446655440000"]}subscriptions lists the triggers followed by this stream.
Events were recorded. Accepted events are grouped when written to the database, per trigger and per source: the current message is a batch_event, which counts the events without containing them.
{ "id": "e67fce20-fa9e-44eb-92c8-4339ba95d6d5", "type": "batch_event", "trigger_id": "550e8400-e29b-41d4-a716-446655440000", "event_count": 3, "event_time": "2024-01-15T10:30:00Z", "source": { "type": "authenticated", "account_id": "6605be92-7b3b-4693-a58a-dc4e5d332e46", "auth_type": "api_key" }}event_count: number of events in the batch,event_time: date of the most recent one.source.typeisauthenticatedorpublic.auth_type(jwtorapi_key) andaccount_idare present only for an authenticated source.- To read the events themselves, call
GET /triggers/{id}/eventsafter the message. - The protocol also provides a
type: "event"message (a single event, with itsmetadatafield, withoutevent_count): handle both types.
heartbeat
Section titled “heartbeat”Keep-alive signal (every 30 seconds):
{ "type": "heartbeat", "timestamp": "2024-01-15T10:30:30Z"}There is no stats message: for an up-to-date total, count the event_count values received or call GET /triggers/{id}/stats again.
Follow each event (debugging)
Section titled “Follow each event (debugging)”By default a stream sends aggregated batch_event messages, which is what the web app consumes. To see the events themselves, like tail -f, add ?mode=events to the authenticated routes:
curl -N -H "X-API-Key: $KEY" \ "https://ostrakon.example.com/api/v1/events/stream/{triggerId}?mode=events"Each event is one frame, with its identifier in the id: line:
id: 5d1c0c3e-8f0a-4a5c-9a52-2e6d3f1f7c11event: eventdata: {"id":"5d1c0c3e-8f0a-4a5c-9a52-2e6d3f1f7c11","type":"event","trigger_id":"550e8400-e29b-41d4-a716-446655440000","event_time":"2024-01-15T10:30:00Z","metadata":{"marker":"abc-123"},"source":{"type":"public"}}- Same routes, scopes and visibility rules as the aggregated stream. A reader whose access comes from a public trigger alone gets the anonymous payload.
- A per-event stream never carries
batch_eventmessages, and an aggregated stream never carries these ones. - The server caps each per-event connection (
sse.event_stream_max_rate, 100 events per second by default). Above the cap events are dropped, not queued, and adroppedmessage tells how many:
event: droppeddata: {"type":"dropped","dropped":42}- A connection that stays over the cap for 30 seconds is closed: reconnect, or lower the rate of the source.
Last-Event-IDis not supported. Theid:only identifies the message, events are not stored by the stream and what was sent while you were disconnected is not replayed. Events sent in the very instant you connect can also be missed: useGET /triggers/{id}/eventsfor a complete history.
Connection handling
Section titled “Connection handling”Automatic reconnection
Section titled “Automatic reconnection”EventSource reconnects on its own. You can customize the behavior:
eventSource.addEventListener('error', () => { if (eventSource.readyState === EventSource.CLOSED) { console.log('Connection closed, reconnecting...'); // Recreate the connection after a delay setTimeout(() => { createEventSource(); }, 5000); }});fetchEventSource also retries by default (onerror to adjust or stop).
Close cleanly
Section titled “Close cleanly”// Close the connection when it is no longer neededeventSource.close(); // EventSourcecontroller.abort(); // fetchEventSourceUsing it with React
Section titled “Using it with React”import { useEffect, useState } from 'react';import { fetchEventSource } from '@microsoft/fetch-event-source';
function useEventStream(triggerId: string, accessToken: string) { const [received, setReceived] = useState(0); const [connected, setConnected] = useState(false);
useEffect(() => { const controller = new AbortController();
fetchEventSource(`/api/v1/events/stream/${triggerId}`, { headers: { Authorization: `Bearer ${accessToken}` }, signal: controller.signal, onopen: async () => setConnected(true), onmessage(msg) { if (msg.event === 'event') { const data = JSON.parse(msg.data); setReceived((n) => n + (data.event_count ?? 1)); } }, onerror: () => setConnected(false), });
return () => controller.abort(); }, [triggerId, accessToken]);
return { received, connected };}Sender tab (echo)
Section titled “Sender tab (echo)”The web app counts an event it has just sent before even receiving it through the stream. To avoid counting it twice, it ignores its own echo, and only its own.
- Header:
X-Ostrakon-Client-IdonPOST /triggers/:id/eventsand/events/batch. The web app sends it on its authenticated requests, with a random ID per page load ([A-Za-z0-9_-], 8 to 64 characters). - Invalid value: a header that is absent or outside the
^[A-Za-z0-9_-]{8,64}$pattern is ignored, never rejected (the event is accepted). - Stream: for an event sent with a JWT and a valid ID, the
sourceof theeventmessage (of typeeventorbatch_event) carriesclient_id. A tab skips the event only ifsource.auth_typeisjwtandsource.client_idis its own. Another tab, or another device on the same account, counts it normally. - Without
client_id: an event sent with a JWT but without a valid ID is counted by all tabs. - API key: the header is ignored, these events never carry a
client_idand are counted everywhere. - Public streams:
client_idis never exposed. Anonymous readers, and those whose access comes only from the trigger's public visibility, receive a publicsourcereduced to its type.
The ID is not stored and is not used as an idempotency key.
Authentication with SSE
Section titled “Authentication with SSE”Private streams authenticate by header, like the rest of the API:
Authorization: Bearer <access_token>(JWT);X-API-Key: <key>with thetrigger:statsscope (see API Keys).
For a connection that reopens (network, restart), start again from a fresh access token (valid for 15 minutes, see Authentication).
Best practices
Section titled “Best practices”-
Handle reconnections - Handle errors and reopen the stream with a fresh token
-
Close unused connections - Avoid resource leaks
-
Limit the buffer - Do not keep too many events in memory
-
Use the heartbeat - Watch the heartbeats to detect disconnections
-
Batch UI updates - Avoid re-rendering on every event
Full example
Section titled “Full example”import { useEffect, useState } from 'react';import { fetchEventSource } from '@microsoft/fetch-event-source';
function LiveCounter({ triggerId, accessToken }: { triggerId: string; accessToken: string }) { const [count, setCount] = useState(0); const [status, setStatus] = useState<'connecting' | 'connected' | 'error'>('connecting');
useEffect(() => { const controller = new AbortController();
fetchEventSource(`/api/v1/events/stream/${triggerId}`, { headers: { Authorization: `Bearer ${accessToken}` }, signal: controller.signal, onopen: async () => setStatus('connected'), onerror: () => setStatus('error'), onmessage(msg) { // Named messages: connected, event, heartbeat if (msg.event === 'event') { const data = JSON.parse(msg.data); setCount((c) => c + (data.event_count ?? 1)); } }, });
return () => controller.abort(); }, [triggerId, accessToken]);
return ( <div> <div className={`status ${status}`}>{status}</div> <div className="count">{count}</div> </div> );}The counter starts at zero on connection: it counts the events received, not the trigger's total (GET /triggers/{id}/stats).