ELLMEngineering Large
Language Models
Download PDF

Chapter 53

Building a Streaming Telemetry Service

On this page

This chapter assembles the preceding summaries into a telemetry service, adding event identity, expiration, partitioning, recovery, and versioned output.

Choosing the correct summary

Query Representative state Error contract Merge operation
Immutable record top-k Size-k min-heap Exact with total order Top-k of local candidates
Insertion-only heavy hitters Misra-Gries Deterministic additive count bound Merge and reduce counters carefully
Point frequency Count-Min Sketch One-sided additive, probabilistic Elementwise counter addition
Distinct count HyperLogLog Approximate relative error Registerwise maximum
Membership Bloom filter False positives, no false negatives under valid use Bitwise OR
Quantile GK, KLL, or other quantile summary Rank error Algorithm-specific merge
Mean and variance (n, mean, M2) Floating-point numerical error Parallel variance formula
Uniform sample Random priorities or reservoir Exact inclusion probability under model Global priority top-k

A complete event-time heavy-hitter design

A streaming service carries event identity, key ownership, window state, and output versions across distinct boundaries. Split-key counts must be merged before ranking. Recovery binds the summary state to consumed offsets; late data follows a declared correction policy.
Open full diagram ↗

A streaming service carries event identity, key ownership, window state, and output versions across distinct boundaries. Split-key counts must be merged before ranking. Recovery binds the summary state to consumed offsets; late data follows a declared correction policy.

Consider a service that reports the top k error signatures per tenant for each five-minute event-time window. Traffic peaks at millions of events per second, events can arrive 20 minutes late, and results should update quickly.

This is a hypothetical workload for design, not a measured deployment. The cumulative exercises at the end of this chapter review all four streaming chapters.

1. Identity and ingestion

Each event carries event_id, tenant, event timestamp, signature, source partition, and source offset. Canonicalize the signature before partitioning. Deduplicate by stable event_id within the required replay horizon, or make the source and sink exactly-once enough that duplicate effects are bounded and documented.

Partition first by tenant and then by a stable subshard to distribute hot tenants. A signature must map deterministically so its partial count can be merged. If salting splits one signature across workers, the second stage must sum its partials before final ranking.

Partitioning by signature avoids split counts but sends an extremely hot signature to one worker. Salting by (signature, event_id) distributes its updates, at the cost of a second keyed aggregation that recombines all salts for that signature. Use measured skew to enable salting only for hot keys; salting every key multiplies shuffle and intermediate state.

2. Window state

Assign each event to a half-open interval [start, start + 5 minutes). On every worker and window, maintain:

  • a Count-Min Sketch for approximate frequency queries;
  • a Misra-Gries table with capacity r for deterministic candidate recall;
  • total accepted mass F_1;
  • estimator parameters and hash seed;
  • revision and source progress metadata.

If the distinct-key count is affordable, exact keyed counts are simpler and may be the right answer. Approximation is justified only by a quantified state or throughput constraint.

The candidate contract is explicit: every signature with frequency greater than F_1/(r+1) is present. To guarantee recall of all true top-k keys, the design must establish that the kth frequency exceeds this threshold, increase r, or use an exact fallback. Count-Min accuracy cannot repair a key that the candidate stage omitted.

3. Watermark and triggers

Derive per-source watermarks from source progress and observed delay, then take the minimum across non-idle inputs. Emit:

  • early speculative panes every 30 seconds of processing time;
  • an on-time pane when the watermark passes the window end;
  • late correction panes after accepted late arrivals;
  • a final pane when the watermark passes window_end + 20 minutes.

Do not describe the on-time pane as complete. It is complete only relative to the watermark model. Records after allowed lateness go to a durable late-data stream with counts and alerts, not silent deletion.

For example, suppose the on-time result is A:100, B:90. A late batch contributes 20 occurrences of B, so revision two must atomically replace the order with B:110, A:100. Appending a second unversioned list would leave consumers unable to determine which result is current.

4. Merge and ranking

Workers emit compatible sketch state plus candidates. The reducer adds Count-Min counters, merges Misra-Gries maps with the reduce-and-prune rule, queries merged frequency estimates, and emits the best k with:

  • estimated count;
  • interval [max(0, f_hat - epsilon F_1), f_hat] and failure parameter delta;
  • window and revision;
  • pane timing class: early, on-time, late, or final;
  • completeness and dropped-event metrics.

