Stream Models: Insertion-Only, Cash Register and Turnstile
Before any algorithm, a streaming result has to say what the stream may contain. A bound proved for streams of insertions can fail completely once deletions are allowed, and a few lower bounds hold only when frequencies may become negative. This lesson fixes the models used in the rest of the course, introduces linear sketches, the tool that handles deletions for free, and works through the first sketch of the course: recovering a vector that has only one non-zero entry.
Updates and the frequency vector
The input is a sequence of updates for , with and . The updates define the frequency vector
and the algorithm must answer a question about (its largest entries, its norm, its number of non-zeros) at the end, or at any time. The models differ in which updates are allowed (the names follow Muthukrishnan, 2005):
| Model | Updates | Typical source |
|---|---|---|
| insertion-only (unit cash register) | : the stream is a list of items | page views, packets, words of a text |
| cash register | bytes per flow, sales amounts | |
| strict turnstile | any , but at all times | a database table with inserts and deletes |
| general turnstile | any , may have negative entries | the difference of two streams, |
Each model contains the ones above it, so an algorithm for the general turnstile model works everywhere, and a lower bound for insertion-only streams holds everywhere. The difference between the last two rows matters: some guarantees (count-min's "never underestimates", for example) use and are lost in the general model.
The time-series model, where is simply the value , is the other classical model; it reduces to the cash register model by sending the update .
The program generates one frequency vector in three ways and checks that the streams agree. Every model ends at the same ; what differs is the path, and an algorithm sees only the path.
import random
from collections import Counter
rng = random.Random(1)
n = 8
target = [rng.randrange(0, 6) for _ in range(n)]
# insertion-only: each item listed f_i times, in random order
ins = [i for i in range(n) for _ in range(target[i])]
rng.shuffle(ins)
# cash register: positive increments that add up to f_i
cash = []
for i in range(n):
left = target[i]
while left:
d = rng.randint(1, left)
cash.append((i, d))
left -= d
rng.shuffle(cash)
# strict turnstile: insert extra copies first, then delete them again (f never goes negative)
turn = [(i, +1) for i in ins] + [(i, +1) for i in range(n)] * 2
rng.shuffle(turn)
turn += [(i, -1) for i in range(n)] * 2
def freq(updates):
f = [0] * n
for i, d in updates:
f[i] += d
return f
print("target f :", target)
print("insertion-only:", freq((i, 1) for i in ins), f"({len(ins)} updates)")
print("cash register :", freq(cash), f"({len(cash)} updates)")
print("turnstile :", freq(turn), f"({len(turn)} updates)")target f : [1, 4, 0, 2, 0, 3, 3, 3]
insertion-only: [1, 4, 0, 2, 0, 3, 3, 3] (16 updates)
cash register : [1, 4, 0, 2, 0, 3, 3, 3] (10 updates)
turnstile : [1, 4, 0, 2, 0, 3, 3, 3] (48 updates)
Resources and what "small" means
A streaming algorithm is judged by:
- space, the number of bits (or words of bits) it keeps between updates. The goal is , or for an -approximation. Storing exactly takes words and is the trivial upper bound;
- update time, the work per update, ideally or ;
- query time, the work to produce an answer;
- the number of passes. Almost everything in the course uses one pass; graph problems sometimes use a few.
Most interesting functions of cannot be computed exactly in sublinear space, even with randomization. The next lesson proves one such bound directly, and Space Lower Bounds from Communication Complexity gives the general method. So the algorithms of the course approximate, and almost all of them are randomized.
Linear sketches
A linear sketch stores for a matrix (or over a field) with , where is chosen at random from a family that can be described in small space, usually by a few hash functions. An update changes the sketch by times column of :
so the sketch can be maintained without storing , as long as column can be computed from the hash functions when it is needed. Linearity gives three properties at once:
- Deletions are free. The update rule does not care about the sign of , so a linear sketch works in the general turnstile model.
- Merging. Two machines that saw streams with frequency vectors and , using the same , can add their sketches: .
- Differences. summarizes how two streams differ, for example the traffic of a link measured at both ends.
Count-min, Count-Sketch and the AMS sketch are linear; Misra-Gries, Space-Saving and HyperLogLog are not (they use comparisons or maxima), which is why they need insertion-only streams. For the general turnstile model a converse holds under technical conditions: any algorithm can be turned into one that maintains a linear sketch with only a logarithmic loss in space (Li, Nguyen and Woodruff, 2014; the conditions, such as very long streams, exclude some practical settings).
A first sketch: recovering a 1-sparse vector
Suppose that at query time has at most one non-zero entry, but the stream before that may have touched many items: a router checking that all flows but one have balanced packet counts, or the classical puzzle of finding the one number missing from a shuffled list. Two counters suffice:
If with , then and , so . Both are linear in . They do not detect whether really is 1-sparse: gives . A third, randomized counter fixes that. Pick a prime and a random and keep
If then . Otherwise the polynomial is a non-zero polynomial of degree at most (assuming the entries of are smaller than in absolute value), which vanishes at the random with probability at most by the Schwartz-Zippel lemma. So the test "is , is an integer , and is ?" accepts a vector that is not 1-sparse with probability at most . This 1-sparse recovery structure is the building block of -sampling (Sparse Recovery and l0-Sampling) and through it of the graph sketches of the course.
import random
P = (1 << 61) - 1
class OneSparse:
def __init__(self, rng):
self.z = rng.randrange(1, P)
self.s0 = self.s1 = self.s2 = 0
def update(self, i, d): # linear in f: works with deletions
self.s0 += d
self.s1 += d * i
self.s2 = (self.s2 + d * pow(self.z, i, P)) % P
def query(self):
if self.s0 == 0:
return "zero" if self.s1 == 0 and self.s2 == 0 else "not 1-sparse"
j, r = divmod(self.s1, self.s0)
if r == 0 and j >= 0 and self.s2 == self.s0 % P * pow(self.z, j, P) % P:
return f"1-sparse: f[{j}] = {self.s0}"
return "not 1-sparse"
rng = random.Random(7)
n = 100000
# all items inserted and deleted again in random order, except item 31337, inserted 3 times
ups = [(i, +1) for i in range(0, n, 7)] * 2 + [(31337, +1)] * 3
rng.shuffle(ups)
ups += [(i, -1) for i in range(0, n, 7)] * 2
s = OneSparse(rng)
for i, d in ups:
s.update(i, d)
print(len(ups), "updates ->", s.query())
t = OneSparse(rng) # f = e_1 + e_3: the plain ratio would say "2"
for i, d in [(1, 1), (3, 1)]:
t.update(i, d)
print("f = e1 + e3: s1/s0 =", t.s1 / t.s0, "->", t.query())57147 updates -> 1-sparse: f[31337] = 3
f = e1 + e3: s1/s0 = 2.0 -> not 1-sparse
The structure keeps three numbers no matter how many updates arrive, and it found the one surviving item among about 57 000 updates. The second case shows why the fingerprint is needed.
In practice
- Insertion-only is the right model for logs and counters, and the deterministic summaries of the next section (Misra-Gries, Space-Saving) are the usual choice there.
- Turnstile arises with databases (inserts and deletes), with differences of streams and with graphs whose edges are added and removed. Linear sketches are then essentially the only option.
- Sliding windows, where only the last items count, form a further model with its own techniques (exponential histograms, Datar, Gionis, Indyk and Motwani, 2002); the course does not treat it. The offline relative is the practice problem Sliding Window Maximum.
Test yourself
In which model may a frequency become negative?
- Insertion-only
- Cash register
- Strict turnstile
- General turnstile
Why does a linear sketch handle deletions?
- It stores the whole stream
- An update adds times column of , whatever the sign of
- It ignores negative updates
- It recomputes after each deletion
The counters and give . What can you conclude without the fingerprint ?
- for some
- Nothing certain: could also be, for example,
- is zero
- has exactly two non-zero entries
Which of these summaries is a linear sketch?
- Misra-Gries
- HyperLogLog
- Count-min
- Space-Saving