Nitin Agrawal
Contact -
  • Home
  • Interviews
    • InterviewFacts >
      • Secret Receipe
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • Companies
    • CompanyInterviews >
      • InvestmentBanks >
        • ECS
        • Bank Of America
        • WesternUnion
        • WellsFargo
        • Deutsche Bank
      • ProductBasedCompanies >
        • CA Technologies
        • Verizon Media
        • Oracle & GoJek
        • IVY Computec
        • Nvidia
        • ClearWaterAnalytics
        • ADP
        • ServiceNow
        • Pubmatic
        • Expedia
        • Amphora
        • CDK Global
        • Delphix
        • CDK Global
        • Epic
        • Sincro-Pune
        • Whiz.AI
        • ChargePoint
        • Salesforce
        • Product Based
        • WayFair
        • Agoda
        • NPCI
        • Minicom
      • ServiceBasedCompanies >
        • SapientInterview
        • Altimetrik
        • ASG World Wide Pvt Ltd
        • Paraxel International & Pramati Technologies Pvt Ltd
        • MitraTech
        • Intelizest Coding Round
        • EPAM
        • Persistent Interview
    • Interviews Theory
    • Interview Questions >
      • 5-12 years Experienced
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems >
        • Problem10
        • Problem300
      • AnagramsSet
    • Core Java >
      • GarbageCollectors
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Profiling
      • Java Releases >
        • Java8 >
          • Performance
          • NasHorn
          • WordCount
          • Thoughts
        • Java9 >
          • ServiceLoaders
          • Lambdas
          • List Of Objects
          • Code Snippets
        • Java14 >
          • Teeing
          • Pattern
          • Semaphores
        • Java17 >
          • Switches
          • FunctionalStreams
          • Predicate
          • Consumer_Supplier
          • Collectors in Java
        • Java21 >
          • Un-named Class
          • Virtual Threads
          • Structured Concurrency
        • Java25
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • ThreadPoolExecutor
        • RecursiveTask
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • Sample Code Part 1 >
        • PatternLength
        • Serialization >
          • Kryo2
          • JAXB/XSD
          • XStream
        • MongoDB
        • Strings >
          • Reverse the String
          • Reverse the String in n/2 complexity
          • StringEditor
          • Reversing String
          • String Puzzle
          • Knuth Morris Pratt
          • Unique characters
          • Top N most occurring characters
          • Longest Common Subsequence
          • Longest Common Substring
        • New methods in Collections
        • MethodReferences
        • Complex Objects Comparator >
          • Performance
        • NIO >
          • NIO 2nd Sample
        • Date Converter
        • Minimum cost path
        • Find File
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • TemplatePattern
        • Adapter Design Pattern
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • Singleton >
          • Singletons
        • Strategy
  • Frameworks
    • Apache Velocity
    • React Library >
      • Tutorial
    • Spring >
      • Spring AI
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • Custom Beans
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit 5 Parameterized Test
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
      • Pact testing
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Messaging Formats
      • Design Patterns
    • AWS >
      • Honeycode
    • Dockers >
      • GitBash
      • Issues
      • Kubernetes
  • Databases
    • MySql
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search
  • Random issues
    • TOAD issue
    • System Design >
      • Cross-Region_Database_Replication
      • Real-Time SMS/USSD Mobile Money Platform
      • UPI_Payment_System_Design
      • Multi-Threaded Hit Counter Architecture
    • Architect's suggestions >
      • Comprehensive Acronyms Reference Guide
      • The Architectural Paradox: Balancing Strategic Value Against Catastrophic Risk in Enterprise Architecture
    • Dynamic loading of agents
  • Your Views

Technical Analysis: Multi-Threaded Hit Counter Architecture

9/6/2026

0 Comments

 
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:
  • 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
  1. Time Window: Fixed at 300 seconds ().
  2. Chronological Invariant (Basic): Standard single-threaded inputs arrive in monotonically increasing order.
  3. 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.
Solution 2: Fixed Circular Ring Buffer with Read-Write Lock
  • 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.
Solution 3: Striped / Per-Core Cell Array
  • 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).
Solution 4: Asynchronous Single-Writer Task Queue (ExecutorService)
  • 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.
Solution 5: Lock-Free Bit-Packed Atomic Ring Buffer
  • 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
  1. 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.
  2. 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.
  3. 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).
  4. 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.
Picture
 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
  • Packing: packedVal = ((long) timestamp << 32) | (hits & 0xFFFFFFFFL)
  • Unpacking Timestamp: recordedTime = (int) (packedVal >>> 32)
0 Comments

    Author

    Archives

    September 2026

    Categories

    All

    RSS Feed

Powered by Create your own unique website with customizable templates.