Managing a Live Event Stream with Pause and Statistics
Data Structure DesignModel answerLast 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
-
Connect to the stream: Use the provided
subscribefunction when the component mounts, and properly clean up the subscription when it unmounts. -
Remove duplicates and maintain order: Each event has a unique
id. If the sameidarrives twice, ignore the second occurrence. Display events sorted bytimestampin descending order (most recent first), regardless of arrival sequence. -
Limit memory usage: Keep at most
maxEventsin the displayed list. When this limit is exceeded, discard the oldest events by timestamp. -
Support pause and resume: Provide
isPaused,pause(), andresume()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 themaxEventslimit). -
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
valuefield 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
maxEventsranges 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Efficient Event Stream Processing
Core Strategy
The main challenge is handling high-frequency bursts without triggering excessive re-renders. The solution separates event ingestion (fast, runs on every event) from UI updates (batched, runs once per frame).
Architecture:
- Hot path: When an event arrives, perform minimal work—check for duplicates using hash lookups, add to a pending buffer, update statistics buckets, and schedule a single flush using
requestAnimationFrame. This path never triggers React re-renders. - Batch flush: Once per animation frame, sort the pending buffer, merge it with the existing sorted list, truncate to
maxEvents, and update React state. If paused, skip the state update but still maintain the internal list. - Canonical storage: Keep the source of truth in a ref (
listRef) that's always sorted and bounded. React state (events) is just a view of this ref. - Statistics tracking: Organize events into one-second buckets keyed by
Math.floor(timestamp / 1000). A periodic interval prunes expired buckets and recomputes metrics, ensuring statistics decay during quiet periods.
Why This Works
Deduplication: An event is rejected if its id exists in any of:
listIds(already displayed)pendingIds(buffered, not yet flushed)windowIds(within the statistics window)
Once an event is evicted from the list due to maxEvents, it cannot reappear. Eviction only happens when the list is full, at which point any incoming event older than the oldest retained event is immediately rejected.
Ordering: Each batch is sorted in descending timestamp order before merging with the already-sorted main list. Merging two sorted sequences produces a sorted result, maintaining the invariant regardless of arrival order.
Memory bounds: The merge operation outputs at most maxEvents items, automatically discarding the oldest entries.
Pause behavior: Events continue merging into listRef while paused. Resuming simply publishes the current state of listRef to React, which represents exactly what the user would have seen without pausing (subject to maxEvents).
Quiet periods: The statistics interval runs independently of event arrivals. After windowMs of silence, all bucket keys become stale and are deleted, causing count and rate to fall to zero.
Complexity Analysis
Let n = maxEvents, k = batch size per frame, B = windowMs / 1000 (number of buckets), W = events in the statistics window.
- Per-event ingestion: O(1) amortized—hash lookups and bucket updates
- Batch flush: O(k log k + n)—sort the batch, then linear merge (more efficient than inserting events one-by-one with binary search, which would be O(kn) due to array shifts)
- Statistics update: O(B + W)—iterate buckets and prune the deduplication set
- Space: O(n + B + W)
Edge Cases
- Duplicate within same burst: caught by
pendingIds - Event older than statistics window: still displayed if it fits, but excluded from metrics
- List at capacity: events older than the oldest retained entry are immediately dropped
- Duplicate after eviction: rejected via
windowIdsor age comparison - Unmount: cancels pending
requestAnimationFrame, clears interval, calls subscription teardown to prevent post-unmount state updates - Division by zero: average returns 0 when count is 0
- SSR compatibility: falls back to
setTimeoutifrequestAnimationFrameis unavailable - Unnecessary re-renders: statistics state update is skipped when values haven't changed
Trade-off to mention: Time-bucketing makes the window edge accurate to ±1 second. Exact millisecond precision would require a per-event queue, which complicates out-of-order handling and pruning.
Implementation
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
interface FeedEvent {
id: string;
type: 'order' | 'trade' | 'alert';
timestamp: number;
value: number;
}
interface UseEventFeedOptions {
subscribe: (onEvent: (event: FeedEvent) => void) => () => void;
windowMs?: number;
maxEvents?: number;
statIntervalMs?: number;
}
interface Stats {
count: number;
ratePerSecond: number;
averageValue: number;
}
function useEventFeed(options: UseEventFeedOptions) {
const {
subscribe,
windowMs = 30000,
maxEvents = 200,
statIntervalMs = 1000,
} = options;
const [events, setEvents] = useState<FeedEvent[]>([]);
const [stats, setStats] = useState<Stats>({
count: 0,
ratePerSecond: 0,
averageValue: 0,
});
const [isPaused, setIsPaused] = useState(false);
const listRef = useRef<FeedEvent[]>([]);
const listIds = useRef(new Set<string>());
const pendingBuffer = useRef<FeedEvent[]>([]);
const pendingIds = useRef(new Set<string>());
const flushScheduled = useRef(false);
const buckets = useRef(new Map<number, { count: number; sum: number }>());
const windowIds = useRef(new Set<string>());
const pausedRef = useRef(false);
pausedRef.current = isPaused;
const flush = useCallback(() => {
flushScheduled.current = false;
if (pendingBuffer.current.length === 0) return;
const batch = pendingBuffer.current.sort((a, b) => b.timestamp - a.timestamp);
pendingBuffer.current = [];
pendingIds.current.clear();
const merged: FeedEvent[] = [];
let i = 0, j = 0;
const list = listRef.current;
while (merged.length < maxEvents && (i < batch.length || j < list.length)) {
if (i >= batch.length) {
merged.push(list[j++]);
} else if (j >= list.length) {
merged.push(batch[i++]);
} else {
merged.push(batch[i].timestamp >= list[j].timestamp ? batch[i++] : list[j++]);
}
}
listRef.current = merged;
listIds.current = new Set(merged.map(e => e.id));
if (!pausedRef.current) {
setEvents([...merged]);
}
}, [maxEvents]);
const scheduleFlush = useCallback(() => {
if (flushScheduled.current) return;
flushScheduled.current = true;
const raf = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame : setTimeout;
raf(flush);
}, [flush]);
const onEvent = useCallback((event: FeedEvent) => {
if (listIds.current.has(event.id) || pendingIds.current.has(event.id) || windowIds.current.has(event.id)) {
return;
}
if (listRef.current.length >= maxEvents) {
const oldest = listRef.current[listRef.current.length - 1];
if (event.timestamp <= oldest.timestamp) return;
}
pendingBuffer.current.push(event);
pendingIds.current.add(event.id);
const bucketKey = Math.floor(event.timestamp / 1000);
const bucket = buckets.current.get(bucketKey) || { count: 0, sum: 0 };
bucket.count++;
bucket.sum += event.value;
buckets.current.set(bucketKey, bucket);
windowIds.current.add(event.id);
scheduleFlush();
}, [maxEvents, scheduleFlush]);
useEffect(() => {
const teardown = subscribe(onEvent);
return () => {
teardown();
if (flushScheduled.current) {
const caf = typeof cancelAnimationFrame !== 'undefined' ? cancelAnimationFrame : clearTimeout;
caf(flushScheduled.current as any);
}
};
}, [subscribe, onEvent]);
useEffect(() => {
const interval = setInterval(() => {
const now = Date.now();
const cutoff = Math.floor((now - windowMs) / 1000);
let count = 0, sum = 0;
for (const [key, bucket] of buckets.current) {
if (key <= cutoff) {
buckets.current.delete(key);
} else {
count += bucket.count;
sum += bucket.sum;
}
}
const newWindowIds = new Set<string>();
for (const event of listRef.current) {
if (event.timestamp >= now - windowMs) {
newWindowIds.add(event.id);
}
}
windowIds.current = newWindowIds;
const newStats = {
count,
ratePerSecond: count / (windowMs / 1000),
averageValue: count > 0 ? sum / count : 0,
};
setStats(prev =>
prev.count === newStats.count &&
prev.ratePerSecond === newStats.ratePerSecond &&
prev.averageValue === newStats.averageValue
? prev
: newStats
);
}, statIntervalMs);
return () => clearInterval(interval);
}, [windowMs, statIntervalMs]);
const pause = useCallback(() => setIsPaused(true), []);
const resume = useCallback(() => {
setIsPaused(false);
setEvents([...listRef.current]);
}, []);
const eventsByType = useMemo(() => {
const byType: Record<string, FeedEvent[]> = {};
for (const event of events) {
if (!byType[event.type]) byType[event.type] = [];
byType[event.type].push(event);
}
return byType;
}, [events]);
return { events, eventsByType, stats, isPaused, pause, resume };
}
Key Takeaways
This problem tests your ability to optimize React performance under high load, manage complex state with refs and batching, and implement efficient algorithms (merge sort, time-windowed aggregation). Interviewers look for candidates who can reason about rendering costs, choose appropriate data structures, and handle edge cases like unmounting, SSR, and data staleness.