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-category statistics in memory using a JavaScript Map (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 valid timestamp recorded 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 Map state 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

  1. 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 a Map<string, { count: number, lastMs: number | null }>. Here count is the total number of events seen for that category, and lastMs is the latest valid event time in epoch milliseconds (the number of milliseconds since January 1, 1970 at 00:00:00 UTC), or null if 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, count still increments by 1, while lastMs advances only via max(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 count and leave lastMs unchanged (rendering "—" if lastMs is still null). An event with a missing or blank category falls 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
                                    }
    
  2. 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 to true alphabetically (. has a smaller character code than Z) even though .5Z is half a second later.
    • Date.parse resolves time-zone offsets: Date.parse converts ISO strings with Z or ±HH:MM offsets 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 include Z or an explicit offset.)
    • Return null for bad input, never NaN: In JavaScript, both NaN > x and NaN < x evaluate to false. Letting a single NaN slip into lastMs would break future comparisons.
    • Guard JavaScript's Date range (±8.64e15 ms): Number.isFinite(1e20) is true, yet new Date(1e20).toISOString() throws a RangeError because a JavaScript Date spans at most ±8.64e15 milliseconds (±100,000,000 days 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), and toEpochMs(1e20) -> null (If a backend ever sends numeric strings like "1776522010000", check /^-?\d+$/.test(timestamp) and convert via Number(timestamp) first, since Date.parse returns NaN for bare millisecond strings in V8.)

  3. Store per-category stats in an immutable Map

    Why Map beats 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 from Object.prototype. With {} in JavaScript, stats["constructor"] is already truthy before any log arrives! A Map keeps user keys completely isolated from object methods. - Built for dynamic keys: Map gives O(1) average-time .get() and .set(), tracks .size directly, and iterates keys in first-seen insertion order.

    Why create a new Map on 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 call stats.set(category, ...) on the existing Map and pass that same Map to setStats(stats), React sees an identical object reference and skips rendering completely! Copying new Map(stats) (O(k) for k categories) 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 count is a sum and lastMs is a maximum, applyEvents is order-independent and batch-invariant: applying 100 events one by one produces the exact same Map as applying all 100 in a single batch.

  4. Subscribe to the stream and batch renders with a ref

    Accepting a subscribe(onEvent) function that returns an unsubscribe() callback cleanly decouples our UI from the transport—whether events come from a WebSocket, Server-Sent Events (EventSource), or a setInterval mock.

    Why buffer events instead of calling setStats on every event? At 5 events/second, per-event state updates are fine. At 1,000 WebSocket messages/second, calling setStats per event triggers up to 1,000 Map copies and 1,000 React renders per second—even though a 60 Hz monitor only draws one frame every 16.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 every 250 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.current outside setStats: 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 mutates pending.current inside setStats would either see an already-cleared array on the second call or drop events. Capturing const batch = pending.current first 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; forgetting unsubscribe() would leave two active listeners and double every count. 3. Keep subscribe referentially stable: Define subscribe at module scope or wrap it in useCallback in the parent so parent re-renders do not tear down and recreate the subscription.

  5. 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 by category lets 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-live on the whole <table>: Marking a table that updates 4 times per second as an ARIA live region floods screen readers with constant chatter.
  6. 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 ms flush (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 count descending and then category ascending 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 }> uses O(k) memory for k distinct 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.parse and accept finite numbers only within ±8.64e15 ms (the maximum span of a JavaScript Date), turning invalid values into null rather than NaN. Format to local strings only during rendering.
  • Prefer Map over plain objects {} for dynamic log keys: Map avoids prototype collisions (where untrusted category names like "constructor" or "__proto__" collide with built-in properties on Object.prototype), supports O(1) average lookups, and exposes .size directly.
  • Immutable updates inside a pure function: Keep applyEvents(stats, events) as a pure function (output depends solely on inputs, with zero in-place mutation), cloning new 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 a 250 ms interval (<= 4 renders/second), draining the ref before calling setStats((prev) => applyEvents(prev, batch)).
  • Clean subscription lifecycle: Subscribe inside useEffect and 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 Map in state and calling setStats(stats). Because Object.is(prev, next) is true when both variables point to the same Map instance, React bails out of re-rendering and the table appears frozen.
  • Reading and clearing pending.current inside the setStats(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 NaN enter state. "+01:00" offsets and variable-precision fractional seconds (".5Z" vs "Z") sort out of chronological order as text, and NaN > anything is always false.
  • Allowing arbitrary finite numbers like 1e20 into new Date(ms).toISOString(). Numbers beyond ±8.64e15 ms are finite floats, yet toISOString() throws a RangeError during render and unmounts the entire component tree.
  • Overwriting lastMs with the latest arrival's timestamp unconditionally. A delayed retry from five minutes ago would overwrite a fresher timestamp and make last update jump backward in time.
  • Calling setState per event on a high-throughput stream. Triggering hundreds of React renders per second starves user interactions and animations on the main thread.
  • Forgetting useEffect cleanup or passing an inline arrow for subscribe. Missing cleanup leaks sockets/timers and double-counts under Strict Mode; an unstable inline subscribe prop 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 by row.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: verify toEpochMs across Z strings, ±HH:MM offsets, valid numbers, 1e20, and garbage strings, and verify applyEvents for new categories, out-of-order timestamps that must not move lastMs backward, unparseable timestamps that still increment count, missing categories mapped to "(unknown)", and immutability of the input Map. Next, write a React Testing Library integration test using fake timers (vi.useFakeTimers() or jest.useFakeTimers()) and a controllable subscribe stub: assert "No events yet." initially, emit the 5-event sequence (billing, ingest, indexer), advance timers by 250 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 300 one-second buckets { second, count } per category, indexing each event at epochSecond = Math.floor(eventMs / 1000) into slot epochSecond % 300 (resetting the slot whenever its stored second differs from epochSecond). For 50 categories, 50 × 300 = 15,000 tiny buckets take minimal memory and sum in microseconds on each 250 ms tick. Note that sliding-window counts must also decrease as old events age out even when the stream goes quiet, so the 250 ms timer 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 and applyEvents on the browser's main thread will compete with 60 fps rendering, so move the WebSocket connection and Map aggregation into a background Web Worker that posts pre-aggregated snapshots every 250 ms—or better yet, aggregate per-second deltas on the backend before streaming to browsers.

Follow-up questions

Similar questions

More Elastic interview questions

All 2 Elastic questions →