From Conveyor Belts to Frequency Vectors
Imagine a checkout conveyor: items pass once, and a clerk keeps a small tally rather than saving every receipt. A streaming algorithm has the same problem at machine speed. It sees a sequence of updates, keeps a limited state, and answers a specified question. Before choosing a compact tally, we must decide what counts as an update, whether corrections can arrive, and how wrong an answer may be.
Suppose the stream is $A, B, A, C, B, A$. The exact counts are A: 3, B: 2, C: 1. We can describe them as a frequency vector indexed by all possible items: for a universe $\{A,B,C,D\}$, it is $(3,2,1,0)$. The vector is a mathematical description of the stream, not a requirement to store four counters. When the universe has billions of possible keys, storing one counter per key may defeat the memory budget. A query might ask for A's count, the number of distinct items, or whether any item is unusually frequent; these are different contracts.
For the conveyor, an arrival adds one. In a payment ledger, a reversal might subtract one. For an incident dashboard, events can also expire from a recent time window. These differences determine which conclusions remain true. We will use basic vectors, sums, inequalities, and probability; no prior sketch design is needed. The motivating question is: what can a small state honestly promise about an enormous changing stream?
A stream is an ordered sequence of updates; its frequency vector is the accumulated result. A compact summary can answer a specified query approximately, but its guarantee depends on the update model, the error measure, and any randomness or adversary assumptions.
| Term | Intuition and exact example | Non-example or boundary | Question it answers |
|---|---|---|---|
| Stream | Ordered updates $(+A),(+B),(+A)$ | An unordered set loses repeated arrivals | What information arrives, and when? |
| Frequency vector | For universe $(A,B,C)$, $f=(2,1,0)$ | The raw log contains order as well as counts | What is the accumulated value of each key? |
| Universe | All permitted keys, such as $\{A,B,C\}$ | Observed keys alone need not include C | What coordinates could exist? |
| Summary | State retained after updates, perhaps fewer bytes than the exact vector | A saved copy of every event is not compact | What can we afford to remember? |
| Query | $f_A$ asks for A's count | “Understand the data” has no testable answer | Which function of the stream matters? |
| Guarantee | $\lvert\hat f_A-f_A\rvert\le\varepsilon N$ under stated assumptions | “Usually accurate” specifies neither error nor probability | How inaccurate may the result be? |
From Conveyor Belts to Frequency Vectors
Take universe $(A,B,C,D)$ and updates $(+A),(+B),(+A),(+C),(+B),(+A)$. Start at $(0,0,0,0)$. After the first three updates, check $(2,1,0,0)$; at the end check $(3,2,1,0)$, total arrivals $N=6$, distinct count $3$, and A's share $3/6$. If you store only $N$, can you recover the count of A? No: $A,A,B$ and $A,B,C$ both have $N=3$ but different A counts. What additional information does your chosen query demand?
Cash Registers, Turnstiles and Windows
Fix a universe of $U$ keys. Update $t$ is a pair $(i_t, \Delta_t)$; its frequency vector after $t$ updates is $f^{(t)}$, with $f_i^{(t)}=\sum_{s\le t,\;i_s=i}\Delta_s$. A cash-register stream has $\Delta_t \ge 0$, commonly $+1$. A turnstile stream permits negative changes. A strict-turnstile stream permits them but requires every coordinate $f_i^{(t)} \ge 0$ at every prefix. An ordinary, or general, turnstile stream need not satisfy that prefix condition. Example: $(+A,3), (-A,2)$ is strict; $(-A,1), (+A,2)$ reaches $-1$ and is general turnstile, although its final count is $1$. Some systems accept only integer updates; specifying the allowed update size matters as well.
A one-pass algorithm reads each update once in arrival order. Its state has at most $S$ bits; each update takes some time $T_u$ and each query some time $T_q$. The stream length $m$ counts updates, while $N=\sum_i f_i$ counts active items only when that sum is meaningful and nonnegative. With deletions, $m$ and $N$ can differ sharply; $\lVert f\rVert_1=\sum_i\lvert f_i\rvert$ is another possible scale. For $W$-event windows, retain only the most recent $W$ updates. For a time window, event timestamps, late arrivals, and the chosen clock become part of the definition. The window's vector is the sum of currently included updates, not necessarily the lifetime vector.
For a query value $q$, additive error $\varepsilon B$ means $\lvert\hat q-q\rvert\le\varepsilon B$ for a declared baseline $B$, such as $N$ or $\lVert f\rVert_1$. Multiplicative error $\varepsilon q$ means $\lvert\hat q-q\rvert\le\varepsilon\lvert q\rvert$ when that expression makes sense. At $q=0$, a purely relative guarantee requires exact zero. A randomized guarantee such as $\Pr_R[\lvert\hat q-q\rvert\le\varepsilon B]\ge1-\delta$ fixes the stream and query first and takes probability over algorithm randomness $R$. It does not automatically promise success for all possible queries at once or against an adversary that adapts to revealed randomness. In a distributed stream, we must also specify partitions, communication budget, merge rules, and whether updates are duplicated.
flowchart TD
U["Updates (key, change)"] --> C{"Negative changes?"}
C -->|No| A["Cash register"]
C -->|Yes| P{"Every prefix nonnegative?"}
P -->|Yes| S["Strict turnstile"]
P -->|No| G["General turnstile"]
U --> W["Window rule selects active updates"]
A --> F["Frequency vector"]
S --> F
G --> F
W --> F
F --> Q["Query and error scale"]
Q --> R["Claim needs memory, time, failure bounds"]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#147D84;
classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
class U,F navy; class A,S,W teal; class G,C,P crimson; class Q,R purple;
| Claim or model | Exact scope and assumption | Counterexample when changed | Consequence |
|---|---|---|---|
| Cash register | Every $\Delta \ge 0$; $N$ never decreases | A refund $-1$ breaks monotonicity | A monotone-count argument needs revision |
| Strict turnstile | Every prefix has $f_i\ge 0$ | Delete A before any A arrives | Final nonnegativity alone is insufficient |
| General turnstile | Signed intermediate counts allowed | Treat $\sum_i f_i$ as number of live objects while some counts are negative | Define an appropriate error scale |
| One pass | Each update read once; at most $S$ bits | Replaying an archive gives extra passes | State a separate pass budget |
| Additive $\varepsilon N$ | For fixed nonnegative $N$, absolute error at most $\varepsilon N$ | At $N=10^{6}$, error 1,000 may swamp true count 2 | Small counts may need another contract |
| Relative $\varepsilon q$ | For $q\ge 0$, error at most $\varepsilon q$ | At $q=0$, any nonzero estimate violates it | Zero handling must be explicit |
| Randomized fixed-query | For each fixed input and query, success probability at least $1-\delta$ over internal coins | Ask many queries and assume one shared success event | Bound simultaneous failure separately |
A theorem's quantifiers are part of its claim: “for every fixed permitted stream and query, with probability at least $1-\delta$ over fresh randomness, the error is at most $\varepsilon B$” is a pointwise guarantee. It alone says nothing about every query succeeding simultaneously or adaptive inputs chosen after observing answers.
Reading a Streaming Guarantee Without Fooling Yourself
Consider a nonnegative frequency vector with total mass $N=\sum_i f_i$. If an estimator promises $\lvert\hat f_i-f_i\rvert\le\varepsilon N$, then for $N=1,000$ and $\varepsilon =0.01$, its allowed error is 10. This is useful for a key with count 400 and weak for a key with count 3. Dividing by $N>0$ gives $\lvert\hat f_i/N-f_i/N\rvert\le\varepsilon$: the same bound is an additive guarantee on the key's share. It is not a 1% relative guarantee on every count. At $N=0$, that division is undefined; the contract needs a separate rule.
Suppose a fixed query fails with probability at most $\delta$. If a fixed collection of $k$ queries is asked using the same randomized state, let $E_j$ be failure of query $j$. The union bound gives $\Pr(\text{at least one failure})\le\sum_j\Pr(E_j)\le k\delta$; independence is unnecessary. To guarantee that all 100 predetermined queries succeed with probability at least 0.99 by this argument, make each query's failure bound at most $0.01/100=0.0001$. This is a sufficient parameter choice, not proof that the failures really add up or that this memory cost is necessary. An adaptively selected query requires a theorem that explicitly covers adaptive choice; the fixed-query derivation cannot be reused without justification.
Memory claims also need units. An exact count in ${0,\ldots,m}$ requires at least $\lceil\log_2(m+1)\rceil$ bits of representation for that count, while a full exact vector of $U$ such bounded counters can be stored using $U\lceil\log_2(m+1)\rceil$ bits. The latter is an upper bound, not a universal lower bound: constraints on the vector or the supported query might allow smaller state. A claim of $O(\varepsilon^{-2}\log(1/\delta))$ counters is incomplete until counter widths, hash seeds, the universe encoding, and per-update work are included.
flowchart TD
P["Premise: fixed stream, fixed query"] --> E["Each failure event has probability ≤ δ"]
E --> C{"How many queries?"}
C -->|One| O["Success probability ≥ 1−δ"]
C -->|k fixed queries| U["Union bound: any failure ≤ kδ"]
C -->|Chosen from answers| X["Stop: adaptive theorem needed"]
U --> T["Choose δ ≤ target failure / k"]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#147D84;
classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
class P,E navy; class O,U,T teal; class X crimson; class C purple;
Reading a Streaming Guarantee Without Fooling Yourself
Given: $f=(400,3,597)$, $N=1,000$, $\varepsilon =0.01$. First compute $\varepsilon N=10$. For the second key, an estimate of 8 has absolute error 5, so it satisfies the additive contract. Its relative error is $5/3$, about 167%, so it does not satisfy a 1% relative contract. Checkpoint: dividing the count error by $N$ gives $0.005\le 0.01$. Now plan 20 predetermined queries with overall failure at most 0.02: choose per-query $\delta \le 0.001$ by the union bound. Variation: suppose a refund makes $f=(400,-3,597)$ while you still call $\sum f_i=994$ the number of live items. That interpretation fails because a coordinate is negative; specify the general-turnstile model and an error scale before transferring the original conclusion.
| Reasoning tool | What it establishes | Assumption and tightness | Failure case |
|---|---|---|---|
| Normalize by $N$ | Additive $\varepsilon N$ count error implies $\varepsilon$ share error | $N>0$, fixed common denominator; says nothing about relative error per key | $f_i=3$, $N=1000$, allowed error 10 |
| Union bound | For $k$ fixed queries, any failure at most $k\delta$ | No independence needed; bound can be loose | Adaptive selection lacks the fixed-query premise |
| Prefix invariant | Nonnegative counts after every strict-turnstile update | Must hold at every prefix, not merely at end | Delete before insert, then restore |
| Bit accounting | $m+1$ possible values require $\lceil\log_2(m+1)\rceil$ bits for one exact count | Assumes a count can take all those values; not a bound for every query | Reporting “10 counters” without counter widths |
Telemetry, Payments and Incident Windows
Approachable telemetry. A school counts library visits by room: $(+A),(+B),(+A),(+C),(+B),(+A)$ is cash register, with $f=(3,2,1)$ and six visits. If a mistaken scan is later canceled, model it as a negative update; whether the stream remains strict turnstile depends on the count at the cancellation prefix. If instead the dashboard asks for visits in the most recent four events, the active suffix is $A,C,B,A$, yielding $(2,1,1)$. A lifetime tally cannot answer that window query without additional information.
Production payments. Imagine 50,000 authorization events per second, a 24-hour retention horizon, one pass at ingestion, and 256 MiB of worker memory. A charge and a reversal must be keyed by the same intended entity; retries and duplicate delivery need a deduplication policy before frequencies mean “transactions.” A strict-turnstile assumption is defensible only if reversals always follow recorded charges in the order the worker sees. Late reversals and cross-region reordering can invalidate it. An approximate count used to prioritize investigation may tolerate an explicit additive bound and failure probability; a settlement amount should be reconciled exactly against the ledger. The stream model guides the design but does not certify business correctness.
Adversarial incident windows. A security dashboard asks for the top IPs during the last 15 minutes. An attacker may generate keys and watch published estimates. A theorem for a fixed stream with private randomness need not cover those adaptively chosen updates. Time windows also need a policy for late events and clock skew. If the arrival rate is 10,000 events per second, a 15-minute window can contain roughly 9 million events; specify whether the 256 MiB bound includes timestamps, keys, and state. Changing the threat model or window boundary changes the claim even if the query wording stays the same.
Telemetry, Payments and Incident Windows: Streaming Models, Guarantees & Complexity
Inputs: visits $A,B,A,C,B,A$; ask for lifetime and last-four-event counts by room. Model choice: cash register for visits, then a four-event sliding window for the second query. Trace: after six arrivals, lifetime $(A:3,B:2,C:1)$; remove the first two arrivals to obtain the suffix $A,C,B,A$ and window $(A:2,B:1,C:1)$. Checks: both totals are respectively 6 and 4; the window cannot have more visits than its four included events. Success criterion: write both vectors, state which events expire, and explain why lifetime A=3 is not the answer to the window's A query. If the second A scan was a duplicate rather than a real visit, define whether the pipeline deduplicates before counting.
Telemetry, Payments and Incident Windows: Streaming Models, Guarantees & Complexity
Scenario: 50,000 payment events/s, 24-hour horizon, 256 MiB per worker, regional retries, reversal events, and per-merchant alert queries. Decision worksheet: (1) Specify whether the target is net authorizations, unique transactions, or money settled; choose the key and units. (2) Test three prefixes: charge then reversal, reversal before delayed charge, and duplicate charge. Mark which satisfy strict turnstile after deduplication. (3) Budget bits for keys, counters, seeds, timestamps, and query support; specify acceptable $\varepsilon$, baseline, $\delta$, query count, and update/query latency. (4) Collect traces for late arrivals, reversal ordering, duplicates, and chosen-merchant queries; measure empirical errors against exact offline counts. Expected decision: use approximate summaries only for triage under a documented contract; reconcile settlement against an exact ledger. Acceptance: the written contract identifies the model, update order, window rule, error scale, failure scope, and a fallback when observed traffic breaks an assumption.
Design the Contract Before the Sketch
A streaming design starts with a question about data, then an update model, then a guarantee and resource budget. Test the contract with small sequences that expose its assumptions before considering an algorithm. The exercises below move from definitions to a review of a realistic specification. A complete answer states not only what works, but which changed input would invalidate the claim.
Practice: Design the Contract Before the Sketch
Level 1 — Define. Classify $(+A,2),(-A,1)$, $(-A,1),(+A,2)$, and $(+A,2),(+B,1)$ as cash register, strict turnstile, or general turnstile. Hint: inspect every prefix, not just the final vector. Expected: respectively strict turnstile (but not cash register), general turnstile, cash register (also strict). State whether the model names are nested rather than mutually exclusive.
Level 2 — Derive. For $f=(49,1,50)$, $\varepsilon =0.02$, compute $N$, the additive count allowance, and the frequency-share allowance. Expected: $N=100$, allowance $2$, share allowance $0.02$; an estimate 3 for the key with true count 1 satisfies additive count error but has 200% relative error. Edge case: repeat when $N=0$ and explain why normalization must stop.
Level 3 — Prove or refute. A fixed query fails with probability ≤0.005. Can 10 predetermined queries all succeed with probability ≥0.95? Hint: bound the probability of at least one failure. Expected: yes, union bound gives at most $10\times 0.005=0.05$ failure. Does the same statement follow for a query selected after reading earlier answers? Expected: no; identify the missing adaptive guarantee rather than claiming a specific failure rate.
Level 4 — Apply. For last-three-event counts from $A,B,A,C$, write the active suffix and vector. Expected: $B,A,C$, with three keys each at 1. A lifetime count for A=2 fails the window query. Describe what changes if “last three minutes” replaces “last three events.”
Level 5 — Extend. Draft a one-page specification for per-merchant payment alerts under reversals and duplicate delivery. Supply a query, exact update semantics, prefix assumption, window policy, additive or relative error baseline, $\delta$, simultaneous query scope, memory bits, pass count, update/query time, and evidence to test the assumptions. Rubric (10 points): model/units 2, window and deduplication 2, error and randomness 2, resource accounting 2, counterexample and validation plan 2. Debugging prompts: Does a refund appear before its charge? Does an empty window cause division by zero? Can clients choose keys after seeing outputs? A strong answer makes each case explicit and identifies which conclusion must be revisited.
Before selecting a sketch, write down the update and window models, the exact query, error baseline, probability scope, adversary, and memory/time budgets; test them on a refund, a duplicate, an empty window, and a rare key. Next, study how a specific frequency sketch implements one such contract and where its proof uses these assumptions.
Next in the Series
In Probability, Concentration & Confidence Amplification, we'll explore Turn random estimators into explicit accuracy and confidence guarantees..