Allocate the failure budget over the complete candidate set before sorting by Count-Min estimates. Misra-Gries candidates are selected independently of Count-Min's hashes, so an upper bound of Q queried candidates permits delta = eta/Q. Allocating only across the displayed winners would ignore their selection by noisy estimates. If ranking intervals overlap, emit "order uncertain" or verify exact counts from retained/durable data. A numerical sort of estimates is not a proof of exact order.

5. Sink and correction semantics

Upsert the complete ranked list by (tenant, window_start). Downstream consumers must not merge lists from different revisions. Include estimator schema, source frontier and completeness in the output identity: identical revision numbers cannot make different payloads equivalent.

Checkpoint operator state together with source offsets or use a framework snapshot that provides the equivalent barrier. At a checkpoint barrier, each operator snapshot must represent exactly the input prefix named by the saved offsets; in-flight records belong either to the snapshot/channel state or to the replay suffix, not neither and not both. When supported, commit sink writes transactionally with that checkpoint.

For a nontransactional sink, persist a monotonically increasing writer epoch separately from the worker checkpoint. Recovery acquires a new epoch and fences the old writer at the sink. The sink retains its last published result and source frontier while the replacement replays. A new epoch alone must not let a partially reconstructed pane overwrite that result: publish only after reaching the durable frontier, and preserve its completeness. With multiple source partitions, the frontier is a vector of offsets and replay must reconstruct through every required component; a maximum scalar offset cannot represent that state.

Within an epoch, use increasing revisions. Bind (tenant, window, epoch, revision) to the exact payload, source frontier and completeness; replay returns the original receipt, while equal identity with different content is a conflict. Compare (epoch, revision) only after checking the active writer and catch-up condition. Reject earlier epochs even if their local revision is larger. A final pane cannot be downgraded to early by recovery. Event-ID deduplication is still needed if upstream redelivery crosses the source consistency boundary.

Consider a sink holding early revision 3 at source offset 3, while the checkpoint contains revision 1 at offset 1. Replay may run faster and emit only final revision 2, because processing-time early triggers do not repeat at the same source positions. A revision-only sink rejects that final pane forever. In the repaired protocol, the new epoch first catches up through offset 3, then publishes final revision 2 under its new identity. The previous result remains visible during catch-up; a late old writer is fenced.

examples/telemetry_sink.py executes this boundary with SQLite transactions, persistent epochs and receipts, and a single-source insertion-only count. Tests reopen the sink, reject a catch-up pane behind its durable frontier, publish the reconstructed final pane, reject equal-key/different-payload replay and divergent counts at an equal frontier, fence a second connection's old writer, and reject an insertion-only count decrease. Offsets, counts and finality still come from a trusted worker: the sink cannot prove correct source replay or a valid watermark from those fields alone. This is a sink protocol reference, not a full streaming engine, authenticated lease service or power-loss experiment. Multiple sources, estimator migration and event-time reconstruction require their corresponding state and acceptance tests.

6. Capacity and failure policy

Estimate active windows as approximately:

active_windows ~= ceil((window_width + allowed_lateness + watermark_lag) / window_slide),

allowing another boundary window depending on trigger timing. Here watermark lag is the nonnegative gap between the newest accepted event time and the watermark; allowed lateness is the separate retention period after the watermark passes a window's end. Multiply by tenants, subshards, sketch bytes, candidate bytes, deduplication state, and checkpoint copies. A stalled watermark can increase retained windows beyond the nominal estimate, so alert on oldest open window and state bytes.

The arithmetic can reject a design before implementation. Five-minute tumbling windows with 20 minutes of allowed lateness retain about five windows in steady state. If there are 50,000 active tenant-subshard pairs and each window uses the earlier 297.4 KiB Count-Min configuration, dense sketch tables alone require:

50,000 * 5 * 304,528 bytes ~= 70.9 GiB.

Candidates, hash metadata, deduplication, object overhead, snapshots, and watermark stalls add more. That budget suggests tiering: use exact sparse maps for low-volume tenants, allocate dense sketches only after a threshold, reduce unnecessary subshards, choose epsilon from a business-relevant count gap, and evict finalized state. Parameters belong in the capacity model, not only in a correctness proof.

