Problem Statement
The goal is to design a Hit Counter system that tracks and counts hits received within the past 5 minutes ().
The system must support two primary operations:
Key Requirements & Constraints
Evolution of Solutions Discussed Throughout our technical discussion, five distinct architectural approaches were analyzed:
Solution 1: Dynamic Array + Binary Search
Deep Dive:
Why Certain Approaches Fail or Stagnate Under Concurrency
While several concepts appear sound on paper, subtle low-level execution mechanics under the Java Virtual Machine (JVM) memory model and modern CPU architectures introduce critical failure modes:
+-----------------------------------------------------------------------------------------------------------------+
| CONCURRENCY PITFALLS ANALYSIS |
+------------------------------------+---------------------------------------------------------------------------+
| Proposed Idea | Primary Failure Mechanism under High Concurrency |
+------------------------------------+---------------------------------------------------------------------------+
| 1. Dynamic List + Binary Search | • Structural list corruption during append |
| | • Out-of-order writes break sorted invariant |
| | • Memory leaks: $O(N)$ unbound memory growth |
+-------------------------------------------+--------------------------------------------------------------------+
| 2. Unsynchronized Array Writes | • Store Buffer Reordering: Timestamp updated |
| (Split-Brain Reset) | before count (or vice versa) |
| | • Concurrent reset overwrites fresh counts |
+---------------------------------------------+------------------------------------------------------------------+
| 3. Queue-Based Single Writer | • Contention shifts from array to Queue Lock |
| (`ExecutorService`) | • GC Pressure from millions of Task objects |
| | • High Latency: $\sim\mu\text{s}$ vs $\text{ns}$ ops |
+-----------------------------------------+----------------------------------------------------------------------+
Technical Explanations of Failures
Architectural Comparison & Decision Matrix
No single solution is strictly "wrong"—each represents a trade-off between implementation complexity, throughput, latency, and memory footprint.
The goal is to design a Hit Counter system that tracks and counts hits received within the past 5 minutes ().
The system must support two primary operations:
- hit(timestamp): Records a hit at the given timestamp (in seconds). Multiple hits can occur at the exact same timestamp.
- getHits(timestamp): Returns the total number of hits received in the past 300 seconds from the given timestamp—specifically in the inclusive time window.
Key Requirements & Constraints
- Time Window: Fixed at 300 seconds ().
- Chronological Invariant (Basic): Standard single-threaded inputs arrive in monotonically increasing order.
- Multi-Threaded Concurrency: High-volume, parallel calls to both hit() and getHits() across multiple CPU cores without data corruption, thread blocking bottlenecks, or memory exhaustion.
Evolution of Solutions Discussed Throughout our technical discussion, five distinct architectural approaches were analyzed:
Solution 1: Dynamic Array + Binary Search
- Concept: Append each incoming hit timestamp to a dynamic list (ArrayList). On getHits(t), compute the lower bound and use binary search (bisect_left) to locate the first valid index within the window.
- Design Pattern / Algorithm: Binary Search (Lower Bound), Append-Only Log Pattern.
- Concept: Maintain two fixed-size arrays of length 300 (times[] and hits[]). Map timestamps to buckets using modulo arithmetic (idx = timestamp % 300). Protect array updates and reads using a ReentrantReadWriteLock.
- Design Pattern / Algorithm: Ring Buffer (Circular Array), Readers-Writer Lock Pattern.
- Concept: Partition the counter into independent ring buffer "Cells" (stripes). Incoming calls to hit() route to a specific stripe based on thread identity or thread-local random probing, avoiding global write contention. getHits() aggregates totals across all stripes.
- Design Pattern / Algorithm: Striping / Sharding, Per-Thread Allocation (similar to Java's LongAdder).
- Concept: Route hit requests through an ExecutorService task queue with a fixed pool of worker threads. Apply the Single-Writer Principle, where a single assigned thread exclusively mutates a specific cell buffer to eliminate write-write Compare-And-Swap (CAS) conflicts without locks.
- Design Pattern / Algorithm: Single-Writer / Actor Pattern, Command Pattern, Producer-Consumer Queue.
- Concept: Maintain a single 300-slot AtomicLongArray. Bit-pack both the timestamp (high 32 bits) and the hit count (low 32 bits) into a single 64-bit long primitive. Update state using a lock-free Compare-And-Swap (compareAndSet) retry loop.
- Design Pattern / Algorithm: Lock-Free CAS (Compare-And-Swap), Bit-Packing / Bitwise Manipulation, Atomic Ring Buffer.
Deep Dive:
Why Certain Approaches Fail or Stagnate Under Concurrency
While several concepts appear sound on paper, subtle low-level execution mechanics under the Java Virtual Machine (JVM) memory model and modern CPU architectures introduce critical failure modes:
+-----------------------------------------------------------------------------------------------------------------+
| CONCURRENCY PITFALLS ANALYSIS |
+------------------------------------+---------------------------------------------------------------------------+
| Proposed Idea | Primary Failure Mechanism under High Concurrency |
+------------------------------------+---------------------------------------------------------------------------+
| 1. Dynamic List + Binary Search | • Structural list corruption during append |
| | • Out-of-order writes break sorted invariant |
| | • Memory leaks: $O(N)$ unbound memory growth |
+-------------------------------------------+--------------------------------------------------------------------+
| 2. Unsynchronized Array Writes | • Store Buffer Reordering: Timestamp updated |
| (Split-Brain Reset) | before count (or vice versa) |
| | • Concurrent reset overwrites fresh counts |
+---------------------------------------------+------------------------------------------------------------------+
| 3. Queue-Based Single Writer | • Contention shifts from array to Queue Lock |
| (`ExecutorService`) | • GC Pressure from millions of Task objects |
| | • High Latency: $\sim\mu\text{s}$ vs $\text{ns}$ ops |
+-----------------------------------------+----------------------------------------------------------------------+
Technical Explanations of Failures
- Failure of Dynamic List + Binary Search:
- Concurrent appends to an unsynchronized ArrayList lead to lost updates, corrupted array bounds, or race conditions.
- If Thread A () gets preempted and writes after Thread B (), the list is no longer sorted, causing binary search to return corrupt results.
- The "Split-Brain" Cell Reset Vulnerability:
- If timestamps and hit counts are stored in two separate arrays (times[300] and hits[300]), resetting an expired bucket requires two distinct writes.
- Race Scenario: Thread A clears an old bucket by updating times[idx] = t. Thread B arrives concurrently, sees the updated time, and increments hits[idx]. Thread A then proceeds to overwrite hits[idx] = 1, completely discarding Thread B's update.
- Memory Visibility & CPU Instruction Reordering:
- CPU cores utilize L1/L2 store buffers. Without explicit volatile memory fences or atomic operations, plain array writes remain trapped in local store buffers.
- A reader thread calling getHits() on a separate CPU core can read stale counts or see reordered instructions (e.g., reading an updated count paired with an old timestamp).
- Bottlenecks of Executor-Based Task Queues:
- Enqueuing every hit request into an ExecutorService relies on queue locks (e.g., ReentrantLock in ArrayBlockingQueue). Under heavy load, caller threads contend for the queue lock, defeating the performance gain.
- Allocating a Runnable object per hit creates heavy garbage collection (GC) pressure, while context-switching worker threads increases latency from nanoseconds to microseconds.
Architectural Comparison & Decision Matrix
No single solution is strictly "wrong"—each represents a trade-off between implementation complexity, throughput, latency, and memory footprint.
Implementation Summary:
Bit-Packed CAS Ring BufferFor high-throughput concurrent systems, Solution 5 provides the optimal balance of speed, safety, and memory efficiency. By bit-packing the timestamp and hit count into a 64-bit long inside an AtomicLongArray, both variables are updated in a single hardware-level CPU instruction (LOCK CMPXCHG):
64-Bit Packed Atomic Primitive Layout
+-------------------------------------------+-----------------------------------------+
| High 32 Bits: Timestamp | Low 32 Bits: Hit Count |
| (Bits 63 . . . . . . . . 32) | (Bits 31 . . . . . . . . 0) |
+-------------------------------------------+-----------------------------------------+
Key Bitwise Formulas
Bit-Packed CAS Ring BufferFor high-throughput concurrent systems, Solution 5 provides the optimal balance of speed, safety, and memory efficiency. By bit-packing the timestamp and hit count into a 64-bit long inside an AtomicLongArray, both variables are updated in a single hardware-level CPU instruction (LOCK CMPXCHG):
64-Bit Packed Atomic Primitive Layout
+-------------------------------------------+-----------------------------------------+
| High 32 Bits: Timestamp | Low 32 Bits: Hit Count |
| (Bits 63 . . . . . . . . 32) | (Bits 31 . . . . . . . . 0) |
+-------------------------------------------+-----------------------------------------+
Key Bitwise Formulas
- Packing: packedVal = ((long) timestamp << 32) | (hits & 0xFFFFFFFFL)
- Unpacking Timestamp: recordedTime = (int) (packedVal >>> 32)
RSS Feed