Design a Memory-Bounded Real-Time URL Analytics Engine
System DesignModel answerLast updated
Architect a memory-efficient system to compute exact all-time and probabilistic 24-hour rolling Top-K URLs from high-velocity web request logs.
Context
A global content delivery network handles hundreds of thousands of HTTP requests per second. To provide actionable telemetry and dynamic firewall rules, you need to build a stream processing platform that continuously tracks and surfaces the most heavily accessed URLs.
Requirements
Functional
- Global Top-K: Query
GetGlobalTopK(k)returning the top $k$ most accessed URLs since system inception ($k \le 1{,}000$). - Rolling Top-K: Query
GetRollingTopK(k, window=24h)returning the top $k$ most accessed URLs within the trailing 24 hours ($k \le 1{,}000$). - Event Ingestion: Process an unbounded stream of log entries formatted as
(url: String, timestamp: EpochMs, user_agent: String, client_ip: String).
Non-Functional & Operational
- Peak Throughput: $100{,}000$ events/second ($\approx 8.6$ billion events/day).
- High Cardinality: Up to 500 million unique URL strings globally.
- Resource Limits: Worker nodes are constrained to 4 GB of physical RAM each. The complete URL state space cannot fit in system memory.
- Latency & Freshness: Read queries must return in under $100\text{ ms}$. Rolling window output must reflect events processed within the last $1\text{--}5$ minutes.
- Out-of-Order Events: Gracefully process events arriving up to 15 minutes out of sequence.
- Accuracy Constraints: Provide guaranteed bounded error approximations where probabilistic structures are used, and define exact tracking bounds where required.
Key Areas to Cover
- System Topology & Data Pipeline: Map the high-level architecture from ingestion (e.g., Kafka) to stream aggregation (e.g., Flink) and serving storage.
- Memory-Constrained Counting Architecture: Compare exact disk-backed state (LSM-trees / RocksDB) against bounded-memory sketches (Space-Saving, Count-Min Sketch). Define key partition strategies that protect nodes from memory exhaustion.
- Sliding Window Processing: Detail how the 24-hour sliding window is discretized into discrete micro-buckets, how state is expired, and how bucket summaries are merged.
- Fault Tolerance & Skew: Explain how to address hot key distributions (e.g., viral URLs) and maintain consistency using watermarks and checkpoints.
Hints
Hint 1
Estimate the size of the full global state space (500M unique URLs) to prove why pure in-memory hash maps fail on a single node.
Hint 2
Partitioning incoming traffic by URL hash guarantees that all instances of a specific URL land on the exact same stream processing worker.
Hint 3
To handle a 24-hour sliding window without high memory churn, discretize time into 5-minute fixed buckets and store mergeable sketches like Space-Saving rather than raw events.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Scale & Capacity Estimation
Data Velocity & Volume
- Ingress Throughput: $100{,}000\text{ events/sec} \times 86{,}400\text{ sec/day} \approx 8.64\text{ billion events/day}$.
- Payload Size: Assuming raw event payloads are $\sim 200\text{ bytes}$, network ingress is roughly $20\text{ MB/s}$ ($160\text{ Mbps}$).
Memory Constraints & State Space
- Unique Cardinality: Up to $500\text{ million}$ unique URLs globally.
- Exact In-Memory State Size: Storing a 500M map of
(URL String -> uint64)requires: $$\text{Memory} \approx 500\text{M} \times (\overbrace{100\text{ bytes}}^{\text{Average URL length}} + \overbrace{8\text{ bytes}}^{\text{Counter}} + \overbrace{32\text{ bytes}}^{\text{Map pointer overhead}}) \approx 70\text{ GB}$$ - Node Constraint: 4 GB RAM per instance. Conclusion: Single-node or pure in-memory state tracking is impossible. State must be distributed, off-loaded to disk (LSM-tree), or tracked probabilistically.
Query Latency & Windowing Parameters
- Target Latency: $< 100\text{ ms}$ (served directly from an in-memory cache/read-replica).
- Sliding Window Resolution: 24-hour rolling window discretized into 5-minute buckets: $$\frac{24\text{ hours} \times 60\text{ min/hour}}{5\text{ min/bucket}} = 288\text{ discrete buckets}$$
2. High-Level System Architecture
+-----------------------------+
| Ingest & Pre-Aggregation |
| (Stateless Combiners) |
+--------------+--------------+
|
v (Partitioned by Hash(URL))
+--------------+--------------+
| Stateful Stream Engine |
| (Flink + RocksDB Workers) |
+--------------+--------------+
|
(Periodic Top-K Summary Push)
v
+--------------+--------------+
| Snapshot Serving Store |
| (Redis Cluster) |
+--------------+--------------+
|
v
[ API / Clients ]
Data Pipeline Components
-
Ingress Tier (Kafka):
- Event stream ingested into a primary Kafka topic (
raw-access-logs). - Partitioning strategy: Round-Robin (or client-ip hash) to prevent partition-level network bottlenecks from skewed traffic patterns.
- Event stream ingested into a primary Kafka topic (
-
Stage 1: Pre-Aggregation (Stateless Stream Workers):
- Micro-batches events locally for 1–2 seconds.
- Performs URL normalization (lower-casing, trailing slash stripping, query parameter removal if out of scope).
- Computes a 64-bit fingerprint (
url_hash = xxHash64(normalized_url)). - Emits aggregated partial tuples
(url_hash, url_string, bucket_id, count)topartitioned-access-logs, partitioned explicitly byurl_hash.
-
Stage 2: Stateful Counting Engine (Stream Processors):
- Workers run partitioned stateful processing (e.g., Apache Flink with RocksDB state backend).
- Because incoming logs are partitioned by
url_hash, a given URL is processed by exactly one worker.
-
Stage 3: Snapshot & Serving Tier (Redis / Cache):
- Workers do not process read queries directly.
- Every 1 minute, workers emit their local Top-$K'$ candidates ($K' = 2{,}000$) to an aggregator process.
- The global aggregator computes the true Top-$K$ and writes an immutable versioned snapshot to Redis.
- API servers read directly from Redis ($\mathcal{O}(1)$ lookup, $< 5\text{ ms}$ query latency).
3. Counting Engine Architecture: Exact vs. Probabilistic
| Strategy | Memory Footprint | Accuracy | Pros/Cons |
|---|---|---|---|
| Exact (RocksDB LSM-Tree) | Bounded RAM (512 MB block cache), unbounded SSD disk space | 100% Exact | Supports auditing; higher write amplification and disk I/O. |
| Count-Min Sketch + Min-Heap | $\sim 8\text{ MB}$ per node | Overestimate bound by $\epsilon N$ with probability $1-\delta$ | Low memory; cannot track key strings natively (requires side-heap). |
| Space-Saving Algorithm | Bounded to $m$ counters ($\sim 160\text{ KB}$ for $m=10{,}000$) | Guaranteed heavy hitters retained with error $\le N/m$ | Deterministic, highly space-efficient, mergeable across windows. |
Hybrid Processing Strategy
To balance absolute accuracy for historical telemetry with memory constraints for rolling windows, we deploy a hybrid model across processing partitions:
+-------------------------------------------------+
| Stage 2 Partition Worker (e.g., Partition #12) |
+------------------------+------------------------+
|
+-----------------------+-----------------------+
| |
v v
[ Global (All-Time) Tracker ] [ 24h Rolling Window Tracker ]
----------------------------- ------------------------------
- Storage: RocksDB (Disk) - Storage: Memory (RAM)
- Structure: Exact Hash Map - Structure: 288 Bucked Summaries
(url_hash -> exact_count) (Space-Saving, m=10,000)
- Maintain: Local Min-Heap (K'=2,000) - Recompute: Merge active buckets
Global (All-Time) Counter: Exact Disk-Backed State
- Each partition handles a subset of the keyspace ($\sim 8\text{ million}$ unique URLs per partition across 64 partitions).
- State Store: Embedded RocksDB instance. Key:
url_hash(8 bytes) $\rightarrow$ Value:(count: uint64, url_string: String). - In-Memory Heap Top-$K'$: Each worker maintains a local Min-Heap of size $K' = 2{,}000$.
- If a URL's updated count in RocksDB exceeds the heap minimum, update the local heap.
- RAM usage per partition for global tracking is constrained to the size of the block cache (e.g., $512\text{ MB}$) plus the tiny 2,000-element heap ($< 1\text{ MB}$).
24-Hour Rolling Counter: Space-Saving Sketch Array
- A pure exact sliding window over 500M unique keys generates unmanageable state churn.
- Data Structure: Use a discretized array of Space-Saving Sketches (one per 5-minute bucket for 24 hours = 288 bucket sketches).
- Each bucket's sketch tracks $m = 10{,}000$ counter nodes.
- Counter Node Layout:
(url_hash: uint64, count: uint64, error: uint64)$\approx 24\text{ bytes}$. - Memory per bucket per partition: $10{,}000 \times 24\text{ bytes} \approx 240\text{ KB}$.
- Total rolling memory for 288 buckets: $288 \times 240\text{ KB} \approx \mathbf{69.1\text{ MB}}$ per partition worker.
4. Sliding Window Implementation
Discretization & Event-Time Processing
- Time Window Mapping: $$\text{bucket_id} = \lfloor \frac{\text{event_timestamp_ms}}{300{,}000} \rfloor$$
- Watermarking & Late Data Handling:
- Out-of-order events are common in distributed edge logs.
- Maintain a streaming Watermark per partition: $\text{Watermark} = \max(\text{event_timestamp}) - 15\text{ minutes}$.
- Buckets before $\text{Watermark} - 24\text{ hours}$ are sealed and pruned from memory.
- Events arriving late (timestamp $< \text{Watermark}$ but within the 24-hour horizon) are routed into their respective open bucket sketch. Events older than 24 hours are dropped to a dead-letter queue / cold store metric.
[Expired] <--- [Sealed Bucket] ... [Sealed Bucket] [Active Bucket] <--- Watermark
(T - 24h - 15m) (T - 23h 55m) (T - 5m) (T - 0m)
Window Merging Algorithm
Every 1 minute, each partition worker calculates its local trailing 24-hour Top-$K'$:
- Iterate Buckets: Fetch all 288 active Space-Saving sketches for the last 24 hours.
- Combine Summaries: Merge the $288 \times 10{,}000$ counter entries into a temporary combined map:
- For each entry
(url_hash)across sketches, compute: $$\text{total_count} = \sum \text{count}_i, \quad \text{total_error} = \sum \text{error}_i$$
- For each entry
- Extract Top-$K'$: Insert combined entries into a local Min-Heap bounded to size $K' = 2{,}000$.
- Emit Candidates: Send local Top-$K'$ lists to the Global Aggregator.
Global Aggregation & Deterministic Tie-Breaking
The Global Aggregator receives up to 64 local Top-$K'$ candidate lists from the partition workers:
def merge_partition_topk(partition_lists, k):
# Global hash map to accumulate counts from workers
combined = {}
for worker_list in partition_lists:
for entry in worker_list:
if entry.url_hash not in combined:
combined[entry.url_hash] = {
'url': entry.url,
'count': 0,
'max_error': 0
}
combined[entry.url_hash]['count'] += entry.count
combined[entry.url_hash]['max_error'] += entry.error
# Convert map to array and sort deterministically
# Primary sort: count descending
# Secondary sort: url_hash ascending (prevents flapping across queries)
candidates = list(combined.values())
candidates.sort(key=lambda x: (-x['count'], x['url']))
return candidates[:k]
5. Mitigation of Operational Realities
Hot Key Skew (Viral URLs)
- Problem: A viral news event causes a single URL to hit 50,000 requests/sec. Partitioning raw logs directly by
hash(URL)will overwhelm a single worker partition CPU/network interface. - Solution:
- Stage 1 Micro-Batch Combiners: Ingest instances aggregate counts locally in RAM for 1 second before writing to the intermediate Kafka topic. A viral URL generating 50,000 hits/sec across 50 ingest nodes is collapsed into just 50 aggregated records/sec emitted to the stream network.
- Salted Partitioning (Fall-back): If a single key exceeds 5% of total cluster volume, append a random salt $s \in [0, S-1]$ to the key (
url_hash#s) to distribute it across $S$ workers, merging the salted counts downstream during the global aggregation phase.
Fault Tolerance & State Recovery
- Checkpointing: Enable Flink-style Chandy-Lamport distributed snapshots saved every 60 seconds to cloud object storage (e.g., S3).
- State Recovery:
- On worker crash, the orchestrator spins up a replacement container.
- The worker recovers its local RocksDB state and Space-Saving bucket sketches from the latest snapshot in S3.
- Replays uncommitted messages from Kafka starting at the snapshot's aligned offsets.
6. Trade-offs & Error Analysis
Error Bounds of Space-Saving Merge
- For a Space-Saving sketch with $m$ counters over $N$ total elements, the maximum overestimation error per item is $\le \frac{N}{m}$.
- With $m = 10{,}000$ and $N_{24h} \approx 8.64 \times 10^9$ events split across 64 partitions ($N_{\text{partition}} \approx 135 \times 10^6$ events/day): $$\text{Max Error Per Bucket} = \frac{135 \times 10^6 / 288}{10{,}000} \approx 46.8\text{ counts}$$ $$\text{Max Aggregated 24h Error} = 288 \times 46.8 \approx \mathbf{13{,}500\text{ counts}}$$
- For high-velocity URLs appearing in the Top-1000 (which routinely accumulate $> 100{,}000$ hits/day), an absolute error of $\sim 13{,}500$ counts represents an acceptable relative error bound ($< 1%$).
Key Architectural Trade-offs
- 5-Minute Buckets vs. Continuous Sliding Windows:
- Discretizing into 5-minute buckets dramatically lowers memory and CPU overhead compared to continuous timestamp queues, at the cost of up to 5 minutes of boundary granularity.
- Probabilistic Rolling vs. Exact Global:
- Rolling windows rely on Space-Saving sketches to fit strictly inside 4 GB RAM. Global counts utilize local SSD disk storage (RocksDB) to deliver 100% exact all-time tracking without risking node OOM crashes.