Thread-Safe Tumbling-Window Log Batcher

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Many application threads emit structured log records concurrently while a downstream sink callback ships grouped records over the network or to disk. Implement a thread-safe tumbling-window collector WindowBatcher that groups incoming records into contiguous five-second intervals of processing time and delivers completed batches to sink in strict chronological order without blocking producer threads on slow I/O.

Use the following data carrier and class interface:

@dataclass
class Batch:
    index: int          # zero-based window index k >= 0 counted from origin
    start: int          # inclusive start timestamp: origin + index * window
    end: int            # exclusive end timestamp: start + window
    records: List[Any]  # records admitted during [start, end), in admission order

class WindowBatcher:
    def __init__(
        self,
        sink: Callable[[Batch], None],
        window: int = 5_000_000_000,
        clock: Callable[[], int] = time.monotonic_ns,
    ) -> None: ...
    def log(self, record: Any) -> None: ...
    def poll(self) -> int: ...
    def close(self) -> int: ...
    def pending(self) -> int: ...

Behavioral Rules

  1. Clock origin and half-open windows:
    • Capture origin = clock() during __init__. Raise ValueError if window <= 0.
    • Window k (k >= 0) covers the half-open interval [origin + k * window, origin + (k + 1) * window). A timestamp equal to origin + window starts window 1, not window 0.
  2. Thread-safe non-blocking admission (log):
    • Read clock() inside the batcher's internal lock so concurrent thread admission order and assigned window indices never invert.
    • Place record into window k = (now - origin) // window, sealing the previously open window into the outgoing queue whenever k advances past it.
    • Never invoke sink inside log().
    • Raise RuntimeError if log() is called after close().
  3. Silent intervals omitted:
    • Windows during which zero records were admitted must never produce a Batch. Consequently, delivered Batch.index values may skip numbers across idle stretches.
  4. Ordered, retry-safe flushing (poll and pending):
    • poll() checks clock() under the lock; if the active window's end has been reached ((now - origin) // window > current_index), it seals that window (if non-empty).
    • poll() then delivers every queued Batch to sink, oldest window first, while ensuring at most one thread calls sink at a time and without holding the fast admission lock during sink(batch).
    • Return the count of batches successfully accepted by sink during this call.
    • If sink(batch) raises an exception, leave batch at the front of the pending queue so the next poll() or close() retries it before any newer batch, and allow the exception to propagate.
    • pending() returns the count of sealed, non-empty batches currently awaiting delivery.
  5. Graceful shutdown (close):
    • Reject all subsequent log() calls with RuntimeError, immediately seal the currently open partial window (if non-empty) even when clock() has not yet reached its end, and flush all queued batches using the same ordered retry semantics as poll(). Return the number of batches delivered.

Examples

Example 1

Instantiate WindowBatcher(sink, window=5000, clock=clock) with initial clock origin = 100:

  1. t = 1200: log("req-1") -> admitted to window 0 ([100, 5100)).
  2. t = 5099: log("req-2") -> admitted to window 0; calling poll() at t = 5099 returns 0 because 5099 < 5100.
  3. t = 5100: log("req-3") -> exact boundary (5100 - 100) // 5000 == 1; window 0 is sealed into the pending queue (pending() == 1, sink not yet called) and "req-3" opens window 1 ([5100, 10100)).
  4. t = 16500: log("req-4") -> (16500 - 100) // 5000 == 3; window 1 is sealed (pending() == 2), silent window 2 ([10100, 15100)) is skipped, and "req-4" opens window 3 ([15100, 20100)).
  5. t = 20100: poll() seals window 3, delivers 3 batches in order, and returns 3:
    • Batch(index=0, start=100, end=5100, records=["req-1", "req-2"])
    • Batch(index=1, start=5100, end=10100, records=["req-3"])
    • Batch(index=3, start=15100, end=20100, records=["req-4"])

Example 2

