Skip to content

Real-time Events

Ostrakon supports real-time event streaming through Server-Sent Events (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.

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:

Terminal window
curl -N https://ostrakon.example.com/api/v1/events/stream/{triggerId} \
-H "X-API-Key: sk_votre_cle"
event: connected
data: {"type":"connected","client_id":"...","subscriptions":["<trigger id>"]}
event: event
data: {"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: heartbeat
data: {"type":"heartbeat","timestamp":"2024-01-15T10:30:30Z"}

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');
});

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.

{
"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.type is authenticated or public. auth_type (jwt or api_key) and account_id are present only for an authenticated source.
  • To read the events themselves, call GET /triggers/{id}/events after the message.
  • The protocol also provides a type: "event" message (a single event, with its metadata field, without event_count): handle both types.

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.

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:

Terminal window
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-2e6d3f1f7c11
event: event
data: {"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_event messages, 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 a dropped message tells how many:
event: dropped
data: {"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-ID is not supported. The id: 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: use GET /triggers/{id}/events for a complete history.

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 the connection when it is no longer needed
eventSource.close(); // EventSource
controller.abort(); // fetchEventSource
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 };
}

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-Id on POST /triggers/:id/events and /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 source of the event message (of type event or batch_event) carries client_id. A tab skips the event only if source.auth_type is jwt and source.client_id is 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_id and are counted everywhere.
  • Public streams: client_id is never exposed. Anonymous readers, and those whose access comes only from the trigger's public visibility, receive a public source reduced to its type.

The ID is not stored and is not used as an idempotency key.

Private streams authenticate by header, like the rest of the API:

  • Authorization: Bearer <access_token> (JWT);
  • X-API-Key: <key> with the trigger:stats scope (see API Keys).

For a connection that reopens (network, restart), start again from a fresh access token (valid for 15 minutes, see Authentication).

  1. Handle reconnections - Handle errors and reopen the stream with a fresh token

  2. Close unused connections - Avoid resource leaks

  3. Limit the buffer - Do not keep too many events in memory

  4. Use the heartbeat - Watch the heartbeats to detect disconnections

  5. Batch UI updates - Avoid re-rendering on every event

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).