Skip to main content

Push flag changes instantly via SSE or gRPC streaming — connection lifecycle, reconnection, and scaling

Last updated November 21, 2026

Real-Time Updates

Flaggr supports two real-time update mechanisms for pushing flag changes to connected clients without polling: Server-Sent Events (SSE) and gRPC streaming.

How a change reaches your client

A flag change in the console reaches @flaggr/sdk clients that stream from the data plane like this:

The write path commits before fanout starts, so stream subscribers never wait on version or audit inserts. As a safety net for missed notifications, each data plane stream also checks for changes every 15 seconds.

SSE (Server-Sent Events)

The default real-time protocol for browser clients.

Data Plane Stream (@flaggr/sdk)

GET https://api.flaggr.dev/api/flags/stream?serviceId=web-app&environment=production
Authorization: Bearer fgr_your_sdk_key

This is the stream @flaggr/sdk opens in stream mode. It reads the key only from the Authorization header, and environment defaults to production. It sends named events:

EventData
configuration_syncOn connect: every flag of the service and environment ({ type, serviceId, environment, flags, version, timestamp })
configuration_deltaAfter a change: the changed flags in flags and the keys of removed flags in removed
heartbeatEvery 30 seconds: { timestamp, version }
access_revokedSent once before the stream closes because access is gone, { type, reason, message, timestamp }. reason is access_revoked or reauthorization_failed (see Reconnection)

Named events don't reach an onmessage handler: a client listens for each event name, as @flaggr/sdk does.

Streaming with a key needs @flaggr/sdk 0.5.0 or later. 0.4.0 opens an EventSource with the key in ?token=, which api.flaggr.dev refuses (401), and it doesn't load as an ES module; see TypeScript SDK.

Connect Stream

GET https://flaggr.dev/api/connect/stream?serviceId=web-app&environment=production&clientId=client-1
Authorization: Bearer fgr_your_sdk_key

Every connection needs a credential: /api/connect/stream has no keyless mode.

Client ID

Each client should provide a unique clientId for connection tracking and deduplication.

Query parameters:

ParameterRequiredDescription
serviceIdYesService to subscribe to
environmentYesdevelopment, staging, or production
clientIdYesUnique client identifier
flagKeyNoSubscribe to specific flags (repeatable)
token / apiTokenNoFor EventSource clients: a read-only SDK key or a signed-in session's ID token. Send any other credential in the Authorization header

Event Format

Events arrive as unnamed JSON messages. eventType is the proto enum's number, and flag uses the Connect flag shape (numeric type, wrapped defaultValue):

{
  "eventType": 2,
  "flagKey": "checkout-v2",
  "flag": {
    "key": "checkout-v2",
    "type": 1,
    "enabled": true,
    "defaultValue": { "boolValue": true }
  },
  "timestamp": "2025-07-20T10:30:00Z",
  "configVersion": "1721471400000"
}

flag also carries the flag's name, description, service, environment, tags and timestamps.

Event types:

eventTypeNameDescription
7PROVIDER_READYSent once on connect; carries no flags
1CREATEDNew flag created (with flag)
2UPDATEDExisting flag changed, toggles included (with flag)
3DELETEDFlag removed
5SYNCFull configuration sync
6HEARTBEATKeep-alive (every 30 seconds)

Browser Usage

EventSource can't send headers, so a browser passes the key in ?token=. That takes only a read-only SDK key (an evaluation-only or read-only fgr_ key, or a JWT whose scopes are all read) or a signed-in session's ID token; any other credential in the URL gets 401. With any other key, use @flaggr/sdk, which streams over fetch with the key in the Authorization header.

const eventSource = new EventSource(
  'https://flaggr.dev/api/connect/stream?serviceId=web-app&environment=production&clientId=browser-1&token=fgr_your_read_only_sdk_key'
)
 
eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data)
 
  if (data.eventType === 2) { // UPDATED
    console.log(`Flag ${data.flagKey} changed`)
    // Update local flag cache
  }
}
 
eventSource.onerror = () => {
  console.log('Connection lost, EventSource will auto-reconnect')
}
Auto-Reconnection

The browser's EventSource reconnects on its own after the connection drops. @flaggr/sdk reconnects with exponential backoff (1 second, doubling to 30 seconds). If the stream refuses the key (401/403), it stops retrying and polls the flags it watches instead, every batchIntervalMs (default 2 seconds).

SDK Integration

@flaggr/sdk handles the stream itself. In stream mode it evaluates the flags it can locally from the streamed configuration and notifies listeners when a value changes:

import { createFlaggr } from '@flaggr/sdk'
 
const client = createFlaggr({
  serviceId: 'web-app',
  apiKey: process.env.FLAGGR_SDK_KEY, // read-only SDK key
  environment: 'production',
  updateMode: 'stream', // SSE from https://api.flaggr.dev
})
 
const stop = client.onFlagChange('checkout-v2', ({ newValue }) => {
  console.log('checkout-v2 is now', newValue)
})

The React hooks from @flaggr/sdk/react re-render when a value changes.

gRPC Streaming

Server-side streaming with binary protobuf messages, for clients generated from Flaggr's service definitions.

Connection Setup

The data plane at api.flaggr.dev serves flaggr.v1.FlagStreamService/StreamFlags over gRPC-Web and the Connect protocol, and flaggr.dev serves it over gRPC-Web under /api/grpc-web (see Protocols). Send the key in the Authorization header. No generated client for these services is published; from TypeScript, @flaggr/sdk streams over SSE instead.

