KatInterview

Managing a Live Event Stream with Pause and Statistics

Data Structure DesignModel answer
MediumModel answerData Structure Designreacthooksstate-management

Last updated

Build a React hook that processes a high-speed event stream with deduplication, sorting, memory limits, pause/resume, and rolling time-window metrics.

Live Event Stream Manager

You need to build state management logic for a dashboard that displays a continuous stream of incoming events. The stream can be fast and chaotic—events may arrive in bursts, out of chronological order, or with duplicate identifiers.

Your job is to implement a React hook called useEventFeed that handles this stream cleanly.

What the hook must do

  1. Connect to the stream: Use the provided subscribe function when the component mounts, and properly clean up the subscription when it unmounts.

  2. Remove duplicates and maintain order: Each event has a unique id. If the same id arrives twice, ignore the second occurrence. Display events sorted by timestamp in descending order (most recent first), regardless of arrival sequence.

  3. Limit memory usage: Keep at most maxEvents in the displayed list. When this limit is exceeded, discard the oldest events by timestamp.

  4. Support pause and resume: Provide isPaused, pause(), and resume() functions. While paused, continue receiving and processing events in the background, but don't update the visible list. When resumed, the display should immediately reflect all events that arrived during the pause (respecting the maxEvents limit).

  5. Compute rolling statistics: Track metrics over a sliding time window (default 30 seconds, configurable via windowMs):

    • Total count of events in the window
    • Event rate (events per second)
    • Average of the value field across events in the window

    These statistics must update periodically and decay to zero during prolonged quiet periods, even if no new events arrive.

Interface

interface FeedEvent {
  id: string;
  type: 'order' | 'trade' | 'alert';
  timestamp: number; // milliseconds since epoch
  value: number;
}

interface UseEventFeedOptions {
  subscribe: (onEvent: (event: FeedEvent) => void) => () => void;
  windowMs?: number; // default: 30000
  maxEvents?: number; // default: 200
  statIntervalMs?: number; // default: 1000
}

interface UseEventFeedResult {
  events: FeedEvent[];
  eventsByType: Record<string, FeedEvent[]>;
  stats: {
    count: number;
    ratePerSecond: number;
    averageValue: number;
  };
  isPaused: boolean;
  pause: () => void;
  resume: () => void;
}

function useEventFeed(options: UseEventFeedOptions): UseEventFeedResult;

Example behavior

// Events arrive in this sequence:
// t=1000: { id: 'A', type: 'trade', timestamp: 1000, value: 50 }
// t=1050: { id: 'C', type: 'trade', timestamp: 3000, value: 100 } (out of order)
// t=1100: { id: 'B', type: 'order', timestamp: 2000, value: 70 }
// t=1150: { id: 'A', type: 'trade', timestamp: 1000, value: 50 } (duplicate)

// The events array after t=1150 should be:
// [C, B, A]  (sorted by timestamp descending; duplicate A was ignored)

Constraints

  • maxEvents ranges from 10 to 5,000
  • The stream can send up to 500 events in a 50ms burst
  • All timestamps are positive integers
  • If no events arrive for longer than windowMs, statistics should drop to zero

Hints

Hint 1

Separate event ingestion from UI updates to handle bursts efficiently—use refs to batch incoming events and flush them to state in one render cycle.

Hint 2

Store the canonical event list in a ref that's always sorted and bounded. When paused, keep processing events into this ref but stop syncing it to React state.

Hint 3

Track statistics in time buckets (e.g., one bucket per second) so you can efficiently drop old data. Run a periodic timer to prune expired buckets and recompute stats, ensuring they decay even when the stream is quiet.