Under backpressure, silently dropping events biases frequency and can change ranking. Prefer source throttling and durable buffering. If controlled sampling is allowed, attach inclusion probabilities and use an estimator designed for weighted observations; do not feed sampled counts into an ordinary sketch and report them as exact.

Define a hard failure policy for a watermark that never advances. Options include marking a demonstrably idle source, quarantining a damaged partition, or capping retention and marking affected windows incomplete. Any cap changes the completeness contract and must surface in output metadata and alerts.

Trace contracts for a generative service

Instrument the request, retrieval, generation, tool attempts, and outcome verification as related operations. Preserve a logical task ID across retries while giving each attempt its own identity. A retry should increase attempt cost without inventing another user request. For asynchronous work, retain causal links when a single parent-child span tree no longer describes execution.

This schema needs versioning. OpenTelemetry semantic conventions v1.42.0 moved GenAI conventions to a dedicated repository; the old repository's GenAI definitions were deprecated. As checked September 24, 2026, integrations should pin the applicable conventions and schema URL, not assume that an old attribute spelling remains the current contract.

Record model and application versions, operation type, outcome, token-accounting semantics, cache use, and phase durations. Distinguish time to first response chunk from time to first useful text token: a protocol event or reasoning-only chunk may arrive first. Likewise, do not add reasoning tokens to output totals when the provider already includes them. Missing usage is unknown, not zero. Keep task IDs and document IDs in traces with suitable access controls, not unbounded metric labels. Raw prompts and tool outputs require a separate retention and disclosure policy.

The Kafka Streams processing contract can couple consumed offsets, state changes, and output records within its transaction boundary. An HTTP notification or remote model call is outside that boundary. For such effects, write an outbox intent with the committed state, dispatch using a stable operation key, and reconcile the receiver's receipt. Delivery may repeat; the externally visible effect must tolerate that repetition.

Worked check: a tool times out, then returns its existing receipt on retry. Count one logical effect and two attempts, and include both attempts in latency and cost. A dashboard that counts only successful spans hides the recovery overhead.

Production readiness checklist

Before shipping a streaming summary, verify:

  • semantics: query, window, update model, ordering, ties, and finalization;
  • accuracy: bound, probability, target population, and adversarial assumptions;
  • numerics: counter overflow, accumulator dtype, NaN, infinity, and hash width;
  • distribution: partition rule, merge compatibility, duplicate handling, and skew;
  • state: bytes per key/window, expiration, compaction, and schema version;
  • recovery: snapshot-to-offset consistency, replay determinism, and idempotent sink;
  • operations: watermark lag, state growth, false-positive or error calibration, and hot keys;
  • degradation: backpressure behavior, sampling policy, and visible completeness metadata.

Design Exercises

  1. Implement exact top-k for immutable records, prove the heap invariant, and prove the exact distributed merge. Give a counterexample for merging local frequency top-k.
  2. Derive both exact sliding maximum with a monotonic deque and approximate sliding one-counts with an exponential histogram. State their ordering assumptions and complexity.
  3. Derive Welford's online variance update, weighted update, removal formula, and parallel merge. Then merge [4,7] with [13,16], accidentally deliver the first partition twice, and quantify the resulting count and mean. Which identity check prevents that error?
  4. Prove Algorithm R reservoir sampling is uniform. Then derive exact distributed uniform and weighted-without-replacement samples.
  5. Derive Misra-Gries candidate and error guarantees, show how two states merge, and contrast its bounds with Space-Saving.
  6. Derive the Count-Min Sketch point-frequency bound, then resize the chapter's width-2,719 sketch for 200 independently selected candidate queries with total failure budget 10^-6. Calculate the changed bytes per window and explain why sizing for only ten displayed winners is insufficient.
  7. Derive the HyperLogLog update, estimator intuition, error-versus-memory tradeoff, union merge, and limitations for deletion and intersection.
  8. Derive Bloom-filter false-positive probability, optimal hash count, and memory formula. Then construct a counting-filter false negative caused by deleting a key that was never inserted. Why does a positive membership answer not authorize deletion?
  9. Explain KLL compaction from first principles, including its rank-error mechanism, query, merge, and the difference between rank and value error.
  10. Keep the service's five-minute windows, 20-minute allowed lateness, 50,000 tenant-subshard pairs, and 304,528-byte sketches. Watermark lag grows to eight minutes, but retention is capped at six windows. Using the chapter's nominal window-count model, calculate the state requirement and explain the capacity, completeness, and recovery decision.

