APIs & Data Architecture Real-Time & Streaming

18. Real-Time Streaming & Webhook Signatures

Stream real-time telemetry over SSE and WebSockets, verify incoming webhook signatures with timing-safe HMAC, and prevent replay attacks.

realtime-webhooks.ts
typescript
import { timingSafeEqual, createHmac } from 'node:crypto';
// Timing-Attack Safe HMAC-SHA256 Webhook Verification
export function verifyWebhookSignature(
rawBody: string,
signatureHeader: string,
secretKey: string
): boolean {
const hmac = createHmac('sha256', secretKey);
const expectedSignature = Buffer.from('sha256=' + hmac.update(rawBody).digest('hex'), 'utf8');
const incomingSignature = Buffer.from(signatureHeader, 'utf8');
if (expectedSignature.length !== incomingSignature.length) return false;
return timingSafeEqual(expectedSignature, incomingSignature);
}

Real-Time Streaming & Webhook Signatures

Choosing between unidirectional Server-Sent Events (SSE) and bidirectional WebSockets, and protecting webhook endpoints with timing-safe signature verification.

ProtocolDirectionTransport & OverheadIdeal Use Case
Short PollingClient → ServerFrequent HTTP GETs; high header overheadLow-frequency status checks, legacy fallback
Long PollingServer → Client (Held)Connection held open until event; high server churnEnvironments where WebSockets/SSE are blocked by firewalls
Server-Sent Events (SSE)Server → ClientHTTP/2 multiplexed, auto-reconnect, 0 socket overheadAI LLM token streams, live market tickers, telemetry
WebSocketsFull BidirectionalRaw TCP frames (ws:// / wss://), 2–10 byte framingMultiplayer gaming, collaborative whiteboards, live chat
Server-Sent Events (SSE) Stream Disconnected
HTTP/2 Unidirectional Stream
Click "Connect SSE Stream" to receive real-time data frames.
Webhook HMAC-SHA256 Signer Timing-Safe Verification
Calculated X-Signature-256:

Calculating...