Instantiate WindowBatcher(flaky_sink, window=5000, clock=clock) at origin = 0, where flaky_sink raises IOError on its first call and succeeds thereafter:

  1. t = 800: log("evt-alpha") -> window 0 ([0, 5000)).
  2. t = 6400: log("evt-beta") -> seals window 0, opens window 1 ([5000, 10000)).
  3. t = 11200: poll() seals window 1 and calls flaky_sink(Batch 0), which raises IOError. Neither Batch 0 nor Batch 1 is lost (pending() == 2).
  4. t = 11500: log("evt-gamma") -> window 2 ([10000, 15000)).
  5. t = 12000: close() seals partial window 2 early, retries Batch 0 first, then delivers Batch 1 and Batch 2 (returns 3). Calling log("late") afterward raises RuntimeError.

Constraints

  • clock() returns non-decreasing integers (default time.monotonic_ns); window is a positive integer in the same unit (<= 0 raises ValueError).
  • log(record) must run in O(1) in-memory time under lock contention and must never block on sink.
  • Concurrent calls to log(), poll(), close(), and pending() must be free of data races, deadlocks, lost batches, and out-of-order deliveries.

Step-by-step walkthrough

  1. Clarify the windowing and delivery rules

    Many producer threads call log(record) concurrently, and our batcher must group those records into five-second windows and deliver non-empty batches in order to a sink function that may be slow or temporarily fail. Before writing a line of code, let's pin down the exact contract:

    • Processing time on admission. A record belongs to the window containing the moment it enters log() under the batcher's lock—we do not trust client-supplied timestamps.
    • Integer monotonic clock. time.monotonic_ns() never jumps backward if an administrator or NTP adjusts the system wall clock, and integer nanoseconds avoid floating-point rounding bugs at boundaries.
    • Half-open windows [origin + 5k, origin + 5(k + 1)). Window 0 covers [origin, origin + w). A record arriving at exact timestamp origin + w starts window 1.
    • Skip empty windows. Quiet periods emit zero batches, so emitted Batch.index values may jump (for example 0, then 3).
    • Non-blocking producers, ordered at-least-once delivery. log() never calls sink. poll() and close() deliver sealed batches oldest-first, removing a batch from the queue only after sink(batch) succeeds.
    • Clean shutdown. close() rejects any future log() calls with RuntimeError, seals the current partial window (if non-empty), and flushes all pending batches.
    from typing import Any, Callable
    import time
    
    class WindowBatcher:
        def __init__(self, sink, window: int = 5_000_000_000, clock: Callable[[], int] = time.monotonic_ns) -> None: ...
        def log(self, record: Any) -> None: ...
        def poll(self) -> int: ...
        def close(self) -> int: ...
        def pending(self) -> int: ...
    
  2. Why naive timer loops and naive lock-free flushes fail

    Two tempting designs break under real concurrency:

    1. Sleeping 5 seconds in a loop (while True: sleep(5); swap_and_flush()). Every iteration takes 5 s + flush_time, so window boundaries steadily drift away from [0, 5), [5, 10), [10, 15). Worse, if the OS scheduler wakes the timer 2 seconds late at t = 7.0 s, records logged between 5.0 s and 7.0 s get swept into window 0 instead of window 1.
    2. Flushing inside log() when a thread notices a new window.
      • If log() calls sink(batch) while holding the lock, every producer thread stalls whenever the network sink takes 500 ms—and if sink itself logs a debug line to the same logger, the thread deadlocks on its own non-reentrant lock.
      • If log() grabs the finished batch, releases the lock, and then calls sink(batch), thread scheduling can deliver batches out of order:
    Thread A (under lock): seals Window 3 -> batch_3, releases lock, OS pauses Thread A
    Thread B (under lock): seals Window 4 -> batch_4, releases lock
    Thread B:              calls sink(batch_4)   <-- Window 4 delivered first!
    Thread A (resumes):    calls sink(batch_3)   <-- Window 3 arrives out of order!
    

    To avoid both traps, we decouple assigning records to windows (fast, in-memory, under a state lock) from sending sealed batches to the sink (serialized by a single emitter outside the state lock).

  3. Compute exact window numbers from an integer clock

    Given origin (the clock value when WindowBatcher was constructed) and window (default 5_000_000_000 ns), any timestamp now >= origin maps to window index k with one integer floor division:

    k = (now - origin) // window
    
    origin=100, window=5000:
      now =  100  ->    0 // 5000 = 0 -+
      now = 5099  -> 4999 // 5000 = 0 -+--> Window 0: [100, 5100)
      now = 5100  -> 5000 // 5000 = 1 ----> Window 1: [5100, 10100)
    

    Two details here prevent subtle bugs:

    • Use integers, not floats. In IEEE 754 floating-point arithmetic, 8.2 - 3.2 evaluates to 4.999999999999999, so (8.2 - 3.2) // 5.0 gives 0.0 instead of 1.0, dropping an exact-boundary log into the wrong window! Integer nanoseconds are exact.
    • Read self._clock() inside self._lock. If Thread A read 5099 before acquiring _lock, lost the lock race to Thread B (which read 5100 and rotated the batcher to window 1), and then entered _lock, Thread A would append a 5099 record after window 0 was already sealed.
  4. Track open and closed windows under the state lock

    Inside WindowBatcher, _lock protects four small pieces of state:

    • _index: integer window number k of the currently open window.
    • _current: Python list collecting records admitted into window _index.
    • _ready: a collections.deque holding sealed, non-empty Batch objects in strict oldest-first order.
    • _closed: boolean set by close() so late log() calls raise RuntimeError.

    Whenever log() or poll() sees target_index > self._index, _rotate_to seals _current into _ready (only if _current is non-empty!) and jumps self._index = target_index. Notice what happens if traffic is idle during windows 1 and 2 and the next log arrives in window 3: _current from window 0 is sealed as Batch(index=0, ...), _index jumps straight to 3, and windows 1 and 2 naturally produce zero batches.

    from typing import Any, Callable, Deque, List
    from collections import deque
    from dataclasses import dataclass
    import threading
    import time
    
    
    @dataclass
    class Batch:
        """All records admitted during one half-open window [start, end) of the logger's clock."""
    
        index: int  # window number k >= 0 counted from the logger's origin; unique per logger
        start: int  # window start timestamp: origin + index * window
        end: int  # window end timestamp (exclusive): start + window
        records: List[Any]  # records in exact admission order
    
    
    class WindowBatcher:
        def __init__(
            self,
            sink: Callable[[Batch], None],
            window: int = 5_000_000_000,
            clock: Callable[[], int] = time.monotonic_ns,
        ) -> None:
            if window <= 0:
                raise ValueError("window must be positive")
            self._sink = sink
            self._window = window
            self._clock = clock
            self._lock = threading.Lock()
            self._emit_lock = threading.Lock()
            self._origin = clock()
            self._index = 0
            self._current: List[Any] = []
            self._ready: Deque[Batch] = deque()
            self._closed = False
    
        def log(self, record: Any) -> None:
            with self._lock:
                if self._closed:
                    raise RuntimeError("logger is closed")
                now = self._clock()
                target_index = self._window_of(now)
                self._rotate_to(target_index)
                self._current.append(record)
    
        def _window_of(self, now: int) -> int:
            return (now - self._origin) // self._window
    
        def _rotate_to(self, target_index: int) -> None:
            if target_index > self._index:
                self._close_current()
                self._index = target_index
    
        def _close_current(self) -> None:
            if self._current:
                start = self._origin + self._index * self._window
                end = start + self._window
                sealed_batch = Batch(self._index, start, end, self._current)
                self._ready.append(sealed_batch)
                self._current = []
    
  5. Deliver batches in strict order without blocking producers

    Now look at how _deliver_ready() drains self._ready safely using a second lock, self._emit_lock:

    Producers calling log()                     Emitter in _deliver_ready()
    -----------------------                     ---------------------------
    acquire _lock (nanoseconds)                 acquire _emit_lock (1 emitter at a time)
      append to _current / right of _ready        acquire _lock -> peek oldest = _ready[0]
    release _lock                                 release _lock
                                                  call _sink(oldest)  <-- _lock is FREE here!
                                                  acquire _lock -> _ready.popleft()
                                                  release _lock
    

    Why this two-lock peek-deliver-pop loop works:

    1. _emit_lock prevents reordering. Even if a background timer calling poll() races with close(), only one thread can enter the while True: delivery loop at a time.
    2. Peeking before calling _sink prevents silent data loss. If self._sink(oldest_batch) raises IOError, popleft() never runs—oldest_batch stays at _ready[0] so the next poll() retries it before any newer batch.
    3. popleft() is guaranteed to remove oldest_batch. While _lock was released during _sink(oldest_batch), producers could only .append() new batches to the right end of _ready, and _emit_lock kept any other thread from popping the left end.
    class WindowBatcher:
        def _deliver_ready(self) -> int:
            delivered = 0
            with self._emit_lock:
                while True:
                    # Peek at the oldest batch without popping so a failed sink call never loses it.
                    with self._lock:
                        if not self._ready:
                            return delivered
                        oldest_batch = self._ready[0]
    
                    # Call the sink outside _lock so slow I/O never blocks log() calls.
                    self._sink(oldest_batch)
    
                    # Safe to popleft(): _close_current only appends on the right, and _emit_lock
                    # prevents any other thread from popping on the left.
                    with self._lock:
                        self._ready.popleft()
                    delivered += 1
    
  6. Wire up poll(), close(), and the background timer

    What if a burst of logs arrives at t = 1.0 s, and then no thread logs anything for the next minute? Because log() never runs again, log() alone would leave window 0 sitting in _current forever. poll() solves that: it acquires _lock, checks the current clock, rotates _current into _ready if the window has ended, and calls _deliver_ready().

    At shutdown, close() sets self._closed = True, calls self._close_current() unconditionally to seal whatever partial window is still open, and calls self._deliver_ready(). In production, a single background thread runs run_timer, polling every ~250 ms until a stop event signals shutdown.

    import sys
    import threading
    
    
    class WindowBatcher:
        def poll(self) -> int:
            with self._lock:
                now = self._clock()
                target_index = self._window_of(now)
                self._rotate_to(target_index)
            return self._deliver_ready()
    
        def close(self) -> int:
            with self._lock:
                self._closed = True
                self._close_current()
            return self._deliver_ready()
    
        def pending(self) -> int:
            with self._lock:
                return len(self._ready)
    
    
    def run_timer(batcher: WindowBatcher, stop: threading.Event, interval_seconds: float = 0.25) -> None:
        """Background emitter loop: poll periodically until `stop` is set."""
        while not stop.wait(interval_seconds):
            try:
                batcher.poll()
            except Exception as exc:
                print(f"log sink failed, will retry: {exc!r}", file=sys.stderr)
    
  7. Trace Example 2: flaky sink retry and shutdown flush

    Suppose origin = 0, window = 5000 ms, and flaky_sink raises IOError on its first call before recovering:

    Time     Call              k   _current        _ready                               Sink outcome
    -------  ----------------  --  --------------  -----------------------------------  ----------------------------
    t=800    log("evt-alpha")  0   ["evt-alpha"]   []                                   (log never calls sink)
    t=6400   log("evt-beta")   1   ["evt-beta"]    [B0(0..5000, ["evt-alpha"])]         window 0 rotated to _ready
    t=11200  poll()            2   []              [B0, B1(5000..10000, ["evt-beta"])]  sink(B0) RAISES IOError!
                                                   (B0 stays at head of _ready!)
    t=11500  log("evt-gamma")  2   ["evt-gamma"]   [B0, B1]                             appended to open window 2
    t=12000  close()           2   []              []                                   seals B2, sends B0, B1, B2 -> 3
    

    Notice what happens across the failure and shutdown: - Every record stayed in the exact 5-second window of its admission time. - When sink(B0) failed at t = 11200, neither B0 nor B1 was popped from _ready. - Calling close() at t = 12000 sealed partial window 2 early and delivered B0, B1, and B2 in strict window order without losing B0.

  8. Complete solution

    from typing import Any, Callable, Deque, List
    from collections import deque
    from dataclasses import dataclass
    import sys
    import threading
    import time
    
    
    @dataclass
    class Batch:
        """All records admitted during one half-open window [start, end) of the logger's clock."""
    
        index: int  # window number k >= 0 counted from the logger's origin; unique per logger
        start: int  # window start timestamp: origin + index * window
        end: int  # window end timestamp (exclusive): start + window
        records: List[Any]  # records in exact admission order
    
    
    class WindowBatcher:
        """Collect records from concurrent threads into windows [origin + k*w, origin + (k+1)*w)."""
    
        def __init__(
            self,
            sink: Callable[[Batch], None],
            window: int = 5_000_000_000,
            clock: Callable[[], int] = time.monotonic_ns,
        ) -> None:
            if window <= 0:
                raise ValueError("window must be positive")
            self._sink = sink
            self._window = window
            self._clock = clock
    
            # _lock: fast state mutex guarding _index, _current, _ready, and _closed.
            self._lock = threading.Lock()
            # _emit_lock: serializes sink calls so at most one thread delivers batches at a time.
            self._emit_lock = threading.Lock()
    
            self._origin = clock()
            # _index: window number k of the currently open buffer _current.
            self._index = 0
            # _current: records admitted into window _index so far, e.g. ["msg1", "msg2"].
            self._current: List[Any] = []
            # _ready: FIFO deque of sealed non-empty Batch objects, oldest window first.
            self._ready: Deque[Batch] = deque()
            self._closed = False
    
        def log(self, record: Any) -> None:
            with self._lock:
                if self._closed:
                    raise RuntimeError("logger is closed")
                # Read the clock inside _lock so thread admission order and window order never disagree.
                now = self._clock()
                target_index = self._window_of(now)
                self._rotate_to(target_index)
                self._current.append(record)
    
        def poll(self) -> int:
            with self._lock:
                now = self._clock()
                target_index = self._window_of(now)
                self._rotate_to(target_index)
            return self._deliver_ready()
    
        def close(self) -> int:
            with self._lock:
                self._closed = True
                self._close_current()
            return self._deliver_ready()
    
        def pending(self) -> int:
            with self._lock:
                return len(self._ready)
    
        # --- Internal helpers below require self._lock to be held by the caller. ---
    
        def _window_of(self, now: int) -> int:
            # Half-open division: now == origin + window lands in window 1, not window 0.
            return (now - self._origin) // self._window
    
        def _rotate_to(self, target_index: int) -> None:
            # Advance only forward; jumping e.g. from window 0 to 3 skips empty windows 1 and 2.
            if target_index > self._index:
                self._close_current()
                self._index = target_index
    
        def _close_current(self) -> None:
            # Omit empty windows by creating a Batch only when _current has at least one record.
            if self._current:
                start = self._origin + self._index * self._window
                end = start + self._window
                sealed_batch = Batch(self._index, start, end, self._current)
                self._ready.append(sealed_batch)
                self._current = []
    
        def _deliver_ready(self) -> int:
            delivered = 0
            with self._emit_lock:
                while True:
                    # Peek at the oldest batch without popping so a failed sink call never loses it.
                    with self._lock:
                        if not self._ready:
                            return delivered
                        oldest_batch = self._ready[0]
    
                    # Call the sink outside _lock so slow I/O never blocks log() calls.
                    self._sink(oldest_batch)
    
                    # Safe to popleft(): _close_current only appends on the right, and _emit_lock
                    # prevents any other thread from popping on the left.
                    with self._lock:
                        self._ready.popleft()
                    delivered += 1
    
    
    def run_timer(batcher: WindowBatcher, stop: threading.Event, interval_seconds: float = 0.25) -> None:
        """Background emitter loop: poll periodically until `stop` is set.
    
        Clean shutdown sequence: stop.set(), join this thread, then call batcher.close() once.
        """
        while not stop.wait(interval_seconds):
            try:
                batcher.poll()
            except Exception as exc:
                # Failed batches stay at the head of _ready and will be retried on the next tick.
                print(f"log sink failed, will retry: {exc!r}", file=sys.stderr)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a busy company mailroom where dozens of clerks drop letters into an open bin labeled with the current 5-second slot (such as 00:00–00:05), while a single delivery driver loads sealed bins off a conveyor belt onto a truck in strict chronological order. Clerks never drive the truck themselves: if a clerk walks up at 00:06, they simply push the 00:00–00:05 bin onto the outgoing belt, open a fresh 00:05–00:10 bin, drop their letter inside, and walk right back to their desk. Meanwhile, a wall timer periodically checks the desk so a finished bin still gets pushed onto the belt even when no new clerks walk up.

