Skip to content

SSE real-time push ​

TodoAI's "real-time" has three layers: server → SSE → browser → cross-component events. Each has its own boundary and constraints.

SSE Streaming

Three independent SSE streams ​

StrategyTerminal subscribes to three streams in parallel, each with its own purpose:

EndpointPurposePoll cadence
/api/strategy/eventsStrategy BUY/SELL/HOLD/ERROR events2.5s
/api/strategy/reasoningReasoning steps (while generating)800ms
/api/user/stats/streamwinStreak / winRate snapshot + pushes15s heartbeat

Each one:

  • Authenticates with getServerSession (PR1–PR3 IDOR)
  • Registered with HMR kill-switch (globalThis symbol); old controllers force-closed on HMR reload
  • Checks closed flag before enqueue + try/catch TypeError to defend against controller race
  • Sets Cache-Control: no-cache, no-transform, X-Accel-Buffering: no (prevents nginx buffering)

The terminal accumulates logs in useState, dedup by id + capped at TERMINAL_MAX_LOGS = 200.

In-process pub/sub: profit-broadcaster ​

When a close path (engine / panic / manual close) completes, we want every subscribed SSE client to push new data immediately. We cannot have each writer push directly to SSE controllers — they belong to different requests, and shouldn't know about subscribers.

src/lib/profit-broadcaster.ts is a single-process pub/sub mediator:

ts
// Writer (any close path)
broadcast(userId, {
  type: 'profit_record_created',
  pnl, pnlPercent,
});

// Reader (/api/user/stats/stream route)
unsubscribe = subscribe(userId, async () => {
  await computeUserStats(userId);
  safeEnqueue(encoder.encode(...));
});

The writer carries no business logic — it only signals "something happened". The reader recomputes from the DB on each signal and pushes.

Current scope is single-process (Map<userId, Set>). Multi-instance deployments need to swap to Redis pub/sub (Redis is already in the stack via Upstash for tier cache).

Cross-component UI events: qt:open-settings ​

StrategyTerminal and Sidebar live in different parts of the tree. React context communication requires lifting state up or Zustand/Redux. For one-off coordination, a plain window event is the simplest:

ts
// StrategyTerminal
if (data.remediationCode) {
  window.dispatchEvent(new CustomEvent('qt:open-settings', {
    detail: { code: data.remediationCode, source: 'strategy_terminal' },
  }));
}

// Sidebar
useEffect(() => {
  const onOpenSettings = () => {
    setLocalMode(tradingMode);
    setShowConfig(true);
  };
  window.addEventListener('qt:open-settings', onOpenSettings);
  return () => window.removeEventListener('qt:open-settings', onOpenSettings);
}, [tradingMode]);

Conventions:

  • Event names use the qt:* namespace
  • Payload stays small, only essential IDs
  • Sidebar is the canonical listener for qt:open-settings — new triggers should reuse the same channel rather than introducing a second

HMR safety ​

In Next.js dev mode, module reloading re-evaluates route handlers, but the old instance's setInterval callbacks keep running. If not handled:

  • Old callbacks send data to a controller already replaced by the new module → ERR_INVALID_STATE: Controller is already closed
  • Multiple old polls run simultaneously → data doubled

Solution: store intervals / controllers on globalThis[symbol]; on every module evaluation, clear the old instances first.

See /api/strategy/events's HMR_INTERVALS_KEY implementation.

Why SSE instead of WebSocket? ​

We considered WebSocket. We chose SSE in the end:

  • Browser-native EventSource with auto-reconnect
  • HTTP/1.1 long connection, easy through reverse proxies
  • Server-to-client push only is enough (we don't need bi-directional)
  • Heartbeat (just a : heartbeat comment line) can be piggybacked within 15s

If we need bi-directional in the future (e.g. cancelling a running backtest from the client), we'll switch to WS.

TodoAI · Turn trading ideas into automated strategies