Real-Time Log Event Aggregation in React
Data Structure DesignModel answerLast updated
Design and build a React component that ingests a real-time event stream, aggregates stats per category, handles out-of-order timestamps, and throttles re-renders for high throughput.
You are tasked with implementing a front-end dashboard component in React that processes an incoming stream of structured log events and displays live aggregated statistics.
Event Format
Every event emitted by the stream has the following structure:
category: A string indicating the source system (e.g.,"auth","checkout").timestamp: A string formatted as an ISO-8601 date (e.g.,"2025-10-24T14:32:00Z") or an epoch integer in milliseconds (e.g.,1761316320000).
Example event:
{ "category": "auth", "timestamp": "2025-10-24T14:32:00Z" }
Functional Requirements
- Stream Consumption: Create a component (or custom React hook) that accepts a subscription callback (e.g.,
subscribe(onEvent)). - Aggregation: Store and update statistics grouped by
category:- Frequency: The total event count for that category.
- Last Seen: The most recent event timestamp encountered for that category.
- UI Display: Render a sorted table or list updating dynamically as new logs arrive.
- Empty State: Show a user-friendly message when no events have been recorded yet.
Performance & Data Integrity Constraints
- Logs may arrive out-of-order due to network latency; "Last Seen" must represent the maximum logical timestamp observed for that category, not simply the arrival order.
- The stream can transmit hundreds or thousands of events per second. Your solution must prevent high-frequency re-renders from degrading UI performance.
- Malformed timestamps should not crash the application; malformed events missing a category should be gracefully ignored.
Hints
Hint 1
How can you avoid copying a Map on every single incoming event while ensuring React re-renders when data changes?
Hint 2
Consider buffering incoming events over small time windows (such as animation frames) rather than triggering state updates per event.
Hint 3
What strategy guarantees that out-of-order log timestamps do not overwrite newer timestamps with older values?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Overview
Building a high-throughput event aggregator in React requires decoupling data ingestion from UI rendering. A common failure mode in live dashboard interfaces is updating React state directly on every event callback, causing excessive renders that freeze the browser UI under high event rates.
To address this, the design uses two key techniques:
- In-memory ref storage: Store aggregate metrics inside a mutable JS
Mapwrapped in a ReactuseRef. This allows $O(1)$ updates without incurring React state reconciliation overhead per event. - Frame-throttled batching: Queue events into a pending buffer and flush them once per frame using
requestAnimationFrame. This caps rendering at roughly 60 FPS regardless of whether 10 or 10,000 events arrive per second.
Data Rules & Parsing Strategy
- Timestamp Parsing: Parse string or numeric timestamps into epoch milliseconds (
ms). Keep track ofMath.max(existingMax, newTimestampMs)to handle out-of-order arrival correctly. - Malformed Inputs: Events lacking a valid category string are discarded. If a timestamp is invalid or unparseable, increment the count but leave
lastSeenMsunchanged (ornullif no valid timestamp has ever been seen). - Data Display: Format output dates in ISO/UTC format and display sorted by highest event frequency first.
React Implementation
import React, { useEffect, useRef, useReducer } from "react";
// ==========================================
// Pure Aggregation & Parsing Helpers
// ==========================================
export function parseTimestamp(ts) {
if (typeof ts === "number") return Number.isFinite(ts) ? ts : null;
if (typeof ts === "string") {
const parsed = Date.parse(ts);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
export function updateStatsMap(statsMap, event) {
const category = event?.category;
if (typeof category !== "string" || !category.trim()) return;
const eventTimeMs = parseTimestamp(event.timestamp);
const existing = statsMap.get(category);
if (!existing) {
statsMap.set(category, {
count: 1,
lastSeenMs: eventTimeMs,
});
return;
}
existing.count += 1;
if (
eventTimeMs !== null &&
(existing.lastSeenMs === null || eventTimeMs > existing.lastSeenMs)
) {
existing.lastSeenMs = eventTimeMs;
}
}
// ==========================================
// Custom Hook: Stream Aggregator
// ==========================================
export function useLogAggregator(subscribe) {
const statsMapRef = useRef(new Map());
const pendingBufferRef = useRef([]);
const animFrameIdRef = useRef(0);
// Simple render trigger
const [, forceUpdate] = useReducer((x) => x + 1, 0);
useEffect(() => {
const flushBuffer = () => {
animFrameIdRef.current = 0;
const batch = pendingBufferRef.current;
pendingBufferRef.current = [];
for (const event of batch) {
updateStatsMap(statsMapRef.current, event);
}
forceUpdate();
};
const handleEvent = (event) => {
pendingBufferRef.current.push(event);
if (!animFrameIdRef.current) {
animFrameIdRef.current = requestAnimationFrame(flushBuffer);
}
};
const unsubscribe = subscribe(handleEvent);
return () => {
if (typeof unsubscribe === "function") unsubscribe();
if (animFrameIdRef.current) {
cancelAnimationFrame(animFrameIdRef.current);
animFrameIdRef.current = 0;
}
};
}, [subscribe]);
// Snapshot map into an array for rendering
return Array.from(statsMapRef.current.entries())
.map(([category, info]) => ({
category,
count: info.count,
lastSeenMs: info.lastSeenMs,
}))
.sort((a, b) => b.count - a.count || a.category.localeCompare(b.category));
}
// ==========================================
// UI Component
// ==========================================
function formatTimestamp(ms) {
return ms !== null ? new Date(ms).toISOString() : "—";
}
export function LogAggregationTable({ subscribe }) {
const rows = useLogAggregator(subscribe);
if (rows.length === 0) {
return <div className="empty-state">Waiting for events...</div>;
}
return (
<table border="1" cellPadding="8" cellSpacing="0">
<thead>
<tr>
<th>Category</th>
<th>Frequency</th>
<th>Last Update (UTC)</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.category}>
<td>{row.category}</td>
<td>{row.count}</td>
<td>{formatTimestamp(row.lastSeenMs)}</td>
</tr>
))}
</tbody>
</table>
);
}
Complexity & Performance Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Event Ingest (Buffer) | $O(1)$ amortized push | $O(B)$ where $B$ is events received per frame |
| Batch Flush | $O(B)$ per frame | $O(1)$ additional space |
| Render Snapshot & Sort | $O(K \log K)$ where $K$ is active categories | $O(K)$ array creation |
Key Trade-offs
-
useRef+useReducervs standarduseState:- Standard
useStatewith immutableMapcopies requires cloning the map ($O(K)$ space/time) on every batch, and causes immediate component updates per batch dispatch. - Using a mutable
useRefallows constant-time mutations inside the event loop, triggering a re-render explicitly viaforceUpdate().
- Standard
-
Frame-Rate Throttling (
requestAnimationFrame):- If 5,000 logs arrive per second, an unthrottled React component attempts 5,000 renders/sec, causing main-thread blockage and frame drops.
- Grouping updates into
requestAnimationFrameguarantees UI updates occur at most once per screen refresh interval (typically ~60Hz or ~144Hz).
-
Memory Leaks and Cleanup:
- Unsubscribing from the log provider inside
useEffectcleanup prevents dangling listeners. - Calling
cancelAnimationFrameprevents scheduled state changes after a component unmounts.
- Unsubscribing from the log provider inside