Worked Solutions

1. Exact record top-k

Maintain a min-heap ordered by (score, stable_id) with at most k records. The invariant after a prefix of length i is that the heap contains the best min(i, k) prefix records and its root is the worst retained record. If the heap is not full, insert. If it is full, a new record no better than the root has at least k records ahead of it and cannot qualify; a better record replaces exactly the old boundary item. That proves the update by induction.

The implementation is:

Example status: Illustrative Python excerpt; not standalone.

from heapq import heappush, heapreplace

def top_k(records, k):
    if k < 0:
        raise ValueError("k must be nonnegative")
    if k == 0:
        return []
    heap = []
    for record in records:
        entry = (record.score, record.stable_id, record)
        if len(heap) < k:
            heappush(heap, entry)
        elif entry > heap[0]:
            heapreplace(heap, entry)
    return [x[2] for x in sorted(heap, reverse=True)]

This excerpt assumes finite scores and unique, comparable stable IDs. Reject or canonicalize non-finite scores before calling it. The worst-case update cost is O(log k) for k >= 2, scan time is O(n log k), state is O(k), and sorted materialization is O(k log k); k = 1 is a linear scan. Also state whether the API returns exactly k records or all score ties at the boundary.

For disjoint immutable shards S_j, each shard emits T_k(S_j). Any record omitted locally has at least k same-shard records above it and therefore cannot rank globally. Thus the coordinator or reduction tree computes T_k over at most p k candidates exactly. Communication is O(p k) records for a flat gather.

The proof depends on each immutable record having one owner and one final score. It is false for keys whose frequency is split. With k = 1, shard one has A:6, X:5, and shard two has B:6, X:5. Local winners contain only A and B, but global X:10 is the true winner. Partial counts must first be aggregated by key or represented by a mergeable frequency summary. Replication also requires deduplication, and mutable scores or deletion require retained full state because a size-k heap has forgotten the next replacement.

2. Exact and approximate sliding windows

For a count window of width w, store candidate indices in increasing index order and decreasing value order. First remove front indices <= i - w because they expired. Then remove back indices whose values are <= x_i. Each removed value is dominated by the new value: the new one is at least as large and expires later, so the old one can never again be a maximum. Append i; the front is the maximum live candidate.

An individual update can remove O(w) entries, but each index is appended once and removed at most once from either end. Across n inputs there are O(n) deque operations, so amortized update time is O(1) and state is O(w).

For counts of one-bits over the last W positions, an exponential histogram stores power-of-two buckets and the timestamp of each bucket's newest one. In the conservative variant above, choose b = ceil(1/epsilon) + 1, allow at most b buckets per size, and merge the two oldest when a size overflows. Return zero for no buckets and the exact sum when the oldest has size one. Otherwise sum all bucket sizes but only half of the oldest:

count_hat = sum(bucket sizes) - oldest_size/2.

Only the oldest bucket can straddle the boundary, so absolute error is at most half its size C/2. When this bucket was formed, at least b-1 newer buckets of size C/2 remained; their mass cannot expire first. Consequently:

(C/2)/(1 + newer represented ones) <= 1/(b-1) <= epsilon,

which converts this to relative error against the true live count. It stores O((1/epsilon) log W) buckets, uses O((1/epsilon) log^2 W) bits with timestamps modulo a suitable multiple of W, and has amortized O(1) update work despite occasional merge cascades when the oldest buckets of each size are directly accessible.

Both algorithms assume an arrival-order count window. A late event belongs in the middle of event-time order and may revise an emitted answer. A reorder buffer, watermark, allowed-lateness policy, and revision protocol are separate system responsibilities.

3. Online, weighted, removable, and parallel variance

Store (n, mu, M2) where M2 = sum_i (x_i - mu)^2. For a new x, set n' = n + 1 and delta = x - mu. Expanding the mean gives mu' = mu + delta/n'. Let delta2 = x - mu'. Re-centering the old observations makes cross terms vanish because their deviations around mu sum to zero. Adding the new deviation yields M2' = M2 + delta * delta2.