Naive designs fail here for subtle concurrency and timing reasons. Running while True: sleep(5); flush() drifts forward by the duration of every slow network call, and if the timer wakes up late at 5.8 s, logs arriving between 5.0 s and 5.8 s get lumped into the [0, 5) batch. Worse, letting producer threads call sink(batch) while holding a mutex (a mutual-exclusion lock that lets only one thread touch shared variables at a time) stalls every application thread on network I/O, whereas releasing the lock before calling sink(batch) creates a race condition (a bug where correctness depends on unpredictable thread scheduling) that can deliver batch 4 before batch 3.

Walk through Example 1 with origin = 100 and window = 5000 ms using half-open intervals [start, end) (ranges that include start and exclude end):

  1. At t = 1200 and t = 5099, log("req-1") and log("req-2") both compute window (t - 100) // 5000 = 0, collecting ["req-1", "req-2"] inside _current.
  2. At t = 5100, log("req-3") computes (5100 - 100) // 5000 = 1 > 0, seals Batch(index=0, start=100, end=5100, records=["req-1", "req-2"]) onto _ready, advances _index = 1, and sets _current = ["req-3"].
  3. At t = 16500, log("req-4") jumps to window (16500 - 100) // 5000 = 3, sealing Batch 1, skipping empty window 2, and opening window 3; then poll() at t = 20100 seals Batch 3 and delivers Batch 0, Batch 1, and Batch 3 to sink outside the state lock.

