Requirements & System Scope
Functional Scope (In-Scope)
- Record Hits:
hit()stamps the current second, read from an injectedClock, and counts one hit. - Count Recent Hits:
getHits()returns how many hits fall in the last W seconds. W is fixed at construction and the examples use 300. - Two Implementations: an exact timestamp queue and a fixed-memory ring of per-second buckets sit behind one
HitCounterinterface and are chosen by aStrategy. - Thread Safety: many threads call
hit()while others callgetHits(), and no hit is lost or counted twice. - Deterministic Tests: time enters only through the
Clock, so a test moves it by hand and gets the same answer every run.
Explicit Boundaries (Out-of-Scope)
- No Sub-Second Precision: the resolution is one second, so two hits inside the same second are indistinguishable.
- No Per-Key Counters: one counter counts one stream. Keyed counters and the eviction of idle keys are an extension.
- No Cross-Process Counting: the counter lives in one process. A fleet-wide count needs sharded counters or Redis, which the concurrency section describes.
Rules for the Edge Cases
These four rules are the answers an interviewer expects before any code is written, and both implementations follow all of them.
- Window boundary: the window is the W seconds ending at now, so it covers seconds
now - W + 1throughnow. A hit stamped exactlynow - Wis excluded. With W = 300 and now = 1300, a hit at second 1000 is out and a hit at second 1001 is in. - Many hits in one second: every hit lands in the same bucket and costs one increment, so a burst of 10,000 hits adds 10,000 to one counter. The queue instead stores 10,000 separate timestamps.
- A gap longer than W: nothing needs cleaning. The queue evicts everything on the next read, and every bucket fails the owner check so it contributes zero until a later hit resets it.
- Backwards or out-of-order time: the counter never lets time run backwards.
MonotonicClockraises any reading behind the highest second seen to that second. A hit that was stamped before its bucket moved on to a newer second is dropped byBucket.add(), because that second has already left the window.
Class Diagram & Entity Relationships
The factory builds one of two counters behind the HitCounter interface and wraps the supplied clock in a MonotonicClock first. The bucketed counter owns a ring of Bucket objects, and every class reads time only through Clock. Every field and method here mirrors the code blueprint.
- Strategy seam: callers hold a
HitCounterand never learn which implementation sits behind it, so the queue and the ring are interchangeable. - Clock as a seam:
SystemClockserves production,ManualClockserves tests, andMonotonicClockdecorates either one to enforce the never-backwards rule in one place. - The slot owns its truth: because
Bucketkeeps its own second and count together, a stale slot is detected by the slot itself and no outside code coordinates the reset.
Design Patterns & SOLID Principles
- Strategy Pattern (Counting Algorithm):
QueueHitCounterandBucketHitCounterboth implementHitCounter, so callers choose between exact and fixed-memory counting without changing a line of their own code. - Static Factory (Strategy Selection):
HitCounterFactory.createmaps aStrategyvalue to a concrete counter, validates the window, and wraps the supplied clock in aMonotonicClock, so no caller can forget the never-backwards rule. - Decorator Pattern (Monotonic Time):
MonotonicClockimplementsClockand holds anotherClock, adding one behavior to any clock it wraps without that clock knowing. - Dependency Injection (Clock): Counters receive a
Clockthrough the constructor, which is what letsManualClockreplaceSystemClockin tests and in the driver. - Single Responsibility Principle (SRP):
Bucketowns the stale-slot rule,BucketHitCounterowns ring indexing and summing, and the clock classes own time. - Open-Closed Principle (OCP): A running-total counter would be one new class, one new
Strategyvalue and one new case in the factory, with callers untouched.
Algorithm: Timestamp Queue Versus Bucketed Ring
Baseline: a queue of timestamps
hit() appends the current second to a queue. getHits() pops timestamps from the head while they are at or before now - W, then returns the queue size. Each timestamp is pushed once and popped once, so both operations are amortized O(1), and the answer is exact.
The cost is memory. The queue holds one entry per hit in the window, so it is O(n) in the hit count. In this blueprint only getHits() evicts, so a counter that is written but rarely read grows without bound. Evicting inside hit() as well caps the queue at one window of hits, but a counter taking 100,000 hits per second with W = 300 still holds 30 million timestamps, which is 240 MB of raw 8-byte values before object overhead.
Optimized: a ring of W buckets (the aha moment)
Hits are counted per whole second, so one counter per second carries the same information as thousands of timestamps. Keep an array of W buckets. Second s maps to bucket s mod W, and each bucket stores the second it currently counts alongside a count. hit() finds the bucket, and if the stored second differs from s it resets the bucket to second s with a zero count, then increments. getHits() sums the counts of buckets whose second lies in (now - W, now].
Overwriting a bucket never discards a live hit. Seconds s and s + W cannot both be inside a window of W seconds, so the second a bucket is giving up has already expired. That is also why no timer thread is needed: a bucket nobody visits again is simply skipped by the owner check.
Worked trace with W = 5
- Two hits at second 7 go to bucket 2 (7 mod 5), which now holds second 7 with count 2.
- One hit at second 9 goes to bucket 4, which holds second 9 with count 1.
- One hit at second 12 maps to bucket 2 again (12 mod 5). That bucket holds second 7, which differs from 12, so it resets to second 12 with count 1. The two old hits vanish, and they were already outside the window.
getHits()at second 12 uses the window(7, 12]. Bucket 2 (second 12) and bucket 4 (second 9) both qualify, so the answer is 2.
Variant: an O(1) running total
To make getHits() constant time, keep a running total. Each hit() adds one. Because buckets expire without any call, every operation first advances a swept-up-to second to now, subtracting the count of each bucket it passes. Every bucket is passed once per lap of the ring, so the sweep is amortized O(1) per elapsed second, and a gap longer than W is handled by clearing everything at once.
The trade-off is concurrency. The total spans every bucket, so the sweep and the increment must be one critical section. Per-bucket locks stop being enough and a single lock serializes every hit. Choose the plain ring when hits are hot and reads are rare, and the running total when a dashboard polls the count far more often than hits arrive.
- Queue:
hitis O(1),getHitsis amortized O(1), memory is O(n) hits in the window. - Ring:
hitis O(1),getHitsis O(W), memory is exactly W buckets whatever the hit rate. - Ring with running total: both operations are amortized O(1), memory is W buckets, and one lock guards the whole ring.
- Accuracy: with one-second buckets the ring and the queue return identical answers, which the driver prints for both. Wider buckets would save slots but blur the window edge by up to one bucket of hits.
Core Execution Workflows
1. Recording a Hit (Bucketed Counter)
- The caller invokes
hit(). The counter readsnowfrom its clock, which is aMonotonicClockand so is never behind an earlier reading. - It picks the bucket at index
now mod W.- Acquire that bucket's lock.
- If the bucket's second is greater than
now, the hit is late and the bucket has already moved on. Release the lock and drop the hit. - If the bucket's second differs from
now, the bucket is stale. Set its second tonowand its count to zero. - Increment the count and release the lock.
2. Counting Hits
- The caller invokes
getHits(). The bucketed counter readsnowand computescutoff = now - W. - For each bucket, it takes that bucket's lock briefly and reads its second and count together. The count joins the total only when
cutoff < second <= now. - It returns the total. The queue counter instead takes its single lock, pops head timestamps that are at or before the cutoff, and returns the remaining size.
3. Failure and Edge Paths
- A window of zero or less is rejected by
HitCounterFactory.createbefore any counter exists. - When the system clock steps backwards,
MonotonicClockkeeps returning the highest second seen, so hits are stamped with that second and nothing is dropped or counted in the past. - After a gap longer than W,
getHits()returns zero because every bucket fails the owner check. The next hit into a bucket that still holds an old second resets it, so the old count never leaks into the new window. - A burst inside one second takes the same path as a single hit, repeated, and the bucketed counter stores one bucket however large the burst.
Concurrency & Thread Safety Strategy
Shared State and Who Touches It
The queue counter shares one deque, touched by hit(), getHits() and storedEntries(). The bucketed counter shares many small pairs instead, the second and count inside each Bucket, written by Bucket.add() and read by Bucket.liveCount(). Every clock read also touches the high-water mark inside MonotonicClock.
The Races
- Lazy reset is a check-then-act: a bucket holds second 7 with count 40, and W = 5 sends second 12 to the same bucket. Threads A and B both hit at second 12 and both read the old second, so both decide to reset. A zeroes the count and increments it to 1, then B zeroes it again and increments to 1. Two hits are recorded as one. A reader running between the two writes of a reset can also see the new second beside the old count and report 40 phantom hits, so the second and the count must change together.
- A stale writer can rewind a bucket: thread A reads second 100 and is descheduled for longer than W seconds. The bucket has since been reused for second 100 plus W. If A then wrote its hit, it would reset the bucket back to second 100 and erase live hits. The
second > hitSecondcheck drops A's hit instead. - The sum is not a snapshot:
getHits()reads the W buckets one at a time while hits keep arriving, so it may include or miss hits that land during the scan. Each bucket is still read as a consistent pair. - The high-water mark races: two threads can both try to raise it. Losing an update would let time slip backwards for one caller.
The Guard Used and Where
In Java, Bucket.add() and Bucket.liveCount() are synchronized, so the owner check, the reset and the increment form one critical section on that bucket's own monitor. A hit touches exactly one bucket, so writers collide only when they hit the same second. QueueHitCounter synchronizes all three of its methods on one monitor because every operation touches the shared head and tail, and it reads the clock inside that lock so appended timestamps stay sorted. MonotonicClock raises its high-water mark with AtomicLong.accumulateAndGet and Math::max, which is a retried compare-and-set loop.
Python follows the same shape with a threading.Lock per Bucket, one lock in QueueHitCounter and one in MonotonicClock. The global interpreter lock does not help here, because the check, the reset and the increment span several bytecodes and a thread switch can land between them. TypeScript needs no lock. hit() and getHits() never await, so the event loop runs each call to completion and the check-then-reset cannot interleave. The driver yields every 500 hits so that its eight tasks interleave, and the total stays exact.
Why LongAdder Alone Is Not Enough
LongAdder makes the increment scale under heavy contention, but the hazard here is the pair of owner and count. Resetting a bucket means βif the owner is stale, set the owner and zero the count, then addβ, and a LongAdder offers no way to do that atomically. Its reset() is documented as effective only when no updates are in flight, so a reset that races an increment can erase it. A lock-free design needs one word that carries both values. Pack the second and the count into a single AtomicLong, then loop. Read the cell. If its second is newer, drop the hit. Otherwise compute the cell plus one for the same second, or a fresh pack of the new second and a count of 1 for a stale cell, and apply it with compareAndSet, retrying on failure. Readers then see a matching pair with one read. The price is a bounded count field and a more delicate loop, which is why the blueprint uses a plain lock.
What the Blueprint Does Not Guard
- One hot bucket: all hits in the current second share a bucket, so a single very hot counter contends on one lock. Striped counters or the packed compare-and-set version are the next step.
- Limiter check-then-act: building
if (getHits() < limit) hit()is racy, because two callers can both see the last free slot and both proceed. A rolling rate limiter needs an atomic try-acquire that checks and increments under one guard, which is the territory of the API Rate Limiter problem. - Durability: counts live in memory, so a restart empties the window.
Going Distributed
Two designs scale the count past one process. With sharded counters, each node keeps its own ring, and the fleet-wide answer is the sum of the node counts, collected on read or pushed to an aggregator, as in the Like Count System (Sharded) problem. The answer lags by the collection interval, and clock skew between nodes blurs the window edge by about the skew. With Redis, a hit runs INCR on a key named for the second, then EXPIRE on the same key inside a Lua script or a MULTI and EXEC transaction, so a crash cannot leave a key without an expiry. Expiry replaces the lazy reset, and INCR is atomic on the server, so there is no lost update to guard against. getHits() then reads exactly the W keys in the window with one MGET and sums them, so expiry only reclaims memory and never decides the window.
A Test That Exposes a Broken Guard
Run many rounds against a bucketed counter with W = 5. In each round, hit once at second 7 so the bucket owns an old second, move the manual clock to second 12, then release sixteen threads together from a barrier so each calls hit() once, and assert that getHits() returns 16. Without the per-bucket lock, some rounds return fewer because one thread's reset erases another's increment. A second, deterministic test calls add(112) and then add(107) on one bucket, which share a slot when W = 5, and asserts that the count of second 112 is still 1.
Complete Clean Code Blueprint
Clean reference designs showing the injectable clock, the exact queue, the bucketed ring with its lazily reset buckets, and the per-bucket guard in Java, TypeScript, and Python. Each driver runs the same scenario against both strategies and prints matching answers, then proves the guard with eight concurrent writers.
// βββ JAVA BLUEPRINT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
// Source of "now" in whole seconds. Injected so tests control time.
interface Clock {
long nowSeconds();
}
class SystemClock implements Clock {
@Override
public long nowSeconds() {
return System.currentTimeMillis() / 1000;
}
}
class ManualClock implements Clock {
private final AtomicLong now;
public ManualClock(long startSeconds) {
this.now = new AtomicLong(startSeconds);
}
public void set(long seconds) {
now.set(seconds);
}
@Override
public long nowSeconds() {
return now.get();
}
}
// Rule for backwards time: a reading behind the highest second seen so far is raised to it,
// so the counter's time never runs backwards. The atomic max is one CAS loop.
class MonotonicClock implements Clock {
private final Clock delegate;
private final AtomicLong highWater = new AtomicLong(Long.MIN_VALUE);
public MonotonicClock(Clock delegate) {
this.delegate = delegate;
}
@Override
public long nowSeconds() {
return highWater.accumulateAndGet(delegate.nowSeconds(), Math::max);
}
}
enum Strategy { EXACT_QUEUE, BUCKETED }
interface HitCounter {
void hit();
long getHits();
int storedEntries();
}
// Baseline: one timestamp per hit. Exact, but memory grows with the hit rate.
class QueueHitCounter implements HitCounter {
private final int windowSeconds;
private final Clock clock;
private final Deque<Long> timestamps = new ArrayDeque<>();
public QueueHitCounter(int windowSeconds, Clock clock) {
this.windowSeconds = windowSeconds;
this.clock = clock;
}
// The clock is read inside the lock, so appends stay sorted for a monotonic clock.
@Override
public synchronized void hit() {
timestamps.addLast(clock.nowSeconds());
}
@Override
public synchronized long getHits() {
long cutoff = clock.nowSeconds() - windowSeconds;
while (!timestamps.isEmpty() && timestamps.peekFirst() <= cutoff) {
timestamps.pollFirst();
}
return timestamps.size();
}
@Override
public synchronized int storedEntries() {
return timestamps.size();
}
}
// One slot of the ring. It remembers which second it is counting, so a stale slot is
// recognised and reset lazily. Every access holds this bucket's own monitor.
class Bucket {
private long second = -1;
private long count = 0;
public synchronized void add(long hitSecond) {
if (second > hitSecond) {
return; // late hit: this slot already moved on, so the hit has expired
}
if (second != hitSecond) {
second = hitSecond; // stale slot from an older lap of the ring: reset it
count = 0;
}
count++;
}
public synchronized long liveCount(long cutoff, long now) {
return (second > cutoff && second <= now) ? count : 0;
}
}
// Optimized: a ring of W buckets indexed by second % W. Fixed memory, O(1) hit, O(W) getHits.
class BucketHitCounter implements HitCounter {
private final int windowSeconds;
private final Clock clock;
private final Bucket[] buckets;
public BucketHitCounter(int windowSeconds, Clock clock) {
this.windowSeconds = windowSeconds;
this.clock = clock;
this.buckets = new Bucket[windowSeconds];
for (int i = 0; i < windowSeconds; i++) {
buckets[i] = new Bucket();
}
}
@Override
public void hit() {
long now = clock.nowSeconds();
buckets[(int) (now % windowSeconds)].add(now);
}
// Each bucket is read consistently, but the sum is not one atomic snapshot of the ring.
@Override
public long getHits() {
long now = clock.nowSeconds();
long cutoff = now - windowSeconds;
long total = 0;
for (Bucket bucket : buckets) {
total += bucket.liveCount(cutoff, now);
}
return total;
}
@Override
public int storedEntries() {
return buckets.length;
}
}
class HitCounterFactory {
private HitCounterFactory() {}
public static HitCounter create(Strategy strategy, int windowSeconds, Clock clock) {
if (windowSeconds <= 0) {
throw new IllegalArgumentException("windowSeconds must be positive.");
}
Clock monotonic = new MonotonicClock(clock);
switch (strategy) {
case EXACT_QUEUE:
return new QueueHitCounter(windowSeconds, monotonic);
case BUCKETED:
return new BucketHitCounter(windowSeconds, monotonic);
default:
throw new IllegalArgumentException("Unknown strategy: " + strategy);
}
}
}
public class Main {
private static void runScenario(Strategy strategy) throws Exception {
ManualClock clock = new ManualClock(1000);
HitCounter counter = HitCounterFactory.create(strategy, 300, clock);
String tag = "[" + strategy + "] ";
for (int i = 0; i < 3; i++) counter.hit(); // 3 hits at t=1000
clock.set(1100);
for (int i = 0; i < 2; i++) counter.hit(); // 2 hits at t=1100
clock.set(1299);
System.out.println(tag + "t=1299 hits=" + counter.getHits() + " (the window is seconds 1000 to 1299)");
clock.set(1300);
System.out.println(tag + "t=1300 hits=" + counter.getHits() + " (a hit at exactly now-W is out)");
for (int i = 0; i < 10_000; i++) counter.hit(); // burst inside one second
System.out.println(tag + "t=1300 burst of 10000 hits=" + counter.getHits() + " stored=" + counter.storedEntries());
clock.set(2000); // gap of 700 seconds, longer than W
System.out.println(tag + "t=2000 after a long gap hits=" + counter.getHits());
counter.hit(); // lands in the bucket still holding t=1100
System.out.println(tag + "t=2000 one hit into a stale bucket hits=" + counter.getHits());
clock.set(1990); // the system clock steps back
counter.hit();
System.out.println(tag + "clock back at 1990 hits=" + counter.getHits() + " (time did not run backwards)");
clock.set(3000);
ExecutorService pool = Executors.newFixedThreadPool(8);
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
for (int i = 0; i < 5000; i++) counter.hit();
});
}
pool.shutdown();
pool.awaitTermination(30, TimeUnit.SECONDS);
System.out.println(tag + "t=3000 8 threads x 5000 hits=" + counter.getHits() + " (expected 40000)");
}
public static void main(String[] args) throws Exception {
runScenario(Strategy.EXACT_QUEUE);
runScenario(Strategy.BUCKETED);
HitCounter live = HitCounterFactory.create(Strategy.BUCKETED, 300, new SystemClock());
live.hit();
live.hit();
System.out.println("[SystemClock] two real hits=" + live.getHits());
}
}Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.