Real-Time Log Category Aggregator Component in React
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Prompt
Build a compact React UI module that summarizes live telemetry records arriving continuously from an event stream.
Each event object delivered by the stream conforms to the following shape:
category(string): logical group name for the record (such as"billing"or"ingest").timestamp(string | number): when the event occurred, encoded either as an ISO-8601 timestamp string or as Unix epoch milliseconds.
Sample incoming payload:
{ "category": "billing", "timestamp": "2026-04-18T14:20:10Z" }
For instance, if "billing" receives "2026-04-18T14:20:10Z", "ingest" receives 1776522025000 (2026-04-18T14:20:25Z), and a delayed "billing" retry arrives with "2026-04-18T14:19:55Z", then "billing" should show a count of 2 while retaining 2026-04-18T14:20:10Z as its latest timestamp, and "ingest" should show a count of 1 at 2026-04-18T14:20:25Z.
Design and implement a React component (plus any supporting hooks or pure helper modules) that meets these specifications:
- Stream ingestion: Subscribe to an asynchronous event feed (for example via a
subscribe(onEvent)callback contract or a simulated timer producer) and clean up properly on unmount. - Per-category state in a
Map: Maintain running per-categorystatistics in memory using a JavaScriptMap(or justify an alternative structure), smoothly accommodating unseen categories at any point in the stream's lifetime. - Live summary UI: Render an updating table or list displaying every observed
category, its event count (cumulative events seen in that category), and its latest event time (the maximum validtimestamprecorded for that category). - Timestamp & empty-stream semantics: Explain how you normalize and compare mixed ISO-8601 strings and numeric timestamps (including out-of-order or malformed inputs), and define what renders before any events arrive.
Scope & Expectations
- Manage
Mapstate immutably so React reliably detects updates, while decoupling high-frequency stream arrivals from render frequency and preventing duplicate subscriptions under React Strict Mode. - Normalize ISO-8601 strings (including time-zone offsets) and bounded epoch-millisecond numbers into a canonical numeric representation so chronological comparisons stay exact even when events arrive out of order or carry invalid timestamps.
- Render an accessible, deterministically sorted table keyed by category with clear fallback states for empty streams and unparseable timestamps.
Step-by-step walkthrough
Define the behavior, edge cases, and state shape
Before writing JSX, lock down the exact rules for how incoming events update state and how missing or out-of-order data should appear on screen:
- Per-category state shape: Store
{ count, lastMs }for each category inside aMap<string, { count: number, lastMs: number | null }>. Herecountis the total number of events seen for that category, andlastMsis the latest valid event time in epoch milliseconds (the number of milliseconds since January 1, 1970 at00:00:00 UTC), ornullif no event in that category had a valid timestamp yet. - "Last update" tracks event time, not arrival time: Distributed log streams often deliver retries or multi-server logs out of order. If an older log arrives late,
countstill increments by1, whilelastMsadvances only viamax(lastMs, eventMs)so the displayed timestamp never jumps backward. - Malformed events never crash the UI: An event with an unparseable timestamp still happened, so we increment
countand leavelastMsunchanged (rendering"—"iflastMsis stillnull). An event with a missing or blankcategoryfalls into an"(unknown)"bucket so total event counts stay accurate. - Keep numbers in state, format strings in JSX: Storing epoch milliseconds makes comparisons fast and exact; human-readable local time strings are formatted only at render time.
- Empty stream state: Before the first event arrives, render
"No events yet."rather than a bare table header with zero rows.
Incoming event Map<category, { count, lastMs }> Rendered table row ────────────────────────────── ────────────────────────────────────── ───────────────────────────────── { category: "billing", "billing" => { | billing | 1 | 4/18/2026, ... | timestamp: "...14:20:10Z" } count: 1, lastMs: 1776522010000 }- Per-category state shape: Store
Normalize mixed timestamps to epoch milliseconds
Incoming events carry either an ISO-8601 string (the international text standard for dates and times, such as
"2026-04-18T14:20:10Z") or an epoch millisecond number. Converting every valid timestamp into a single epoch millisecond number at ingestion avoids four subtle JavaScript traps:- Alphabetical string comparison gets order wrong:
"2026-04-18T16:21:00+02:00"and"2026-04-18T14:21:00Z"represent the exact same instant (1776522060000), and"2026-04-18T14:20:10.5Z" < "2026-04-18T14:20:10Z"evaluates totruealphabetically (.has a smaller character code thanZ) even though.5Zis half a second later. Date.parseresolves time-zone offsets:Date.parseconverts ISO strings withZor±HH:MMoffsets into UTC epoch milliseconds. (Note: in JavaScript, a date-time string without an offset like"2026-04-18T14:20:10"is interpreted in the browser's local time zone, so producers should always includeZor an explicit offset.)- Return
nullfor bad input, neverNaN: In JavaScript, bothNaN > xandNaN < xevaluate tofalse. Letting a singleNaNslip intolastMswould break future comparisons. - Guard JavaScript's
Daterange (±8.64e15ms):Number.isFinite(1e20)istrue, yetnew Date(1e20).toISOString()throws aRangeErrorbecause a JavaScriptDatespans at most±8.64e15milliseconds (±100,000,000days around 1970). Rejecting out-of-range numbers at ingestion prevents one corrupt number from crashing the component during render.
// logStats.js export const UNKNOWN_CATEGORY = "(unknown)"; // Largest absolute millisecond value a JavaScript Date can represent without throwing RangeError const MAX_DATE_MS = 8.64e15; export function toEpochMs(timestamp) { if (typeof timestamp === "number") { const isValidRange = Number.isFinite(timestamp) && Math.abs(timestamp) <= MAX_DATE_MS; return isValidRange ? timestamp : null; } if (typeof timestamp === "string") { const parsedMs = Date.parse(timestamp); return Number.isNaN(parsedMs) ? null : parsedMs; } return null; }Quick check on sample inputs: -
toEpochMs("2026-04-18T14:20:10Z")->1776522010000-toEpochMs(1776522025000)->1776522025000-toEpochMs("invalid-ts"),toEpochMs(undefined), andtoEpochMs(1e20)->null(If a backend ever sends numeric strings like"1776522010000", check/^-?\d+$/.test(timestamp)and convert viaNumber(timestamp)first, sinceDate.parsereturnsNaNfor bare millisecond strings in V8.)- Alphabetical string comparison gets order wrong:
Store per-category stats in an immutable Map
Why
Mapbeats a plain object{}: - Immune to prototype collisions: A prototype collision happens when an untrusted string key from external logs—such as"constructor","toString", or"__proto__"—clashes with built-in properties inherited fromObject.prototype. With{}in JavaScript,stats["constructor"]is already truthy before any log arrives! AMapkeeps user keys completely isolated from object methods. - Built for dynamic keys:MapgivesO(1)average-time.get()and.set(), tracks.sizedirectly, and iterates keys in first-seen insertion order.Why create a new
Mapon each update instead of mutating in place: React decides whether to re-render by checking referential equality (Object.is(oldState, newState)—whether both variables point to the exact same object in memory). If you callstats.set(category, ...)on the existingMapand pass that sameMaptosetStats(stats), React sees an identical object reference and skips rendering completely! Copyingnew Map(stats)(O(k)forkcategories) and replacing modified{ count, lastMs }objects gives React a fresh reference while keeping previous snapshots intact.Keep this logic in a pure function (a function whose return value depends only on its inputs and that never mutates its arguments or external variables), making it effortless to unit-test without mounting React:
// logStats.js (continued) function categoryOf(event) { const raw = event?.category; if (typeof raw !== "string") return UNKNOWN_CATEGORY; const trimmed = raw.trim(); return trimmed !== "" ? trimmed : UNKNOWN_CATEGORY; } export function applyEvents(stats, events) { // Return the exact same Map reference on an empty batch so React skips re-rendering if (events.length === 0) return stats; const next = new Map(stats); for (const event of events) { const category = categoryOf(event); const eventMs = toEpochMs(event?.timestamp); const previous = next.get(category); const count = previous ? previous.count + 1 : 1; let lastMs = previous ? previous.lastMs : null; if (eventMs !== null && (lastMs === null || eventMs > lastMs)) { lastMs = eventMs; } // Replace the entry object rather than mutating `previous` in place next.set(category, { count, lastMs }); } return next; } export function toRows(stats) { const rows = []; for (const [category, entry] of stats) { rows.push({ category, count: entry.count, lastMs: entry.lastMs }); } // Highest frequency first; break ties alphabetically so row order never flickers rows.sort((a, b) => b.count - a.count || a.category.localeCompare(b.category)); return rows; }Because
countis a sum andlastMsis a maximum,applyEventsis order-independent and batch-invariant: applying 100 events one by one produces the exact sameMapas applying all 100 in a single batch.Subscribe to the stream and batch renders with a ref
Accepting a
subscribe(onEvent)function that returns anunsubscribe()callback cleanly decouples our UI from the transport—whether events come from a WebSocket, Server-Sent Events (EventSource), or asetIntervalmock.Why buffer events instead of calling
setStatson every event? At 5 events/second, per-event state updates are fine. At 1,000 WebSocket messages/second, callingsetStatsper event triggers up to 1,000Mapcopies and 1,000 React renders per second—even though a 60 Hz monitor only draws one frame every16.7 ms. Instead, push incoming events into a React ref (useRef, a mutable box that persists across renders without triggering re-renders) and flush the buffer into React state every250 ms(at most 4 renders per second):Stream events (e.g. 1,000/s) useRef buffer 250 ms interval React UI ──────────────────────────── ───► pending.current.push(e) ──► drain batch & call ───► At most 4 calm (no re-render per arrival) [e1, e2, e3, ...] applyEvents(prev, batch) renders / second// LogStats.jsx import { useEffect, useMemo, useRef, useState } from "react"; import { applyEvents, toRows } from "./logStats.js"; export function useLogStats(subscribe, flushMs = 250) { const [stats, setStats] = useState(() => new Map()); // Buffer incoming events between flushes without triggering re-renders const pending = useRef([]); useEffect(() => { function flush() { if (pending.current.length === 0) return; // Drain the ref BEFORE calling setStats so the state updater stays pure const batch = pending.current; pending.current = []; setStats((previous) => applyEvents(previous, batch)); } const unsubscribe = subscribe((event) => { pending.current.push(event); }); const timerId = setInterval(flush, flushMs); return () => { unsubscribe(); clearInterval(timerId); pending.current = []; }; }, [subscribe, flushMs]); return stats; }Three React lifecycle details prevent subtle bugs here: 1. Drain
pending.currentoutsidesetStats: React may run(previous) => ...asynchronously during the next render, and in React Strict Mode (a development-only check that intentionally invokes state updaters and effects twice to catch side effects) calling an impure updater that mutatespending.currentinsidesetStatswould either see an already-cleared array on the second call or drop events. Capturingconst batch = pending.currentfirst makes(previous) => applyEvents(previous, batch)100% pure. 2. Clean up both subscription and timer: Strict Mode mounts, unmounts, and remounts every component once in development; forgettingunsubscribe()would leave two active listeners and double every count. 3. Keepsubscribereferentially stable: Definesubscribeat module scope or wrap it inuseCallbackin the parent so parent re-renders do not tear down and recreate the subscription.Render the live table and empty states
// LogStats.jsx (continued) function formatTime(ms) { return new Date(ms).toLocaleString(); } export function LogStatsTable({ subscribe, flushMs = 250 }) { const stats = useLogStats(subscribe, flushMs); const rows = useMemo(() => toRows(stats), [stats]); if (rows.length === 0) { return <p>No events yet.</p>; } return ( <table> <caption>Live log events by category</caption> <thead> <tr> <th scope="col">Category</th> <th scope="col">Frequency</th> <th scope="col">Last update</th> </tr> </thead> <tbody> {rows.map((row) => ( <tr key={row.category}> <td>{row.category}</td> <td>{row.count}</td> <td> {row.lastMs === null ? ( "—" ) : ( <time dateTime={new Date(row.lastMs).toISOString()}> {formatTime(row.lastMs)} </time> )} </td> </tr> ))} </tbody> </table> ); } const MOCK_CATEGORIES = ["billing", "ingest", "indexer"]; export function mockSubscribe(onEvent) { const timerId = setInterval(() => { const category = MOCK_CATEGORIES[Math.floor(Math.random() * MOCK_CATEGORIES.length)]; onEvent({ category, timestamp: new Date().toISOString() }); }, 200); return () => clearInterval(timerId); } export default function App() { return <LogStatsTable subscribe={mockSubscribe} />; }key={row.category}instead of array index: As frequencies change, rows swap positions; keying bycategorylets React track each category's<tr>accurately.<time dateTime={...}>: Preserves the exact UTC ISO timestamp in the DOM for automated tests and assistive tools while displaying friendly local time to the user.- Avoid
aria-liveon the whole<table>: Marking a table that updates 4 times per second as an ARIA live region floods screen readers with constant chatter.
Walk through a 5-event stream step by step
Let's trace five tricky events arriving either one by one or in a single
250 msflush (times shown in UTC for clarity):# Incoming event Map state after event (category: count @ UTC time) ─ ───────────────────────────────────────────────── ────────────────────────────────────────────────────────── 0 (initial mount) (empty Map) -> renders "No events yet." 1 { category: "billing", billing: 1 @ 14:20:10 timestamp: "2026-04-18T14:20:10Z" } 2 { category: "ingest", billing: 1 @ 14:20:10 | ingest: 1 @ 14:20:25 timestamp: 1776522025000 } 3 { category: "billing", billing: 2 @ 14:20:10 | ingest: 1 @ 14:20:25 timestamp: "2026-04-18T14:19:55Z" } (late!) (count increments to 2, lastMs stays 14:20:10) 4 { category: "billing", billing: 3 @ 14:21:00 | ingest: 1 @ 14:20:25 timestamp: "2026-04-18T16:21:00+02:00" } (+02:00 equals 14:21:00 UTC > 14:20:10 UTC, so it wins) 5 { category: "indexer", billing: 3 @ 14:21:00 | ingest: 1 @ 14:20:25 | indexer: 1 @ — timestamp: "invalid-ts" } (invalid!) (counted, lastMs stays null -> renders "—")Sorting by
countdescending and thencategoryascending renders three clean rows: 1.billing—3—14:21:00(in viewer's local time) 2.indexer—1——3.ingest—1—14:20:25
Intuition & how it works
Imagine operating a live stadium scoreboard while thousands of paper event slips pour out of a ticker machine. Instead of taping every paper slip onto a giant wall or repainting the scoreboard 1,000 times a second, you keep one compact tally card per category ({ count, lastMs }), let incoming slips collect in a small inbox tray for a quarter of a second, and update the tally cards in calm 4-times-per-second batches.
The naive approach fails on four fronts. Appending every raw log event to a React state array causes memory and render work to grow without bound as the stream runs. Mutating a JavaScript Map in place and passing the same Map back to setState leaves the screen frozen because React checks referential equality (Object.is, whether old and new state point to the exact same object in memory) and skips re-rendering. Comparing ISO-8601 date strings (like "2026-04-18T14:20:10Z") alphabetically mishandles time-zone offsets and fractional seconds, while calling setState on every single message overwhelms the browser's main thread during traffic spikes.
Trace a tiny 4-event burst to see how our solution handles each edge case:
1. { category: "billing", timestamp: "2026-04-18T14:20:10Z" } parses to epoch milliseconds 1776522010000 (14:20:10 UTC, milliseconds since Jan 1, 1970 UTC) and sets billing -> { count: 1, lastMs: 1776522010000 }.
2. { category: "billing", timestamp: "2026-04-18T14:19:55Z" } arrives out of order (14:19:55 UTC); count becomes 2, while max(lastMs, eventMs) keeps lastMs at 14:20:10 UTC.
3. { category: "billing", timestamp: "2026-04-18T16:21:00+02:00" } normalizes the +02:00 offset to 14:21:00 UTC (1776522060000), advancing billing to { count: 3, lastMs: 1776522060000 }.
4. { category: "indexer", timestamp: "invalid-ts" } fails parsing (null), safely recording indexer -> { count: 1, lastMs: null }, which renders "—" for the timestamp without losing the count or crashing the table.
Key points
- Compact, order-independent state:
Map<category, { count, lastMs }>usesO(k)memory forkdistinct categories regardless of how many millions of events stream past. Because sum (count) and maximum (lastMs) are commutative and associative, out-of-order and batched events produce identical totals. - Normalize timestamps to epoch milliseconds once at ingestion: Convert ISO-8601 strings via
Date.parseand accept finite numbers only within±8.64e15ms (the maximum span of a JavaScriptDate), turning invalid values intonullrather thanNaN. Format to local strings only during rendering. - Prefer
Mapover plain objects{}for dynamic log keys:Mapavoids prototype collisions (where untrusted category names like"constructor"or"__proto__"collide with built-in properties onObject.prototype), supportsO(1)average lookups, and exposes.sizedirectly. - Immutable updates inside a pure function: Keep
applyEvents(stats, events)as a pure function (output depends solely on inputs, with zero in-place mutation), cloningnew Map(stats)per batch so React detects the new reference and unit tests can verify every edge case without mounting DOM components. - Decouple arrival rate from render rate: Push incoming events into a React ref (
useRef, a mutable holder whose changes do not trigger re-renders) and flush on a250 msinterval (<= 4renders/second), draining the ref before callingsetStats((prev) => applyEvents(prev, batch)). - Clean subscription lifecycle: Subscribe inside
useEffectand unsubscribe + clear the interval on unmount, ensuring React Strict Mode (which mounts, unmounts, and remounts components once in development to surface cleanup bugs) never creates duplicate subscriptions.
Common mistakes
- Mutating the
Mapin state and callingsetStats(stats). BecauseObject.is(prev, next)istruewhen both variables point to the sameMapinstance, React bails out of re-rendering and the table appears frozen. - Reading and clearing
pending.currentinside thesetStats(prev => ...)callback. React may run updater callbacks asynchronously during the next render—and calls them twice in Strict Mode—so an updater that mutates a ref can read an already-emptied buffer and silently drop events. - Comparing ISO-8601 strings lexicographically or letting
NaNenter state."+01:00"offsets and variable-precision fractional seconds (".5Z"vs"Z") sort out of chronological order as text, andNaN > anythingis alwaysfalse. - Allowing arbitrary finite numbers like
1e20intonew Date(ms).toISOString(). Numbers beyond±8.64e15ms are finite floats, yettoISOString()throws aRangeErrorduring render and unmounts the entire component tree. - Overwriting
lastMswith the latest arrival's timestamp unconditionally. A delayed retry from five minutes ago would overwrite a fresher timestamp and makelast updatejump backward in time. - Calling
setStateper event on a high-throughput stream. Triggering hundreds of React renders per second starves user interactions and animations on the main thread. - Forgetting
useEffectcleanup or passing an inline arrow forsubscribe. Missing cleanup leaks sockets/timers and double-counts under Strict Mode; an unstable inlinesubscribeprop restarts the effect on every parent render. - Using array indices (
key={index}) on sorted rows. When categories swap ranks, React pairs DOM rows by position rather than byrow.category.
Follow-up questions
- How would you design automated unit and component tests for this streaming aggregator? Start with fast unit tests on the pure helpers in
logStats.js: verifytoEpochMsacrossZstrings,±HH:MMoffsets, valid numbers,1e20, and garbage strings, and verifyapplyEventsfor new categories, out-of-order timestamps that must not movelastMsbackward, unparseable timestamps that still incrementcount, missing categories mapped to"(unknown)", and immutability of the inputMap. Next, write a React Testing Library integration test using fake timers (vi.useFakeTimers()orjest.useFakeTimers()) and a controllablesubscribestub: assert"No events yet."initially, emit the 5-event sequence (billing,ingest,indexer), advance timers by250 ms, assert the sorted table rows, and unmount inside<StrictMode>to verify the unsubscribe callback ran cleanly. - How would you adapt the state structure to report rolling 5-minute event counts instead of all-time totals? Instead of a single integer per category, store a fixed-size circular array (ring buffer) of
300one-second buckets{ second, count }per category, indexing each event atepochSecond = Math.floor(eventMs / 1000)into slotepochSecond % 300(resetting the slot whenever its storedseconddiffers fromepochSecond). For 50 categories,50 × 300 = 15,000tiny buckets take minimal memory and sum in microseconds on each250 mstick. Note that sliding-window counts must also decrease as old events age out even when the stream goes quiet, so the250 mstimer should recompute window totals whenever wall-clock seconds advance, not only when new events arrive. - What architectural changes are needed if the feed grows to 10,000 distinct categories or 50,000 events per second? Rendering 10,000
<tr>elements slows browser layout, so add list virtualization (rendering only the ~25 rows currently visible in the scroll viewport via a library like TanStack Virtual) or display the top-N categories with a filter input. At 50,000 events/second, JSON parsing andapplyEventson the browser's main thread will compete with 60 fps rendering, so move the WebSocket connection andMapaggregation into a background Web Worker that posts pre-aggregated snapshots every250 ms—or better yet, aggregate per-second deltas on the backend before streaming to browsers.
Follow-up questions
- How would you design automated unit and component tests for this streaming aggregator?
- How would you adapt the state structure to report rolling 5-minute event counts instead of all-time totals?
- What architectural changes are needed if the feed grows to 10,000 distinct categories or 50,000 events per second?
Similar questions
- Audit and Implement Nested Array Flatten
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One