Complexity

  • log(record): O(1) time. Under self._lock, log reads the integer clock once, computes one floor division, optionally wraps self._current into a Batch reference in O(1) time without copying its elements, and appends record to a Python list.
  • poll() and close(): O(b) bookkeeping time for b ready batches, plus sink I/O time. Each ready batch acquires and releases self._lock twice—once to peek self._ready[0] in O(1) time and once to popleft() in O(1) time—while self._sink(batch) runs outside self._lock.
  • Space: O(R), where R is the number of undelivered records currently in memory. Every record sits once in either self._current or a queued Batch inside self._ready until the sink accepts it; if the sink stays down indefinitely without a cap, R grows with incoming traffic.

Edge cases

  • Exact boundary timestamps (origin + 5000): Because (5000 - 0) // 5000 == 1, a record admitted at origin + w cleanly starts window 1 rather than leaking into [origin, origin + w).
  • No logs arrive after a window ends: log() never runs during quiet periods, so poll() independently reads the clock and rotates the finished window onto _ready.
  • Long idle gaps across multiple windows: Jumping from window 0 to window 3 advances _index from 0 to 3 without pushing empty batches for windows 1 and 2, while Batch.index (0, then 3) still lets downstream consumers distinguish quiet windows from dropped batches.
  • Floating-point clock precision: In IEEE 754 floats, (8.2 - 3.2) // 5.0 evaluates to 0.0 instead of 1.0; using integer nanoseconds from time.monotonic_ns() (a monotonic clock, meaning a timer guaranteed to move only forward at a steady rate regardless of wall-clock adjustments) eliminates boundary rounding bugs.
  • Sink failure during poll() or close(): Because _deliver_ready peeks _ready[0] and only pops after _sink returns, an exception leaves the failed batch at the front of _ready so the next poll() or close() retries it first.
  • Calling close() multiple times: Setting _closed = True and clearing _current makes repeated close() calls safe and idempotent once all batches are flushed.

