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
- Clock origin and half-open windows:
- Capture
origin = clock()during__init__. RaiseValueErrorifwindow <= 0. - Window
k(k >= 0) covers the half-open interval[origin + k * window, origin + (k + 1) * window). A timestamp equal toorigin + windowstarts window1, not window0.
- Capture
- 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
recordinto windowk = (now - origin) // window, sealing the previously open window into the outgoing queue wheneverkadvances past it. - Never invoke
sinkinsidelog(). - Raise
RuntimeErroriflog()is called afterclose().
- Read
- Silent intervals omitted:
- Windows during which zero records were admitted must never produce a
Batch. Consequently, deliveredBatch.indexvalues may skip numbers across idle stretches.
- Windows during which zero records were admitted must never produce a
- Ordered, retry-safe flushing (
pollandpending):poll()checksclock()under the lock; if the active window'sendhas been reached ((now - origin) // window > current_index), it seals that window (if non-empty).poll()then delivers every queuedBatchtosink, oldest window first, while ensuring at most one thread callssinkat a time and without holding the fast admission lock duringsink(batch).- Return the count of batches successfully accepted by
sinkduring this call. - If
sink(batch)raises an exception, leavebatchat the front of the pending queue so the nextpoll()orclose()retries it before any newer batch, and allow the exception to propagate. pending()returns the count of sealed, non-empty batches currently awaiting delivery.
- Graceful shutdown (
close):- Reject all subsequent
log()calls withRuntimeError, immediately seal the currently open partial window (if non-empty) even whenclock()has not yet reached itsend, and flush all queued batches using the same ordered retry semantics aspoll(). Return the number of batches delivered.
- Reject all subsequent
Examples
Example 1
Instantiate WindowBatcher(sink, window=5000, clock=clock) with initial clock origin = 100:
t = 1200:log("req-1")-> admitted to window0([100, 5100)).t = 5099:log("req-2")-> admitted to window0; callingpoll()att = 5099returns0because5099 < 5100.t = 5100:log("req-3")-> exact boundary(5100 - 100) // 5000 == 1; window0is sealed into the pending queue (pending() == 1,sinknot yet called) and"req-3"opens window1([5100, 10100)).t = 16500:log("req-4")->(16500 - 100) // 5000 == 3; window1is sealed (pending() == 2), silent window2([10100, 15100)) is skipped, and"req-4"opens window3([15100, 20100)).t = 20100:poll()seals window3, delivers3batches in order, and returns3: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:
t = 800:log("evt-alpha")-> window0([0, 5000)).t = 6400:log("evt-beta")-> seals window0, opens window1([5000, 10000)).t = 11200:poll()seals window1and callsflaky_sink(Batch 0), which raisesIOError. NeitherBatch 0norBatch 1is lost (pending() == 2).t = 11500:log("evt-gamma")-> window2([10000, 15000)).t = 12000:close()seals partial window2early, retriesBatch 0first, then deliversBatch 1andBatch 2(returns 3). Callinglog("late")afterward raisesRuntimeError.
Constraints
clock()returns non-decreasing integers (defaulttime.monotonic_ns);windowis a positive integer in the same unit (<= 0raisesValueError).log(record)must run inO(1)in-memory time under lock contention and must never block onsink.- Concurrent calls to
log(),poll(),close(), andpending()must be free of data races, deadlocks, lost batches, and out-of-order deliveries.
Step-by-step walkthrough
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 asinkfunction 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)). Window0covers[origin, origin + w). A record arriving at exact timestamporigin + wstarts window1. - Skip empty windows. Quiet periods emit zero batches, so emitted
Batch.indexvalues may jump (for example0, then3). - Non-blocking producers, ordered at-least-once delivery.
log()never callssink.poll()andclose()deliver sealed batches oldest-first, removing a batch from the queue only aftersink(batch)succeeds. - Clean shutdown.
close()rejects any futurelog()calls withRuntimeError, 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: ...- Processing time on admission. A record belongs to the window containing the moment it enters
Why naive timer loops and naive lock-free flushes fail
Two tempting designs break under real concurrency:
- Sleeping 5 seconds in a loop (
while True: sleep(5); swap_and_flush()). Every iteration takes5 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 att = 7.0 s, records logged between5.0 sand7.0 sget swept into window0instead of window1. - Flushing inside
log()when a thread notices a new window.- If
log()callssink(batch)while holding the lock, every producer thread stalls whenever the network sink takes 500 ms—and ifsinkitself 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 callssink(batch), thread scheduling can deliver batches out of order:
- If
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).
- Sleeping 5 seconds in a loop (
Compute exact window numbers from an integer clock
Given
origin(the clock value whenWindowBatcherwas constructed) andwindow(default5_000_000_000ns), any timestampnow >= originmaps to window indexkwith 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.2evaluates to4.999999999999999, so(8.2 - 3.2) // 5.0gives0.0instead of1.0, dropping an exact-boundary log into the wrong window! Integer nanoseconds are exact. - Read
self._clock()insideself._lock. If Thread A read5099before acquiring_lock, lost the lock race to Thread B (which read5100and rotated the batcher to window1), and then entered_lock, Thread A would append a5099record after window0was already sealed.
- Use integers, not floats. In IEEE 754 floating-point arithmetic,
Track open and closed windows under the state lock
Inside
WindowBatcher,_lockprotects four small pieces of state:_index: integer window numberkof the currently open window._current: Pythonlistcollecting records admitted into window_index._ready: acollections.dequeholding sealed, non-emptyBatchobjects in strict oldest-first order._closed: boolean set byclose()so latelog()calls raiseRuntimeError.
Whenever
log()orpoll()seestarget_index > self._index,_rotate_toseals_currentinto_ready(only if_currentis non-empty!) and jumpsself._index = target_index. Notice what happens if traffic is idle during windows1and2and the next log arrives in window3:_currentfrom window0is sealed asBatch(index=0, ...),_indexjumps straight to3, and windows1and2naturally 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 = []Deliver batches in strict order without blocking producers
Now look at how
_deliver_ready()drainsself._readysafely 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 _lockWhy this two-lock peek-deliver-pop loop works:
_emit_lockprevents reordering. Even if a background timer callingpoll()races withclose(), only one thread can enter thewhile True:delivery loop at a time.- Peeking before calling
_sinkprevents silent data loss. Ifself._sink(oldest_batch)raisesIOError,popleft()never runs—oldest_batchstays at_ready[0]so the nextpoll()retries it before any newer batch. popleft()is guaranteed to removeoldest_batch. While_lockwas released during_sink(oldest_batch), producers could only.append()new batches to the right end of_ready, and_emit_lockkept 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 += 1Wire 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? Becauselog()never runs again,log()alone would leave window0sitting in_currentforever.poll()solves that: it acquires_lock, checks the current clock, rotates_currentinto_readyif the window has ended, and calls_deliver_ready().At shutdown,
close()setsself._closed = True, callsself._close_current()unconditionally to seal whatever partial window is still open, and callsself._deliver_ready(). In production, a single background thread runsrun_timer, polling every ~250 ms until astopevent 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)Trace Example 2: flaky sink retry and shutdown flush
Suppose
origin = 0,window = 5000ms, andflaky_sinkraisesIOErroron 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 -> 3Notice what happens across the failure and shutdown: - Every record stayed in the exact 5-second window of its admission time. - When
sink(B0)failed att = 11200, neitherB0norB1was popped from_ready. - Callingclose()att = 12000sealed partial window2early and deliveredB0,B1, andB2in strict window order without losingB0.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):
- At
t = 1200andt = 5099,log("req-1")andlog("req-2")both compute window(t - 100) // 5000 = 0, collecting["req-1", "req-2"]inside_current. - At
t = 5100,log("req-3")computes(5100 - 100) // 5000 = 1 > 0, sealsBatch(index=0, start=100, end=5100, records=["req-1", "req-2"])onto_ready, advances_index = 1, and sets_current = ["req-3"]. - At
t = 16500,log("req-4")jumps to window(16500 - 100) // 5000 = 3, sealingBatch 1, skipping empty window2, and opening window3; thenpoll()att = 20100sealsBatch 3and deliversBatch 0,Batch 1, andBatch 3tosinkoutside the state lock.
Complexity
log(record): O(1) time. Underself._lock,logreads the integer clock once, computes one floor division, optionally wrapsself._currentinto aBatchreference inO(1)time without copying its elements, and appendsrecordto a Python list.poll()andclose(): O(b) bookkeeping time for b ready batches, plus sink I/O time. Each ready batch acquires and releasesself._locktwice—once to peekself._ready[0]inO(1)time and once topopleft()inO(1)time—whileself._sink(batch)runs outsideself._lock.- Space: O(R), where R is the number of undelivered records currently in memory. Every record sits once in either
self._currentor a queuedBatchinsideself._readyuntil the sink accepts it; if the sink stays down indefinitely without a cap,Rgrows with incoming traffic.
Edge cases
- Exact boundary timestamps (
origin + 5000): Because(5000 - 0) // 5000 == 1, a record admitted atorigin + wcleanly starts window1rather than leaking into[origin, origin + w). - No logs arrive after a window ends:
log()never runs during quiet periods, sopoll()independently reads the clock and rotates the finished window onto_ready. - Long idle gaps across multiple windows: Jumping from window
0to window3advances_indexfrom0to3without pushing empty batches for windows1and2, whileBatch.index(0, then3) still lets downstream consumers distinguish quiet windows from dropped batches. - Floating-point clock precision: In IEEE 754 floats,
(8.2 - 3.2) // 5.0evaluates to0.0instead of1.0; using integer nanoseconds fromtime.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()orclose(): Because_deliver_readypeeks_ready[0]and only pops after_sinkreturns, an exception leaves the failed batch at the front of_readyso the nextpoll()orclose()retries it first. - Calling
close()multiple times: Setting_closed = Trueand clearing_currentmakes repeatedclose()calls safe and idempotent once all batches are flushed.
Common mistakes
- Reading
clock()before acquiringself._lock: Thread A can readt = 4999, get paused by the OS while Thread B readst = 5000and seals window0, and then resume to append its4999record into window1(or mutate an already-sealed list). - Holding
self._lockacrossself._sink(batch): Slow HTTP/disk sinks freeze every producer thread callinglog(), and ifsinkitself callslog()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 popsBatch 3and Thread B popsBatch 4before racing for_emit_lock, Thread B can win_emit_lockand deliverBatch 4beforeBatch 3. Always leave batches in_readyand let the holder of_emit_lockpeek_ready[0]. - Popping from
_readybeforeself._sink(batch)succeeds: Any network timeout or exception permanently discards that 5-second batch of logs. - Using
time.time()instead oftime.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.Queuepipeline: Producers push(clock(), record)tuples onto a boundedqueue.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) * windowandstop.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) // windowis computed from the clock at admission time insidelog(), 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 whypoll()also computes_window_of(self._clock())and calls_rotate_toto 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
_lockand sending it over the network outside_lockare two separate steps, and the OS scheduler can pause a thread right between them. If Thread A sealsBatch 3and pauses right after releasing_lock, Thread B can sealBatch 4, release_lock, and finishsink(Batch 4)before Thread A wakes up to callsink(Batch 3). Pushing sealed batches onto_readyunder_lockfixes the order permanently, and_emit_lockensures 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]untilself._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 nextpoll()to resend the same batch, eachBatchincludes 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
_readydeque 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 oncependingexceeds a budget while incrementing adropped_countmetric keeps user requests fast; for audit or billing logs where data loss is unacceptable, blocklog()on athreading.Conditionor spill sealed batches to local disk, and move any poison batch (a malformed batch that triggers permanent4xxrejection from the sink) aside afterNretries so it does not block newer batches forever.
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?
- Why can sealing under a lock and calling the sink concurrently outside that lock deliver batches out of sequence?
- How do you retry transient sink errors without dropping batches or causing duplicate side effects downstream?
- How would you bound memory growth and apply backpressure during an extended sink outage?
Similar questions
- Retry-Safe Job Worker with Jittered Backoff and DLQ
- Reclaiming All Docker Host Resources Safely
- RF and Analog IC Design Fundamentals
- Severity-Based Log Filtering and Contract Verification
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
More Other interview questions
- Global Live Video Streaming Platform Medium
- Multi-User Collaborative Document Editor Medium
- Monthly Regional Revenue Pivot with Historical FX Rates Medium Pro
- Retry-Safe Job Worker with Jittered Backoff and DLQ Medium Pro
- Test Digit String Divisibility by Eight Easy Pro
- Reclaiming All Docker Host Resources Safely Easy Pro
- String Equality After Backspace Edits Medium Pro
- Markov Step Queries and Matrix Estimation Medium Pro
- Markov Chain Power and Empirical Matrix Easy Pro
- Basket Total After Single-Item Discount Medium Pro