Observed-population variance is M2/n; M2/(n-1) is unbiased for the generating variance for independent, identically distributed observations with finite variance and n >= 2. This avoids the dangerous subtraction in mean(x^2) - mean(x)^2, though adequate accumulator precision and non-finite input policy are still required.

For a positive frequency weight w, replace count by total weight W. With delta = x - mu:

W' = W + w,

mu' = mu + (w/W') delta,

M2' = M2 + w delta (x - mu') = M2 + (Ww/W') delta^2.

If removing a previously included (x,w) and W > w:

mu' = (W mu - w x)/(W-w),

M2' = M2 - w(x-mu)(x-mu').

Removal is numerically more fragile than addition and requires exact knowledge that the observation was present. Frequency weights, reliability weights, and probability weights have different unbiased-variance denominators; do not automatically use W-1 outside replicated-observation frequency weights.

For disjoint states A and B, let delta = mu_B - mu_A and W = W_A + W_B. Re-centering both groups around the combined mean gives:

mu = mu_A + delta W_B/W,

M2 = M2_A + M2_B + delta^2 W_A W_B/W.

For unweighted observations, set W_A=n_A and W_B=n_B. The extra term is the between-partition sum of squares. Handle empty partitions explicitly, use a balanced merge tree for numerical quality, and ensure each record belongs to exactly one state.

For the changed exercise, the correct union has count four and mean ten. Delivering [4,7] twice produces count six and sum 51, hence mean 8.5. The variance-merge formula has correctly computed the wrong multiset; numerical stability cannot identify the duplicate. Bind each contribution to a partition and source-offset range, and deduplicate or replace its version before merging.

4. Uniform, distributed, and weighted sampling

Algorithm R stores the first k items. At one-based position i > k, it selects a uniform integer in [1, i] and replaces that reservoir slot if the integer is at most k. The new item enters with probability k/i.

Assume every earlier item is present after i-1 positions with probability k/(i-1). Conditional on being present, its particular slot is replaced with probability 1/i, so it survives with probability (i-1)/i. Its new inclusion probability is (k/(i-1))((i-1)/i) = k/i. The induction proves that every item has inclusion probability k/N at the end.

Naively combining equal-size shard reservoirs is biased if shard sizes differ. A robust distributed construction assigns each record an independent continuous priority, keeps the k smallest priorities locally, then keeps the k smallest globally. An item omitted locally already has k lower-priority same-shard items, so it cannot qualify globally. Independent continuous priorities produce the same exact uniform size-k subset as a global priority sample because ties occur with probability zero. A stable finite hash and deterministic tie-breaker make the result reproducible, but the construction is only approximately uniform when collisions are possible; use enough hash bits to make that bias negligible for the population and risk tolerance.

An alternative first draws shard sample counts from:

P(s_1,...,s_p) = product_j choose(n_j,s_j)/choose(N,k),

then takes a uniform size-s_j subset from each shard's uniform reservoir. This is exact but requires trustworthy shard sizes and coordinated hypergeometric allocation.

For positive weights and sequential probability proportional to remaining weight, draw independent U_i in (0,1], set:

priority_i = -ln(U_i)/w_i,

and keep the k smallest. These are independent exponential clocks of rates w_i; the chance clock i rings first is w_i/sum_j w_j, and memorylessness repeats the rule among remaining items. Local priority top-k then global priority top-k is exactly composable. Record the seed, priority/hash algorithm, canonical ID encoding, target population, and whether weights are supported; time decay and sampling with replacement require different laws.

5. Misra-Gries and Space-Saving

With capacity r, Misra-Gries increments a tracked key, inserts into a free slot, or otherwise decrements all r counters and discards zeros. Each decrement round cancels r+1 distinct occurrences: the arrival plus one from every tracked key. If there are g rounds, then g <= N/(r+1). For any tracked key:

c_hat(x) <= f(x) <= c_hat(x) + g.

An untracked key has f(x) <= g, so every key above N/(r+1) must be tracked. Moreover:

g = (N - sum_x c_hat(x))/(r+1).

