Turn Telemetry Questions into Requirements
A real-time telemetry analyzer is the control room for a busy transport network. Individual signals—requests, errors, device readings, and latency measurements—arrive continuously. The analyzer cannot keep every signal in fast memory, yet it must answer operational questions quickly: How many events arrived in the last minute? How many services were active? Which keys dominate errors? Is p99 latency breaching its objective? Is the answer complete enough to alert on?
Suppose five events arrive with event-time seconds and latency milliseconds: (0, api, 40), (8, api, 60), (12, db, 90), (18, api, 50), (25, cache, 20). At event time 30, the half-open window [10,30) contains three events, three distinct keys, api as a joint top key, and sorted latencies [20,50,90]. The nearest-rank p50 is 50 ms. If the event at time 12 arrives after the watermark has passed 17 with five seconds of allowed lateness, the system must apply its documented late-data policy rather than quietly rewriting history.
An event time is when the source says the event occurred; processing time is when the analyzer handles it. A watermark is a claim that events earlier than a point are unlikely to arrive, not a clock and not proof of completeness. A window groups event times; a rate divides an accepted count by a stated duration. Cardinality counts distinct keys, heavy hitters identify high-frequency keys, and a quantile answers a rank question about a distribution. An alert is a policy decision over a versioned query result, not simply a red chart.
Stakeholders include application owners, SREs, platform engineers, security/privacy reviewers, finance teams, and incident commanders. Acceptance requires bounded state, deterministic replay, defined late and duplicate handling, stable versioned schemas, calibrated sketch error, query p99 below the service target, no cross-tenant leakage, recoverable checkpoints, and alerts whose evidence can be audited.
The analyzer is a bounded-memory measurement system over event-time windows, not an archive of raw truth. Every answer must state its window, watermark, algorithm, and guarantee before it can safely drive an alert.
| Term | Intuitive meaning | Exact example | Non-example | Assumption | Question answered |
|---|---|---|---|---|---|
| Event time | Time at the source | occurred_at=12.000Z | Consumer receipt time | Source clock quality is monitored | When did the event happen? |
| Watermark | Completeness frontier | watermark=17s with 5s lateness | Wall-clock “now” | Later events are handled by policy | Which windows may be finalized? |
| Window | Named event-time interval | Tumbling [10,20) | “Recent” with no duration | Boundary convention is fixed | Which events belong together? |
| Rate | Count divided by interval | 120 requests / 60 s = 2 rps | Current queue depth | Accepted-event semantics are defined | How fast are events occurring? |
| Cardinality | Number of unique keys | {api,db,cache} = 3 | Total event count 5 | Key normalization and hash are stable | How many distinct entities were active? |
| Heavy hitter | Key above a frequency criterion | api has 60% of errors | Largest observed latency | Positive updates and threshold are stated | Which keys dominate the stream? |
| Quantile | Value at a distribution rank | p50 of [20,50,90] is 50 | Arithmetic average 53.3 | Quantile convention is documented | What latency do most events stay below? |
| Alert | Policy over evidence | p99 > 500 ms for 3 closed windows | One unlabelled sample > 500 | Freshness and confidence gates pass | Should an operator act now? |
Turn Telemetry Questions into Requirements
Use events (0,api,40), (8,api,60), (12,db,90), (18,api,50), (25,cache,20) and the window [10,30). First cross out timestamps outside the half-open interval: 0 and 8. Count the remaining three events, form the key set {db,api,cache}, tally each key once, and sort latency as [20,50,90]. Expected results: rate 3/20 = 0.15 events/s, cardinality 3, a three-way frequency tie, and nearest-rank p50 50 ms. Now imagine (12,db,90) arrives after finalization. Reflection: should the result be revised, side-output for audit, or dropped—and what would each choice do to alert reproducibility?
Design the Ingestion, Window and Alert Architecture
The target workload is multi-tenant telemetry at 500,000 events per second, 5,000 active streams, 60-second tumbling and 5-minute sliding views, and queries below 100 ms p99. The event contract is {tenant_id, stream_id, event_id, event_time, key, value, attributes, schema_version}. The gateway authenticates, validates a 64 KiB size limit, redacts forbidden attributes, applies quotas, and writes to a replayable partition log. Partition workers use event time, a five-second allowed-lateness default, idempotent checkpoint epochs, and per-tenant memory budgets.
The ingestion path updates aligned bucketed counters, HLL registers for cardinality, a Space-Saving candidate summary backed by a Count-Min estimate for top keys, and KLL-style quantile summaries. Window queries merge only compatible bucket generations. Alert evaluation consumes query results only when watermark freshness, coverage, and error metadata satisfy policy. Operators change versioned configuration through a separate control plane. Snapshots record algorithm identifiers, dimensions, seed IDs, schema versions, bucket boundaries, watermark, checkpoint epoch, payload checksum, and encryption metadata.
The threat model includes malformed events, cardinality attacks, crafted hash collisions, replay duplication, clock skew, cross-tenant queries, snapshot tampering, poisoned alert rules, and compromised operator tokens. Privacy rules minimize raw attributes, hash or tokenize permitted keys, restrict drill-down, audit sensitive queries, and cap retention. The service explicitly excludes forensic raw-event search; durable object storage and a governed warehouse own that use case.
flowchart TD
P[Telemetry producers] --> G[Auth validate redact]
G --> L[Partitioned replay log]
L --> W[Event-time workers]
W --> C[Window counters]
W --> H[HLL cardinality]
W --> F[Heavy hitters]
W --> Q[Quantile sketches]
C --> A[Query and alert engine]
H --> A
F --> A
Q --> A
W --> S[Versioned snapshots]
A --> N[Dashboards and notifications]
O[Operators] --> R[Rules and rollout control]
R --> A
W --> M[Metrics traces audit]
classDef navy fill:#17365D,color:#fff,stroke:#102844;
classDef teal fill:#147D84,color:#fff,stroke:#0c5c61;
classDef crimson fill:#C6284D,color:#fff,stroke:#8e1935;
classDef purple fill:#6C3BAA,color:#fff,stroke:#482675;
class P,O navy;
class G,L,W,C teal;
class H,F,Q,S purple;
class A,N,R,M crimson;
| Candidate | Guarantee | Scale / latency | Memory | Operational burden | Privacy | Recovery | Decision |
|---|---|---|---|---|---|---|---|
| Raw events in RAM | Exact arbitrary queries | Degrades with volume | Unbounded | High eviction pressure | Highest exposure | Large checkpoints | Reject for hot-path state; retain governed log separately |
| Aligned time buckets | Exact accepted counts per bucket | O(1) update; merge buckets per query | O(keys × buckets) unless aggregated | Boundary and lateness logic | Aggregates reduce exposure | Replay current horizon | Select for rates and exact small-key counters |
| Exponential decay | Smooth recency weighting, no hard window | O(1) update | Small | Harder incident interpretation | Aggregate only | Snapshot scalar state | Use for trends, not contractual window alerts |
| HLL per bucket | Approximate distinct count | Constant update; fast register merge | Fixed registers × buckets | Precision/version compatibility | Hashed identity still sensitive | Register-wise max after validation | Select for cardinality |
| Exact top-key map | Exact frequencies | Slow/unbounded under cardinality attack | O(distinct keys) | Sharding and eviction | Retains key inventory | Heavy snapshots | Use only as oracle or bounded tenant tier |
| Space-Saving + CMS | Candidate recall plus bounded frequency estimates | Constant bounded work | Fixed counters/cells | Saturation and seed monitoring | Frequency inference risk | Compatible merge/replay rules required | Select for operational top keys |
| Exact sorted latency list | Exact quantiles | Query sort cost | O(events/window) | Simple only at low rate | Can reveal distributions | Large state | Keep as oracle |
| KLL-style summary | Probabilistic rank accuracy; mergeable | Fast amortized updates | Bounded by accuracy | Versioned compaction policy | Distribution leakage remains | Merge compatible levels | Select for latency quantiles |
The central invariant is that each accepted event affects exactly the documented windows and only tenant-compatible, version-compatible states may merge. Launch is blocked by silent late-data loss, cross-tenant access, unbounded state, unlabelled approximation, or alerting on stale/incomplete windows.
Integrate Summaries into a Live Analyzer
Build vertically. Slice 1 accepts a typed event, assigns it to fixed event-time buckets, and answers exact count/rate queries with an exact replay oracle. Slice 2 adds watermarking, allowed lateness, deduplication, checkpoint/restore, and finalization. Slice 3 adds HLL, top-key summaries, and quantile sketches behind a shared result envelope. Slice 4 evaluates alert rules only from results that pass freshness and quality gates. Each slice has its own demo, memory ceiling, and rollback boundary.
The stable contracts are ingest(event), advance_watermark(time), query(metric, start, end), snapshot(), and restore(bytes). Configuration validates window alignment, lateness, bucket count, sketch dimensions, tenant budget, and seed identity before allocation. Snapshot format includes a checksum and an explicit version; adjacent migrations are named and tested, while unsupported versions trigger replay or a visible STATE_INCOMPATIBLE condition. Safe fallback may serve a labeled stale result, reduce optional dimensions, or reject work—never fabricate completeness.
flowchart TD
C[Typed event contract] --> E[Exact bucket baseline]
E --> W[Watermark and lateness]
W --> S[Checkpoint and replay]
S --> H[HLL and heavy hitters]
H --> Q[Quantile summaries]
Q --> A[Alert quality gate]
A --> K[Shadow canary]
K -->|SLO and oracle pass| P[Progressive promotion]
K -->|Drift or invariant fail| R[Rollback generation]
R --> E
classDef navy fill:#17365D,color:#fff,stroke:#102844;
classDef teal fill:#147D84,color:#fff,stroke:#0c5c61;
classDef crimson fill:#C6284D,color:#fff,stroke:#8e1935;
classDef purple fill:#6C3BAA,color:#fff,stroke:#482675;
class C,E navy;
class W,S,H,Q teal;
class A,K purple;
class P,R crimson;
Integrate Summaries into a Live Analyzer: Real-Time Telemetry Analyzer
Create contracts.py, windows.py, summaries.py, alerts.py, and test_replay.py. Replay the five-event trace; checkpoint 1 passes when [10,30) yields count 3, rate 0.15/s, cardinality 3, a three-way key tie, and p50 50 ms. Advance the watermark to 35; checkpoint 2 passes when the window is complete, a duplicate ID is ignored, and an event at time 20 arriving then is classified too_late. Add sketches and compare them with exact set, map, and sorted-array oracles over 30 fixed seeds. Split the replay by partition, merge compatible summaries, and compare with a single pass. Corrupt a checkpoint, change one seed, regress the watermark, and exceed the key budget; each must fail before state mutation. Done means one command proves normal results, deterministic replay, bounded state, compatible merge, late-data behavior, alert gating, and all four rejection paths.
Replay Incidents and Prove Operational Readiness
Verification separates algorithm error from pipeline error. Unit tests cover boundary assignment, watermark monotonicity, parameter calculators, serialization, and rule evaluation. Property tests generate streams to assert that accepted events land in exactly the documented windows, finalized windows do not change, HLL error is calibrated, heavy-hitter candidates satisfy the configured threshold contract, and observed quantile rank error stays within its stated envelope. Differential replay compares every approximate result with exact sets, maps, and sorted arrays.
The approachable scenario is the five-event trace plus one duplicate and one late arrival. The professional workload is 500,000 events/s across 5,000 streams, 60-second and 5-minute windows, Zipf-skewed keys, bimodal latency, and 5% out-of-order delivery. SLOs are 99.9% query availability, p99 under 100 ms, ingestion acceptance above 99.99% for valid in-quota events, alert evaluation within 10 seconds of window finalization, memory below 4 GiB per worker, and recovery below 10 minutes. The cost budget is tracked per million events and per active stream.
Failure injection kills workers during checkpoints, delays one partition, corrupts snapshot bytes, removes a notification sink, rotates a hash seed incorrectly, advances a source clock by two minutes, and floods unique keys. Metrics expose ingest lag, watermark delay, late/duplicate/rejected counts, state bytes, sketch saturation, estimate/oracle deltas, checkpoint age, alert suppression reason, and notification failures. Traces connect ingest, bucket update, query, rule, and notification. Audit logs preserve configuration, access, alert evidence, acknowledgement, rollback, and owner.
| Requirement / guarantee | Oracle | Workload | Metric and threshold | Failure injection | Evidence | Owner |
|---|---|---|---|---|---|---|
| Correct window membership | Exact interval filter | Boundaries, disorder, duplicates | Zero membership mismatch | Clock skew and delayed partition | Seeded replay diff | Correctness lead |
| Finalization obeys lateness policy | Retained raw replay | 5% late traffic | Zero post-finalization mutation; classified late events | Pause partition past watermark | Watermark timeline and late-event audit | Stream owner |
| HLL cardinality is calibrated | Exact set | Uniform and Zipf keys over 30 seeds | RMSE within documented envelope; regression <10% | Precision/seed mismatch | Accuracy report and seed manifest | Algorithms reviewer |
| Heavy hitters meet threshold contract | Exact frequency map | Hot keys plus adversarial cardinality | Required recall at φ; frequency error within bound | Unique-key flood and saturation | Candidate recall report | Backend owner |
| Quantile rank error is bounded | Sorted exact values | Bimodal and heavy-tail latency | Observed rank error within configured envelope | Compaction and checkpoint interruption | Rank-error plots | Backend owner |
| Query SLO | Load generator clock | 500k events/s, 5k streams | p99 <100 ms; availability ≥99.9% | One slow partition | Dashboard and trace exemplars | SRE |
| Alerts are timely and defensible | Rule oracle | Breach and recovery sequences | Evaluate ≤10 s after finalization; 0 stale alerts | Notification outage, stale watermark | Alert evidence payload and audit trail | Incident commander |
| Memory remains bounded | Allocator telemetry | Cardinality ramp to quota | State <4 GiB/worker; reject before overrun | Malicious high-cardinality tenant | Heap profile and quota audit | Platform lead |
| Recovery is safe | Snapshot checksum + replay hash | Worker loss during checkpoint | RTO <10 min; no incompatible restore | Kill worker and corrupt snapshot | Recovery timeline and hashes | SRE |
| Tenant and privacy isolation | Authorization oracle | Cross-tenant query/sensitive attributes | Zero unauthorized results; all sensitive access audited | Forged tenant token | Security test and audit export | Security owner |
Replay Incidents and Prove Operational Readiness: Real-Time Telemetry Analyzer
Run a 35-minute trial: 10 minutes at 250k events/s, 15 at 500k, and 10 at 650k, with 5,000 streams, Zipf keys, bimodal latency, and 5% events delayed by up to eight seconds. Require query p99 below 100 ms at target load, valid-event acceptance above 99.99%, alert evaluation within 10 seconds of finalization, memory below 4 GiB, and sketch/oracle metrics inside their envelopes. At minute 12 pause one partition for 30 seconds; expect watermark-delay and alert-suppression signals. At minute 20 kill a worker during checkpoint; expect recovery under 10 minutes. At minute 27 corrupt a snapshot and rotate one seed; expect quarantine and no incompatible merge. Roll back on any isolation/invariant failure, memory above 90%, p99 above 150 ms for five minutes, or recovery breach. Record GO, CONDITIONAL GO, or NO-GO with dashboard captures, replay hashes, cost per million events, owners, and expiry dates for conditions.
Ship the Analyzer with a Runbook
The release bundle includes the API and event schemas, window/lateness semantics, result-envelope examples, configuration calculators, a pinned environment, seeded replay datasets, benchmark commands and raw outputs, the correctness dossier, migration matrix, security/privacy review, dashboards, alert rules, and an operational runbook. Each artifact names its version, owner, generation command, and review date.
The runbook starts from symptoms—watermark delay, ingest rejection, state growth, oracle drift, stale checkpoints, notification failure—and gives diagnostic queries, decision thresholds, safe mitigations, escalation paths, rollback commands, and evidence-preservation steps. It distinguishes late source data from pipeline lag and true service degradation. The demonstration ingests the five-event trace, shows a complete result envelope, introduces a duplicate and late event, compares approximate summaries with exact oracles, blocks a stale alert, rejects incompatible state, restores a valid checkpoint, and ends on the professional workload dashboard.
Peer reviewers ask: Are half-open boundaries and finalization unambiguous? Can event-time and processing-time failures be distinguished? Do sketch guarantees survive bucket merge? Can a caller tell error, staleness, and partial coverage apart? Does high cardinality degrade safely? Are sampled attributes and key identities protected? Handoff requires a tagged build, checksums, one-command verification, benchmark provenance, signed dossier, rehearsed recovery/rollback, on-call ownership, and no undocumented exception.
Ship the Analyzer with a Runbook: Real-Time Telemetry Analyzer
Final checklist: (1) build from a clean checkout; (2) run unit, property, replay, load, security, and fault suites; (3) publish schemas and window semantics; (4) attach calculator proofs and sketch calibration; (5) archive datasets, seeds, environment lock, commands, and raw benchmarks; (6) sign the correctness and privacy dossiers; (7) rehearse checkpoint recovery, notification failure, and rollback; (8) confirm dashboard, alert, and on-call ownership. Demo the five-event window, duplicate suppression, late-event side output, exact-versus-sketch comparison, freshness-gated alert, corrupt-snapshot rejection, and load-test dashboard. Score 0–2 for correctness, contract clarity, reproducibility, bounded resources, observability, recovery, security/privacy, and documentation; require at least 14/16 and no zero. Stretch goals: adaptive precision, privacy-budgeted aggregates, cross-region federation, and exemplar links. Milestones: production calibration, adaptive per-tenant budgets, then privacy-preserving alert evidence.
Launch only when window semantics, sketch calibration, resource bounds, alert freshness gates, privacy controls, and recovery are proven and owned. Known risks include source clock error, hash assumptions, cardinality attacks, distribution shift, and telemetry becoming surveillance; ask which failure could still look like a real incident, then make production calibration against shadow exact oracles the next milestone.