Common mistakes

  • Reading clock() before acquiring self._lock: Thread A can read t = 4999, get paused by the OS while Thread B reads t = 5000 and seals window 0, and then resume to append its 4999 record into window 1 (or mutate an already-sealed list).
  • Holding self._lock across self._sink(batch): Slow HTTP/disk sinks freeze every producer thread calling log(), and if sink itself calls log() on the same batcher, the thread hits a deadlock (freezing forever waiting for a non-reentrant lock it already holds).
  • Popping a batch into a local variable before acquiring _emit_lock: Even with _emit_lock, if Thread A pops Batch 3 and Thread B pops Batch 4 before racing for _emit_lock, Thread B can win _emit_lock and deliver Batch 4 before Batch 3. Always leave batches in _ready and let the holder of _emit_lock peek _ready[0].
  • Popping from _ready before self._sink(batch) succeeds: Any network timeout or exception permanently discards that 5-second batch of logs.
  • Using time.time() instead of time.monotonic_ns(): System clock jumps from NTP syncs or daylight-saving misconfigurations can jump backward (merging distinct windows) or forward (prematurely closing windows).

Alternative approaches

  • Single-consumer queue.Queue pipeline: Producers push (clock(), record) tuples onto a bounded queue.Queue, and one dedicated worker thread owns all window state and sink calls without needing two locks. A bounded queue provides automatic backpressure, though every record incurs per-item queue locking and tuple allocation.
  • Sleeping until the exact next boundary: Instead of polling every 250 ms, the timer thread can compute the remaining nanoseconds until (index + 1) * window and stop.wait(remaining_seconds), waking up right at window end with fewer idle wakeups.

