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.
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).
50M Keys x 60 Sliding Panes -> 18 GB OOMKilled
1.:
2.:
Caption: Storing exact HashSets across 60 overlapping 1-minute panes multiplies RAM past 18 GB per pod, triggering OOMKilled (exit 137).
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(maxfor HLL,sumfor CMS) to answer the 1-hour sliding query.
1 Active Pane/Worker -> 60-Slot Ring Buffer -> 1h Query
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.
Exact RAM & Error Budgeting Across 200 Tenants.
Size each sketch explicitly before deployment:
- HyperLogLog (
p=12per tenant, orp=14for top tenants):p=12uses 4 KB (+-1.6%error);200 tenants * 4 KB = 800 KBper worker! - Count-Min Sketch (
d=4, w=2,048x 4B ints):32 KBper tenant (200 * 32 KB = 6.4 MBper worker; or 1 shared global CMS keyed by(tenant_id, endpoint)using 256 KB total). - Top-100 Min-Heap:
100 * 128B ≈ 13 KBper tenant (2.6 MBtotal).
Per-Tenant Sketch Footprint vs Shared CMS
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.
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 exactdictuntil cardinality > 1,000). - Exact-to-Sketch Promotion: Start new/small tenants in a tiny 1,000-entry
dictand promote to HLL+CMS only whenlen > 1,000.
Shared CMS Pollution vs Whale-Isolated Sketches
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.
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))Kirsch-Mitzenmacher Hashes -> CMS + Top-K -> Retried Flush
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.
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 MBtotal—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.
18 GB State Checkpoint vs <8 MB Sketch Checkpoint
1.:
2.:
Caption: Fixed-size sketch checkpoints shrink Flink/Kafka failover snapshots from gigabytes to under 8 MB, completing in <150 ms.
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 assertabs(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/sto verify dedicated CMS isolation.
OOMKilled 137 vs <512 MB Steady State
1.:
2.:
Caption: Daily 1% ground-truth audits and flat <512 MB RSS telemetry confirm <2% estimation error with zero OOMKilled crashes.
Practice: Make the trade-off yourself.
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?