Streaming Lifecycle

Client                          Server
  │                               │
  ├── StreamFlags(request) ──────►│
  │                               │
  │◄── SYNC (one per flag) ───────│
  │                               │
  │        ... time passes ...    │
  │                               │
  │◄── UPDATED (flag changed) ───│
  │◄── CREATED (new flag) ───────│
  │                               │
  │        ... heartbeat ...      │
  │◄── HEARTBEAT ────────────────│
  │                               │

Reconnection

Streams on flaggr.dev (/api/connect/stream, /api/flags/stream, gRPC-Web StreamFlags, and the console's /api/flags/{key}/metrics/stream and /api/ai/safety-alerts/stream) re-check their access about once a minute. If your key is revoked or expires, your membership is removed, an access override hides the service or environment, or the service is deleted, the stream sends one { "type": "access_revoked" } message (gRPC-Web: an end-stream permission_denied) and closes. A re-check that fails because Flaggr couldn't look up your credential (it couldn't read your user, key or token, or your SSO connection, from its storage) isn't a revocation: the stream stays open through one such failure, and two in a row close it with reason: "reauthorization_failed" (gRPC-Web: unavailable). If access is still there, the stream applies changed overrides to what it forwards. Clients should reconnect as usual: @flaggr/sdk does, with backoff, and reconnecting authorizes from scratch (a revoked key then gets 401). Console streams that pass a session ID token in ?token= end when that token expires: the Action center's live alerts reconnect with a fresh token, and a flag's live evaluation rate falls back to polling.

Streams on api.flaggr.dev (/api/flags/stream, and Connect and gRPC-Web StreamFlags and SyncFlags) re-check access too. A data plane stream's first re-check comes 30–60 seconds after it opens (spread at random), then one every 60 seconds. Each re-check looks the key up again, because the data plane caches no credentials. So the stream closes within about a minute when the key is revoked or rotated, its project is deleted, or its scopes no longer cover the service, environment or flags the stream names:

  • SSE: one final named event, event: access_revoked, with {"type":"access_revoked","reason":"access_revoked","message":"Access to this stream was revoked or has expired; reconnect to authorize again.","timestamp":…}, then the stream closes.
  • Connect and gRPC-Web: the stream ends with unauthenticated when the key no longer authenticates, and permission_denied when it no longer covers the stream. (flaggr.dev answers permission_denied for both.)
  • A failed lookup is tolerated once. Two in a row close the stream with reason reauthorization_failed and the message "Access to this stream couldn't be confirmed; reconnect to authorize again." (Connect and gRPC-Web: unavailable).

On the data plane, a key with an expiry ends its stream at that expiry, with no access_revoked event. A new connection with a revoked fgr_ key is refused at once (401), so @flaggr/sdk can't reconnect with it.

Delivery Architecture

Data Plane: Postgres Notifications

Every flag write on the control plane sends a Postgres NOTIFY on flaggr_flags_changed. Data plane instances listen on that channel, reload the affected service's configuration and push configuration_delta events (gRPC: CREATED, UPDATED, DELETED) to their streams. Each stream also checks for changes every 15 seconds, which covers missed notifications.

Control Plane: Redis Pub/Sub

When Redis is configured, flag changes are published to the flaggr:updates Redis channel. The control plane's stream handlers subscribe to it for instant delivery.

Flag Update → Redis PUBLISH → All Stream Handlers → Connected Clients

Fallback Without Redis

Without Redis, the Connect stream (/api/connect/stream) polls the database every 5 seconds, and /api/flags/stream on flaggr.dev gets only the changes made on its own instance.

Scaling Note

Without Redis, in-memory broadcast only reaches clients connected to the same instance. For multi-instance deployments, Redis is required for cross-instance flag change delivery on the control plane.

Protocol Comparison

FeatureSSEgRPC Streaming
Browser supportNativeVia gRPC-Web
Server supportYes (@flaggr/sdk streams over fetch)Yes
Auto-reconnectBrowser-native (EventSource), backoff in @flaggr/sdkYour client's logic
EncodingJSON textBinary protobuf
Connection limit6 per domain over HTTP/1.1Multiplexed over one HTTP/2 connection
Best forBrowsers, SPAs, dashboardsMicroservices

Connection Monitoring

Track connection state in your application:

import { ConnectionState } from '@flaggr/sdk'
 
const stop = client.onConnectionStateChange((state) => {
  // connecting -> connected -> disconnected -> error
  console.log('Connection state:', state)
 
  if (state === ConnectionState.ERROR) {
    // Show fallback UI or use cached values
  }
})

The useConnectionState() React hook provides this in components (meaningful with updateMode: 'stream'):

import { ConnectionState } from '@flaggr/sdk'
import { useConnectionState } from '@flaggr/sdk/react'
 
function StatusBadge() {
  const state = useConnectionState()
  return state === ConnectionState.CONNECTED
    ? <span className="text-green-500">Live</span>
    : <span className="text-yellow-500">Reconnecting...</span>
}

Metrics

Real-time connections are tracked via Prometheus:

MetricDescription
flaggr_grpc_active_connectionsActive gRPC streaming connections
flaggr_grpc_active_streamsActive gRPC streams
flaggr_grpc_messages_totalTotal gRPC messages (by direction)
flaggr_sse_active_connectionsActive SSE connections on the control plane, by endpoint (connect or legacy)