Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

1M Events/sec Streaming Distinct-Count
& Top-K Without OOM.

Replace per-pod HashSets and HashMaps with 16 KB HyperLogLog sketches (for distinct users) and 256 KB Count-Min Sketch + size-K Min-Heaps (for Top-K endpoints), merged across workers in 1-minute tumbling sub-windows.
Start the journey7 stages· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Your real-time telemetry pipeline ingests 1,000,000 events/sec across 16 Kafka/Flink worker pods (4 GB RAM per pod) and tracks 50,000,000 unique `user_id`s and `endpoint`s per 1-hour sliding window across 200 tenants. Using per-pod `HashSet` and `HashMap` aggregations causes pods to exceed 12 GB and crash with `OOMKilled` (exit code 137) within 10 minutes, while shuffling raw `user_id`s across nodes saturates the network. Design a <1 MB/shard streaming analytics architecture.

From patterns to decisions.

Replace per-pod HashSets and HashMaps with 16 KB HyperLogLog sketches (for distinct users) and 256 KB Count-Min Sketch + size-K Min-Heaps (for Top-K endpoints), merged across workers in 1-minute tumbling sub-windows.

Full walkthrough · 7 stages
01
Stage 1 • Triagefoundation

Why 50M Unique Keys + Sliding Windows OOM 4 GB Pods.

Even 3.1M unique user_ids per pod (50M / 16 pods) in a HashSet<String> takes ~3.1M * 96 bytes ≈ 300 MB for one window. With a 1-hour sliding window advancing every 1 minute, naive overlapping panes multiply memory by 60x (18 GB!)—far above the 4 GB cgroup limit (OOMKilled 137).

Memory Explosion

50M Keys x 60 Sliding Panes -> 18 GB OOMKilled

1M Events/secHashSet + 60 PanesOOMKilled (137)StorePod crash loop

1.:

2.:

Caption: Storing exact HashSets across 60 overlapping 1-minute panes multiplies RAM past 18 GB per pod, triggering OOMKilled (exit 137).

02
Stage 2 • Window Architecturefoundation

60x 1-Minute Tumbling Panes with Mergeable HLL + CMS.

Instead of assigning every event to 60 overlapping windows, each worker maintains 1 active 1-minute tumbling sketch (HLL + CMS + TopK):

  • Zero Duplication: Each incoming event updates exactly one active sketch in O(1) time.
  • Sliding Window Evaluation: At minute T, the central aggregator stores a 60-slot ring buffer of global 1-minute sketches [T-59 .. T] and merges them in <2 ms (max for HLL, sum for CMS) to answer the 1-hour sliding query.
Pane Merging

1 Active Pane/Worker -> 60-Slot Ring Buffer -> 1h Query

Active 1m Sketch16-Worker Merge60-Pane Ring BufferStoreEvict T-60 pane

1.:

2.:

Caption: Decomposing a 1-hour sliding window into 60 tumbling 1-minute sketch panes cuts worker state by 60x and lets the aggregator merge global metrics in <2 ms.

03
Stage 3 • Memory Mathintermediate

Exact RAM & Error Budgeting Across 200 Tenants.

Size each sketch explicitly before deployment:

  • HyperLogLog (p=12 per tenant, or p=14 for top tenants): p=12 uses 4 KB (+-1.6% error); 200 tenants * 4 KB = 800 KB per worker!
  • Count-Min Sketch (d=4, w=2,048 x 4B ints): 32 KB per tenant (200 * 32 KB = 6.4 MB per worker; or 1 shared global CMS keyed by (tenant_id, endpoint) using 256 KB total).
  • Top-100 Min-Heap: 100 * 128B ≈ 13 KB per tenant (2.6 MB total).
Memory Budget

Per-Tenant Sketch Footprint vs Shared CMS

200 Per-TenantSketchesShared Global CMS +HLLStateStore

1.:

2.:

Caption: Sizing HLL at p=12 (4 KB) and using a shared tenant-prefixed Count-Min Sketch (256 KB) keeps total per-pod memory under 1–10 MB.

04
Stage 4 • Skew & Hot Keysintermediate

Handling Tenant Skew & High-Volume DDoS Bursts.

If Tenant A generates 900K events/sec (N_total = 54M/min) while Tenant B generates 100 events/sec, a single shared CMS has error epsilon * N_total = 0.001 * 54M = 54,000—swamping Tenant B's true count of 100!

  • Isolate Whale Tenants: Route heavy-hitter tenants (> 10K events/sec) to dedicated per-tenant CMS instances, while small tenants share a pooled CMS (or use exact dict until cardinality > 1,000).
  • Exact-to-Sketch Promotion: Start new/small tenants in a tiny 1,000-entry dict and promote to HLL+CMS only when len > 1,000.