To merge states A and B, add their maps keywise. If more than r keys remain, let C be the (r+1)th-largest combined counter, subtract C from every counter, and discard nonpositive values. Pruning lowers any estimate by at most C and removes at least (r+1)C total counter mass. Therefore the new budget:

Delta' = (N_A+N_B-sum c')/(r+1)

increases by at least C beyond the two input budgets and still covers every key's underestimate. This proves deterministic merge validity, though the merged table may differ from serial processing order.

Space-Saving replaces the minimum estimate c_min with a new key at estimate c_min+1 and stored error c_min. A tracked key then satisfies:

estimate-error <= f <= estimate,

and an untracked key is bounded by the current minimum. It often gives tighter practical candidates on skewed data, while Misra-Gries has the simpler cancellation merge. A Space-Saving table is not merged by adding local winners; use a proved error-aware variant. Either summary needs a second pass or separated intervals to certify exact order.

6. Count-Min Sketch and heavy hitters

In one row, the counter for x is f(x) plus nonnegative collision mass. Therefore every row and their minimum are at least f(x). With width w, pairwise-independent hashing makes expected collision noise at most F_1/w. Set w = ceil(e/epsilon); then expected noise is at most epsilon F_1/e. Markov's inequality bounds the chance that one row's noise exceeds epsilon F_1 by 1/e.

With d independent rows, the minimum is too large only if every row has excessive noise, with probability at most e^(-d). Choosing d = ceil(ln(1/delta)) gives f(x) <= f_hat(x) <= f(x) + epsilon F_1 with probability at least 1-delta for a fixed query.

For epsilon=0.001 and delta=10^(-6), choose w=2,719 and d=14: 38,066 counters or about 297.4 KiB at eight bytes each. At F_1=100,000,000, the allowance is 100,000 counts. This is additive, so it is meaningful only relative to the application's frequency scale.

For Q fixed queries with overall failure budget eta, allocate delta=eta/Q, so d=ceil(ln(Q/eta)); this follows from the union bound. Adaptive adversarial queries need separate analysis.

With 200 hash-independent candidates and eta=10^-6, per-query failure is 5*10^-9, and depth rises from 14 to ceil(ln(200/10^-6))=20. The same width needs 2719*20*8=435040 bytes, about 424.8 KiB per window rather than 297.4 KiB. Sizing for ten displayed winners is invalid because noisy estimates select those winners from all 200 candidates. The increased state is the cost of the stronger simultaneous claim.

The sketch does not store keys, so add Misra-Gries, Space-Saving, an external dictionary, or a replay pass for candidate discovery. Merge compatible standard sketches by elementwise addition, merge candidates with their proved rule, and query the merged sketch. Report f(x) in [max(0,f_hat-epsilon F_1), f_hat]. If intervals around the kth boundary overlap, the exact order is unresolved.

The guarantee assumes nonnegative current frequencies, no counter overflow, independent hash rows, secret or nonadversarial hashing as appropriate, and identical width, depth, seeds, encoding, counter type, and update rule across merged states. Standard linear updates also support valid strict-turnstile deletions. Arbitrary signed frequencies, duplicates relative to the intended population, and conservative-update variants require separate treatment.

7. HyperLogLog

Hash each canonical key uniformly. Use p prefix bits to choose one of m=2^p registers and let rho be one plus the leading-zero count in the remaining bits. Update M[j]=max(M[j],rho). Since P(rho>r)=2^(-r), a large maximum is evidence of many distinct hashes. The harmonic-mean estimator:

E = alpha_m m^2 / sum_j 2^(-M[j])

has normal-range relative standard error about 1.04/sqrt(m). With p=14, m=16,384, the RSE is about 0.8125% and byte registers occupy 16 KiB. If V registers are zero in the small range, linear counting uses m ln(m/V); production libraries also apply calibrated bias and large-range corrections.

Duplicate keys are idempotent because the same register maximum is repeated. Compatible states merge by registerwise maximum, exactly representing the register state of set union. Precision, hash seed/width, canonical encoding, and estimator version must match.

HLL does not estimate per-key frequency or membership. It cannot delete because a register does not retain the second-largest rho. Inclusion-exclusion for intersection subtracts three noisy estimates and is unstable for small intersections. Use per-window HLLs or a purpose-built set-expression sketch when those are core queries.

8. Bloom-filter sizing and validity