Follow-up questions

  • How does your design stay accurate when the periodic poller runs late or when traffic goes completely silent after a window ends? Because every record's window index k = (now - origin) // window is computed from the clock at admission time inside log(), a late poller never puts records into the wrong window—it only delays when already-sealed batches reach the sink. Conversely, when traffic goes completely silent after a window ends, log() does not run, which is why poll() also computes _window_of(self._clock()) and calls _rotate_to to seal the finished window on the next timer tick.
  • Why can sealing under a lock and calling the sink concurrently outside that lock deliver batches out of sequence? Sealing a batch under _lock and sending it over the network outside _lock are two separate steps, and the OS scheduler can pause a thread right between them. If Thread A seals Batch 3 and pauses right after releasing _lock, Thread B can seal Batch 4, release _lock, and finish sink(Batch 4) before Thread A wakes up to call sink(Batch 3). Pushing sealed batches onto _ready under _lock fixes the order permanently, and _emit_lock ensures a single thread drains _ready[0] one by one.
  • How do you retry transient sink errors without dropping batches or causing duplicate side effects downstream? Keeping a batch at _ready[0] until self._sink(batch) returns gives at-least-once delivery (every batch is guaranteed to be delivered one or more times as long as the process stays alive, rather than silently dropped on error). Because a network timeout after the server saved the batch causes the next poll() to resend the same batch, each Batch includes an idempotency key (a unique identifier such as (logger_instance_id, batch.index) that lets the receiver recognize and ignore duplicate deliveries) so downstream storage achieves effectively-once results; to survive process crashes as well, producers must append records to a local write-ahead log (WAL) (an append-only disk file written before acknowledging admission in memory).
  • How would you bound memory growth and apply backpressure during an extended sink outage? An unbounded _ready deque will eventually exhaust RAM during a long outage, so production loggers add backpressure (a mechanism that slows down or sheds incoming load when downstream capacity cannot keep up) by capping buffered records or bytes. For ordinary debug/application logs, dropping newest records once pending exceeds a budget while incrementing a dropped_count metric keeps user requests fast; for audit or billing logs where data loss is unacceptable, block log() on a threading.Condition or spill sealed batches to local disk, and move any poison batch (a malformed batch that triggers permanent 4xx rejection from the sink) aside after N retries so it does not block newer batches forever.

Follow-up questions

Similar questions

More Other interview questions

All 51 Other questions →