Skew Isolation

Shared CMS Pollution vs Whale-Isolated Sketches

Shared CMS OnlyExact <1K ->Isolated SketchStateStore

1.:

2.:

Caption: Promoting small tenants from exact maps (>1,000 keys) and isolating high-volume whale tenants prevents cross-tenant Count-Min over-estimation.

05
Stage 5 • Implementationintermediate

Streaming Pane Aggregator with CMS + Min-Heap & Bounded Flush Retry.

Below is a self-contained Python TopKSketchPane combining a d x w Count-Min Sketch, a size-K Min-Heap, and bounded retry when flushing closed 1-minute panes:

import hashlib, heapq, random, time

class TopKSketchPane:
    def __init__(self, k: int = 10, d: int = 4, w: int = 2048):
        self.k, self.d, self.w = k, d, w
        self.table = [[0] * w for _ in range(d)]
        self.topk_map: dict[str, int] = {}

    def _hashes(self, key: str) -> list[int]:
        digest = hashlib.blake2b(key.encode(), digest_size=16).digest()
        h1 = int.from_bytes(digest[:8], 'big')
        h2 = int.from_bytes(digest[8:], 'big') | 1
        return [((h1 + i * h2) & 0xFFFFFFFFFFFFFFFF) % self.w for i in range(self.d)]

    def add(self, key: str, count: int = 1) -> int:
        est = None
        for r, col in enumerate(self._hashes(key)):
            self.table[r][col] += count
            val = self.table[r][col]
            est = val if est is None or val < est else est
        assert est is not None
        if key in self.topk_map or len(self.topk_map) < self.k:
            self.topk_map[key] = est
        else:
            min_k, min_v = min(self.topk_map.items(), key=lambda kv: kv[1])
            if est > min_v:
                del self.topk_map[min_k]
                self.topk_map[key] = est
        return est

def flush_pane_with_retry(sink_fn, payload: bytes, max_retries: int = 3) -> None:
    for attempt in range(max_retries):
        try:
            sink_fn(payload)
            return
        except OSError as exc:
            if attempt == max_retries - 1:
                raise RuntimeError(f'Pane flush failed: {exc}') from exc
            time.sleep((0.2 * (2 ** attempt)) + random.uniform(0, 0.1))
Pane Implementation

Kirsch-Mitzenmacher Hashes -> CMS + Top-K -> Retried Flush

blake2b (h1 + i*h2)Bounded Top-K MapBounded Flush RetryStoreEmit closed 1m pane

1.:

2.:

Caption: Using one 16-byte blake2b digest with Kirsch-Mitzenmacher probing updates the Count-Min table and bounded Top-K map in O(d + K) time.

06
Stage 6 • State Checkpointingadvanced

Fast RocksDB/S3 Checkpointing of 16 KB Sketches.

With exact HashSets, Flink checkpoints took minutes and timed out during pod restarts. With fixed-size sketches:

  • Sub-Second Checkpoints: Serializing 200 tenants x (4 KB HLL + 32 KB CMS) is < 8 MB total—snapshotting to S3 in <150 ms.
  • Exact-Once Replay: On pod crash, Flink restores the last 1-minute sketch checkpoint and replays Kafka offsets from the last barrier with zero OOM risk.
Failover Recovery

18 GB State Checkpoint vs <8 MB Sketch Checkpoint

18 GB Exact State<8 MB Sketch StateStateStore

1.:

2.:

Caption: Fixed-size sketch checkpoints shrink Flink/Kafka failover snapshots from gigabytes to under 8 MB, completing in <150 ms.

07
Stage 7 • Verificationadvanced

Validating Error Bounds, Memory Ceilings, and Skew Alerts.

Validate the pipeline continuously with three automated checks:

  • Shadow 1% Ground-Truth Audit: Route 1% of tenants to an offline batch exact COUNT(DISTINCT) job daily and assert abs(hll - exact) / exact < 0.025.
  • Pod RSS Ceiling: Assert worker RSS remains flat < 512 MB (under 15% of the 4 GB limit) across 50M+ unique keys.
  • Whale-Tenant Promotion Alert: Alert when any tenant crosses 10K/s to verify dedicated CMS isolation.
Post-Fix Telemetry

OOMKilled 137 vs <512 MB Steady State

Before (HashSet)After (HLL + CMS)StateStore

1.:

2.:

Caption: Daily 1% ground-truth audits and flat <512 MB RSS telemetry confirm <2% estimation error with zero OOMKilled crashes.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Tenant A sends 900K events/sec while Tenant B sends 100 events/sec into a single shared Count-Min Sketch. Why does Tenant B's frequency estimate become wildly inaccurate?

Recommended Learning Flow