After h n uniform bit placements in m bits, a bit remains zero with probability (1 - 1/m)^(h n), approximately exp(-h n/m). A key not in the set becomes a false positive when all h queried positions are one, so:

p_fp ~= (1 - exp(-h n/m))^h.

Let a=m/n and y=exp(-h/a). Then:

d[ln p_fp]/dh = ln(1-y) + h y/(a(1-y)).

Setting y=1/2 and h=a ln 2 makes the derivative zero. Therefore:

h_opt = (m/n) ln 2,

p_min ~= exp(-(m/n)(ln 2)^2),

m ~= -n ln p/(ln 2)^2,

h ~= -ln p/ln 2.

For ten million distinct keys and p=0.001, this is about 143,775,876 bits, 17.1 MiB, and ten hash probes. Round h, then recompute p_fp and consider CPU cost. Double hashing can derive g_i=h_1+i h_2 mod m, provided the construction and modulus avoid short cycles.

"No false negatives" assumes append-only valid use, no lost or corrupted bits, identical encoding/seeds at insert and query, and correct concurrent writes. An ordinary filter cannot delete. A counting filter can decrement only if every insertion and deletion is balanced; deleting an absent key can clear shared counters and create false negatives. Overfilling raises false positives, so monitor bit occupancy and rotate or rebuild.

For the changed deletion case, use one hash and two different keys that share a counter. Insert A once: the counter is one. Never insert B, but observe that its membership query is a false positive. Decrementing for B sets the counter to zero and creates a false negative for A. A positive membership answer supplies no proof that the exact key was inserted. Authoritative multiplicity or balanced event receipts must authorize deletion.

9. KLL quantiles

KLL stores a hierarchy. A level-ell item has weight 2^ell. Items enter level zero. When a level exceeds capacity, sort it, flip a fair coin to retain odd or even positions, discard the rest, and promote survivors one level with doubled weight. For 2s compacted items, represented mass is preserved.

For any fixed threshold v, the compacted sorted prefix differs from its original represented rank by at most one level item, or 2^ell. The random parity makes this a conditionally zero-mean signed error. The level capacities limit high-weight compactions; concentration over their errors gives the probabilistic rank bound. Preserve an unpaired item at its current level when a buffer has odd length.

To query rank r, attach each retained item its level weight, sort all retained items by value, and return the value where cumulative weight reaches r. To merge compatible states, concatenate each level and compact overflows. Merge order can change retained samples but preserves the library's contract.

Rank error is not value error. With 500 zeros and 500 values equal to one billion, their occupied rank intervals are 1–500 and 501–1000. Both intersect the allowed range 490–510 around target rank 500; using only each value's inclusive upper rank would misstate this returned-quantile criterion. State whether the guarantee is pointwise or simultaneous, the failure probability, handling of duplicates and weights, and the exact quantile convention. KLL does not support arbitrary subtraction; sliding-window deletion needs pane decomposition, an expiration-aware sketch, or retained data.

10. A retention cap cannot advance a watermark

The nominal requirement becomes ceil((5 + 20 + 8) / 5) = 7 windows. Dense sketch tables alone need 50,000 * 7 * 304,528 / 2^30, about 99.3 GiB. Six windows consume about 85.1 GiB, leaving a 14.2 GiB shortfall before candidates, deduplication, snapshots, and object overhead. Trigger alignment can require another boundary window; this estimate is a planning floor under the stated model, not an exact peak allocation.

The seventh window still accepts legitimate corrections. Increase or tier capacity, or use declared backpressure and durable buffering while recovering source progress; buffering alone cannot free already retained state. If the hard cap forces eviction, mark the affected result incomplete and preserve the late-data/reconstruction policy. Memory pressure cannot justify labeling an unfinished window final.

Checkpoint completeness flags and output revisions with their source-offset boundary. Otherwise a restore can resurrect an evicted window as apparently complete, lose an accepted correction, or publish a stale revision. The changed workload therefore needs both a larger state budget and a tested degraded-result contract.

The telemetry track completes Part VI. Return to the earlier retrieval and agent cases to choose which measurements their acceptance decisions require, or continue to Part VII for recent mechanisms and adoption experiments. The separate classical ML companion is an optional refresher, not the next core chapter.

Further Study and Primary References