Sliding Windows over Data Streams
Approximate counts in tiny memory: exponential histograms and DGIM.
A router sees billions of packets and is asked, at any moment, how many of the last million were errors. Storing the last million bits answers exactly, and a short proof shows nothing smaller can. Allow a 10% error and a few hundred buckets of power-of-two sizes, under 4,000 bits, do the job: the exponential histogram of Datar, Gionis, Indyk and Motwani (2002), provably optimal up to constant factors.
What you’ll learn
- Define the sliding-window streaming model and prove that exact counting of 1s in the last bits needs bits of memory.
- Implement an exponential histogram (DGIM) with buckets of power-of-two sizes, merging and expiry, and trace it on a short stream.
- Prove its relative error bound and its -bit memory bound, and state the matching lower bound.
- Extend the idea to sums, and place it among smooth histograms, sliding-window sampling and streaming sketches.
The sliding-window model
Counting the 1s of the whole stream needs a single counter of bits. The window is harder because of expiry: when a 1 drops out of the window, the algorithm must notice, so it must remember when its 1s arrived, not just how many there were. Remembering everything is exact; the surprise is that nothing less is.
Write a window as , oldest first; every one of the bit strings can occur. If zeros arrive next, after of them the window holds the newest bits of followed by zeros, so the correct answer is
Take two different windows , and let be the largest index with . All later bits agree, so after zeros the correct answers differ by exactly one:
An algorithm in the same memory state on and would behave identically on the same future input and give the same answers, a contradiction. So the windows need different states:
Exponential histograms
The way out is approximation. An exponential histogram groups the 1s of the window into buckets. A bucket stores two things: its size, a power of two, and the arrival time of its newest 1. Recent 1s sit in small buckets, old ones in large buckets, so the uncertainty is concentrated in the oldest bucket, the only one that can straddle the window's edge. This is the DGIM algorithm, in a simple form with a parameter :
- A 1 arrives: create a bucket of size 1. Whenever buckets share a size, merge the two oldest into one of twice the size, stamped with the newer of the two times. Merges can cascade upward like carries.
- Expiry: drop the oldest bucket once its time leaves the window.
- Query: add all bucket sizes, then subtract half of the oldest bucket's size, rounded down.
from collections import deque
class ExpHistogram:
"""Approximate count of 1s among the last N bits of a stream (a DGIM-style histogram)."""
def __init__(self, N, r):
self.N, self.r, self.t = N, r, 0
self.levels = [] # levels[i]: times of the buckets of size 2**i, oldest first
def add(self, bit):
self.t += 1
top = len(self.levels) - 1 # the oldest bucket sits in the highest nonempty level
while top >= 0 and not self.levels[top]:
top -= 1
if top >= 0 and self.levels[top][0] <= self.t - self.N:
self.levels[top].popleft() # its newest 1 has left the window
if bit:
stamp, i = self.t, 0 # a new bucket of size 1
while stamp is not None:
if i == len(self.levels):
self.levels.append(deque())
self.levels[i].append(stamp)
stamp = None
if len(self.levels[i]) > self.r: # r + 1 buckets of this size: merge the two oldest
self.levels[i].popleft()
stamp = self.levels[i].popleft() # the merged bucket keeps the newer time
i += 1
def estimate(self):
total = oldest = 0
for i, q in enumerate(self.levels):
if q:
total += len(q) << i
oldest = 1 << i # size of the oldest bucket (the highest level)
return total - oldest // 2 # the oldest bucket may stick out of the windowPython integers keep exact times here; a real implementation stores each time modulo , which suffices because every stored time lies in the last steps.
| Bucket size | Time of its newest 1 | Its 1s arrived at | Inside the window |
|---|---|---|---|
| 4 | 6 | 1, 3, 4, 6 | only the 1 at time 6 |
| 4 | 11 | 7, 8, 10, 11 | all 4 |
| 2 | 14 | 13, 14 | both |
| 2 | 16 | 15, 16 | both |
| 1 | 18 | 18 | yes |
| 1 | 19 | 19 | yes |
Error, memory and optimality
Let the oldest bucket have size and let be the total size of all the others. Their 1s are newer than the oldest bucket's newest 1, which is inside the window, so they are all inside; of the oldest bucket, between one and all of its 1s are inside:
The estimate is for (and exact for ), the midpoint of that range up to rounding, so
A bucket of size exists only because every smaller size has overflowed, and a size keeps buckets after each of its merges, losing buckets only to further merges (expiry removes the oldest bucket, which has the largest size). So every size with holds at least buckets:
Dividing the error by gives the accuracy. The same inequality bounds the sizes: since , , so at most sizes occur, each with at most buckets. Each arriving 1 adds one bucket and each merge removes one, so merges never outnumber arrivals.
For a window of bits and (error below 10%), what is the bound on the number of buckets, ?
Show the answer
187
and , so at most sizes with buckets each: 187 buckets. With 20-bit times that is 3,740 bits, about 470 bytes, against bits for exact counting. The bound is nearly tight: on a stream of all 1s with and , a simulation reaches 119 buckets against a bound of 121.
Datar, Gionis, Indyk and Motwani proved a matching lower bound: any algorithm that estimates the count within a factor , deterministic or randomized, needs bits. So the exponential histogram is optimal up to constant factors; their own accounting of buckets differs from the simple version here only in constants.
Signs break everything. If the stream may contain negative values, say from , they show that even a constant-factor approximation of the window's sum needs bits: cancellation lets a window of large positive and negative parts sum to almost nothing, and the algorithm cannot know what will expire.
Beyond counting
Sums of non-negative integers. If every item is an integer in , write it in binary and run one histogram per bit position: the sum of the window is , where counts the 1s in bit position . Using histograms multiplies the memory by . Datar, Gionis, Indyk and Motwani also give a direct histogram for sums, with matching upper and lower bounds.
Each per-bit histogram estimates its count within relative error . Why is the combined estimate of the window's sum also within relative error ?
- The errors of different bit positions cancel out on average
- Every term is non-negative, so
- Only the highest bit position matters
- It is not: the error grows by a factor equal to the number of bit positions
Show the answer
B. Every term is non-negative, so
The triangle inequality bounds the total error by the weighted sum of the individual errors, and each of those is at most times a non-negative count. No cancellation is needed, so the guarantee holds deterministically.
Other statistics. Babcock, Datar, Motwani and O'Callaghan (2003) maintained the variance and -medians clusterings of a window with histogram-like structures. Braverman and Ostrovsky (2007) introduced smooth histograms, which turn many insertion-only streaming algorithms into sliding-window algorithms for functions that change smoothly as old items are dropped, such as many norms of the window. Random samples of a window, which simple reservoir sampling cannot provide because items expire, need their own techniques too.
Counting distinct items or frequent items in a window combines these ideas with hashing-based sketches; see Count-Min, HyperLogLog & Streaming Sketches.
Key takeaways
- In the sliding-window model, exact counting of 1s in the last bits needs bits: feeding zeros distinguishes any two windows.
- An exponential histogram keeps at most buckets of each power-of-two size, merges the two oldest on overflow, expires the oldest, and counts half of the oldest bucket.
- Its relative error is below , its memory bits, and DGIM's matching lower bound makes it optimal up to constants; with negative values even approximation needs bits.
- Sums of bounded non-negative integers, variance, clustering and smooth functions extend the idea; frequent and distinct items combine it with hashing sketches.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why must an exact counter of 1s in the last bits remember about bits?
- Because the count itself can be as large as
- Because any two different windows can be told apart by feeding zeros and watching the exact counts, so they need different memory states
- Because the algorithm must be able to output the window itself
- It need not: a counter of bits plus the time of the oldest 1 suffices
Show the answer
B. Because any two different windows can be told apart by feeding zeros and watching the exact counts, so they need different memory states
Feed zeros until the last bit where the two windows differ is about to expire: the exact counts then differ by one. Same state would force the same answers, so the windows need states.
Why does the estimate subtract half of the oldest bucket's size?
- Because the oldest bucket always has exactly half of its 1s inside the window
- Because merging doubled its size by mistake
- Because anywhere from one to all of its 1s are inside the window, and half splits the difference
- To make the estimate always smaller than the true count
Show the answer
C. Because anywhere from one to all of its 1s are inside the window, and half splits the difference
Every other bucket lies entirely inside the window; the oldest one is known to have its newest 1 inside, but not how many of the rest. Counting half of it keeps the error at most half its size, and the buckets of each smaller size make that small relative to the count.
The histogram uses bits. Where does each factor come from?
- One from the number of bucket sizes, one from the bits needed to store each bucket's time
- One from sorting the buckets, one from binary search
- Both from the cascade of merges
- One from the counter, one from the sizes written in binary
Show the answer
A. One from the number of bucket sizes, one from the bits needed to store each bucket's time
Sizes are powers of two up to about , so there are of them, each with buckets; every bucket stores a time modulo , bits. DGIM showed this product cannot be beaten by more than a constant.
A stream contains values , and , and you want the sum of the last values within a constant factor. What is true?
- One histogram for the s and one for the s, subtracted, gives relative error
- The bit-decomposition trick handles it in bits
- An exponential histogram works unchanged
- Every algorithm needs bits: cancellation can make the true sum tiny while the window is full of information
Show the answer
D. Every algorithm needs bits: cancellation can make the true sum tiny while the window is full of information
DGIM proved this lower bound. Subtracting two good estimates fails because the difference of two large, nearly equal numbers can be tiny, so their small relative errors become a huge relative error of the difference.
Further reading
- M. Datar, A. Gionis, P. Indyk & R. Motwani, "Maintaining stream statistics over sliding windows," SIAM Journal on Computing 31(6) (2002), 1794–1813; extended abstract at SODA 2002.
- B. Babcock, M. Datar, R. Motwani & L. O'Callaghan, "Maintaining variance and k-medians over data stream windows," PODS 2003.
- V. Braverman & R. Ostrovsky, "Smooth histograms for sliding windows," FOCS 2007.
- J. Leskovec, A. Rajaraman & J. D. Ullman, Mining of Massive Datasets, 3rd ed. (Cambridge University Press, 2020), chapter 4, "Mining data streams".
- G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).