Sub topic 13
Deletions and the Turnstile Model
This chapter assumes you know the count-min sketch update and query from the earlier chapters. It also assumes you know the one-sided error property and the Markov argument for the (ε, δ) guarantee. Here you will see what happens when the stream can also remove items, and why the estimator has to change when counts can go negative.
Three stream models
So far every update added to a count. That is the cash register model: each stream element increments one item's count by a positive amount, and counts only grow.
Real systems often need to subtract. Examples are a user unfollowing an account, an item leaving a cache, or a session ending. The general framework is the turnstile model. Each update is a pair (item, delta), and delta may be negative. The name comes from a turnstile that counts people entering and leaving.
The turnstile model has two variants, and they behave very differently.
| Model | Allowed updates | Counts can be negative? | Estimator | Error type |
|---|---|---|---|---|
| Cash register | `delta > 0` | No | Row minimum | Overcount only |
| Strict turnstile | Any `delta`, but every true count stays ≥ 0 | No | Row minimum | Overcount only |
| General turnstile | Any `delta` | Yes | Row median | Over or undercount |
In the strict turnstile model you may only remove what you previously added. In the general turnstile model, counts can drop below zero. This happens when you track differences between two streams, or when deletions can arrive before the matching insertions.
Deletions in the strict turnstile model
The sketch update is linear. Adding delta to the item's counter in each row works for negative delta as well. If the stream is strictly non-negative at query time, the one-sided error argument still holds:
- Each counter equals the sum of the current true counts of all items hashed to that cell.
- Every current true count is ≥ 0, so a counter is the item's true count plus a non-negative amount from collisions.
- The row minimum is therefore still ≥ the true count.
The error bound holds with N defined as the current total, the sum of the current counts. Insertions that were later deleted no longer contribute. A sketch that saw a million insertions and 999,000 deletions has an error scale of about ε · 1,000, not ε · 1,000,000.
The sketch below takes w and d directly so the second demo can use a degenerate shape. It has both estimators. It is self-contained and uses integer items, so the output is the same on every run.
import random
import statistics
class TurnstileSketch:
def __init__(self, w, d, seed=0):
self.w = w
self.d = d
self.p = (1 << 61) - 1
rng = random.Random(seed)
self.params = [
(rng.randrange(1, self.p), rng.randrange(0, self.p))
for _ in range(d)
]
self.table = [[0] * w for _ in range(d)]
def _cols(self, item):
x = hash(item) % self.p
return [((a * x + b) % self.p) % self.w for a, b in self.params]
def update(self, item, delta):
for row, col in zip(self.table, self._cols(item)):
row[col] += delta
def estimate_min(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))
def estimate_median(self, item):
return statistics.median(
row[col] for row, col in zip(self.table, self._cols(item))
)
# Strict turnstile: insert 10 of each of 200 items, then delete 5 of the first 100.
sketch = TurnstileSketch(w=272, d=5)
truth = {}
for item in range(200):
sketch.update(item, 10)
truth[item] = 10
for item in range(100):
sketch.update(item, -5)
truth[item] -= 5
for item, count in truth.items():
assert sketch.estimate_min(item) >= count # still never an undercount
print("current total N =", sum(truth.values())) # 1500
print("item 0:", truth[0], sketch.estimate_min(0))The assertion holds for every item because the true counts never went below zero.
Why the minimum fails with negative counts
The minimum works because collisions only add. In the general turnstile model, a colliding item can have a negative count, so a cell can hold less than the item's true count. The row minimum picks the most deflated cell, so it can undercount, and the one-sided guarantee is gone.
The following extreme case shows the effect. With a single column, every item shares one counter per row.
tiny = TurnstileSketch(w=1, d=3)
tiny.update(1, 5) # item 1 has true count +5
tiny.update(2, -5) # item 2 has true count -5
print(tiny.estimate_min(1), tiny.estimate_median(1)) # 0 0, true count is 5The negative mass of item 2 cancels item 1 completely. Real sketches are wider, so the cancellation is partial. But the direction of the error is now unpredictable, and taking the minimum or the maximum would pick out the worst noise in either case.
The median estimator
For the general turnstile model, take the median of the d row values instead of the minimum.
The error in one row is the signed sum of the other items' counts that landed in the same cell. It can be positive or negative, and it is usually small. Each row gives an independent noisy reading of the true count. The median ignores readings that are far off in either direction, so a few bad rows do not move it.
The guarantee changes in three ways:
- Error scale. The bound is in terms of ‖f‖₁, the sum of the absolute values of all counts, not the signed sum. Items with negative counts add to the noise.
- Two-sided error. With probability at least 1 − δ, the estimate satisfies |estimate − true| ≤ ε‖f‖₁. It may be above or below the true count.
- Larger constants. The row analysis needs more headroom, as described next.
Why the median works
Choose the width w = ⌈4/ε⌉. For one row, the expected absolute collision error is at most ‖f‖₁ / w ≤ ε‖f‖₁ / 4. By Markov's inequality, the probability that this row's error exceeds ε‖f‖₁ is at most 1/4. Call such a row bad.
The median is wrong only if at least half of the rows are bad. Rows use independent hash functions, so the number of bad rows is dominated by a binomial with success probability 1/4. A Chernoff bound shows that the probability of half the rows being bad falls exponentially in d. So d = O(log(1/δ)) rows suffice.
The pattern matches the minimum case: Markov bounds one row, and independence across rows boosts the confidence. The difference is that the minimum needs only one good row, while the median needs a majority of good rows. That is why the median needs a wider table (4/ε instead of e/ε) and a larger constant on the depth.
What stops working with deletions
Several features from earlier chapters depend on counts only growing.
The other features behave as follows:
- Merging still works. Merging adds tables cell by cell, and addition is linear. Subtracting one sketch from another also works if the shapes and hash parameters match. This gives a sketch of the difference between two streams, which is a general turnstile use case.
- Heavy hitters with a heap become harder. The heap from the earlier chapter keeps items whose estimates have risen. After deletions, an item in the heap can fall below the threshold without any new update to it. An item outside the heap can never re-enter if it is not updated again. A real implementation must recheck candidates or use a different structure.
- Invalid deletions break the strict model. Deleting an item that was never inserted gives it a negative count. The minimum then loses its guarantee. If your pipeline can produce such events, plan for the median estimator.
Choosing between them
Use the minimum estimator when updates are insertions only, or when you can guarantee deletions always match earlier insertions. It gives the tighter table and the one-sided guarantee. Use the median estimator when the stream tracks signed quantities, such as differences between two streams, or when deletion events can arrive out of order.
If you need two-sided error but also want exact lower bounds, the Count Sketch (covered in the final chapter) uses random signs and handles the general model with a better error scale. It measures error against the L2 norm, not the L1 norm.
Exercise
A sketch has seen 1,000,000 insertions and 990,000 matching deletions, so every true count is still ≥ 0. You query it with the row minimum. Is the estimate guaranteed to be at least the true count, and what is N in the error bound ε·N?
Show answer
Yes. This is the strict turnstile model, so every cell is the sum of non-negative current counts and the minimum never undercounts. N is the current total, 10,000, not the 1,000,000 insertions seen. The overcount is at most ε · 10,000 with probability at least 1 − δ.
Exercise
Why does the median estimator need a wider table than the minimum estimator, and why is the row minimum unsafe when counts can be negative?
Show answer
The minimum needs only one row with a small collision error, so w = ⌈e/ε⌉ is enough. The median needs a majority of rows to be good, so each row must be good with probability well above 1/2, which is why the standard analysis uses w around 4/ε. With negative counts, a colliding item can subtract from a cell and pull it below the true count. The minimum then picks that deflated cell, and the sketch can undercount.