ELLMEngineering Large
Language Models
Download PDF

Chapter 50

Exact Streaming Queries and Time Windows

On this page

A streaming query must update its answer as events arrive, without retaining the entire history. This chapter implements exact top-k and time-window queries, including expiration and duplicate handling.

Start with the streaming contract

Let the stream be updates u_1, u_2, .... An update may be:

  • an insertion (key, value, event_time);
  • a weighted increment (key, delta);
  • a replacement of a previously identified record;
  • a deletion or negative increment;
  • a duplicate delivery of an earlier update.

Those cases are not interchangeable. A cash-register stream permits only nonnegative increments. A strict-turnstile stream permits negative increments but requires every true frequency to remain nonnegative. A general-turnstile stream permits signed frequencies. Standard linear Count-Min Sketch has its familiar one-sided guarantee for nonnegative frequencies, including valid strict-turnstile updates; it does not have that guarantee for arbitrary signed frequencies. A heap over immutable records does not implement updates or deletion.

Define the query before the data structure:

  • top k immutable records by score;
  • top k keys by frequency;
  • maximum over the most recent w arrivals;
  • maximum over an event-time interval;
  • mean or variance since a checkpoint;
  • a uniform sample of all records seen;
  • approximate membership, cardinality, frequency, or quantile.

Then define the contract along six dimensions:

Dimension Questions that change the algorithm
Scope All history, count window, event-time window, or exponential decay?
Accuracy Exact, deterministic rank error, one-sided additive error, or probabilistic relative error?
Updates Insert-only, replacements, deletions, or signed increments?
Ordering In arrival order, event-time order, or no ordering guarantee?
Distribution Must states merge exactly? Are partitions disjoint? Can records move between shards?
Recovery Are updates replayable? Are sources idempotent? Must snapshots align with offsets?

The space lower bound follows the query. Exact arbitrary-frequency counts require state proportional to the number of distinct keys. Exact arbitrary quantiles can require retaining the stream. Bounded memory therefore usually means a restricted window, a restricted input model, or an approximation.

Notation and error vocabulary

The four-chapter streaming sequence uses the following notation:

  • N is the number of processed updates or the current window width, as stated locally;
  • f(x) is the true nonnegative frequency of key x;
  • F_1 = sum_x f(x) is total frequency mass;
  • D = |{x : f(x) > 0}| is distinct cardinality;
  • R_le(v) = |{i : x_i <= v}| and R_lt(v) = |{i : x_i < v}| are inclusive and strict cumulative ranks; R(v) below denotes R_le(v);
  • p is a probability and delta is usually a failure-probability budget;
  • epsilon is an application-selected error tolerance, not machine epsilon.

An additive frequency bound |f_hat(x) - f(x)| <= epsilon F_1 scales with total mass. A relative bound |f_hat(x) - f(x)| <= epsilon f(x) scales with the queried frequency and is much stronger for rare keys. A rank bound |R_hat(v) - R(v)| <= epsilon N says nothing directly about numerical value error. A false-positive rate is a probability over queries and hash construction, not a count-error interval.

Also state the scope of probability:

  • pointwise: a fixed query chosen independently of the sketch succeeds with probability at least 1 - delta;
  • simultaneous: all queries in a declared set succeed together with probability at least 1 - delta;
  • empirical: an observed error percentile from experiments, not a mathematical guarantee.

To convert a pointwise failure probability to a simultaneous guarantee over Q fixed queries, a union bound can allocate delta/Q to each query. Adaptive queries chosen after inspecting outputs need a separate analysis; blindly reusing the pointwise statement can be invalid.

Finally, "mergeable" does not mean byte-for-byte identical to processing one serial stream. It means a documented merge operation produces a summary of the multiset union while preserving the promised error contract. Floating-point states, randomized compaction, and order-sensitive implementations can produce different internal bytes while remaining valid.

Exact top-k for immutable records

Suppose each record has a total ordering key (score, tie_breaker). The tie breaker must be deterministic and unique enough for the application, such as a record ID. Define "larger" as better. Maintain a min-heap H containing at most k records.

Assume finite scores and unique, comparable IDs; duplicate deliveries must be deduplicated or assigned distinct occurrence IDs according to the query. The invariant after processing the first i accepted records is:

H contains exactly the best min(i, k) records among the prefix, and H[0] is the worst retained record.

The update rule follows directly:

  1. If len(H) < k, insert the record.
  2. Otherwise compare it with H[0].
  3. If it is not better, discard it.
  4. If it is better, replace the root.

Example status: Illustrative Python excerpt; not standalone.

from math import isfinite
from heapq import heappush, heapreplace

def exact_top_k(stream, k):
    if k < 0:
        raise ValueError("k must be nonnegative")
    if k == 0:
        return []

    heap = []  # (score, stable_id, payload)
    for item in stream:
        if not isfinite(item.score):
            # A production API must choose reject, canonical ordering, or alert.
            continue
        entry = (item.score, item.id, item)
        if len(heap) < k:
            heappush(heap, entry)
        elif entry > heap[0]:
            heapreplace(heap, entry)

    return [entry[2] for entry in sorted(heap, reverse=True)]

Correctness proof

Use induction on the prefix length.

  • Base case: before any record, the heap contains the best zero records.
  • Inductive step: assume the invariant holds after i - 1 records. If the heap has fewer than k records, adding record i clearly gives the best prefix of size i. Otherwise, H[0] is the kth-best retained record. If the new record is no better than H[0], at least k prefix records are at least as good, so the new record cannot belong to the top k. If it is better, the old root becomes rank k + 1 or worse and replacing it produces exactly the new top k.

Heap construction for the first k records costs O(k) with bottom-up heapify or O(k log k) with repeated insertion. Each of the remaining n - k records costs O(1) for comparison and O(log k) only when it enters the heap. The worst-case bound is O(n log k) time and O(k) state. Producing sorted output adds O(k log k).

A full sort costs O(n log n) and retains O(n) records. Selection by partitioning can find the threshold in expected O(n) time for a materialized finite array, but it is not a bounded-state one-pass streaming algorithm. The heap is the appropriate choice when k << n, arrivals are incremental, and only retained records need storage.

Worked heap trace

Let k = 3 and let the total-order keys arrive as (8,a), (2,b), (5,c), (9,d), (5,e), where a larger score wins and the ID breaks ties. Heap storage order is an implementation detail; the retained sets evolve as:

Arrival Retained top set Boundary root
(8,a) {(8,a)} (8,a)
(2,b) {(2,b), (8,a)} (2,b)
(5,c) {(2,b), (5,c), (8,a)} (2,b)
(9,d) {(5,c), (8,a), (9,d)} (5,c)
(5,e) {(5,e), (8,a), (9,d)} (5,e)

The last replacement depends on the declared ID order. If equal scores should preserve first arrival, use arrival sequence as an inverse tie breaker. If the product must return every record tied with the kth score, a fixed-size heap is only the first phase: find the kth score, then retain or replay all records at that score.

Boundary semantics

Production correctness includes details hidden by the asymptotic result:

  • Define whether ties at the boundary return exactly k records or all tied records.
  • Reject or order NaN; language comparisons involving NaN can violate heap assumptions.
  • Include version and score definition in serialized state.
  • Decide whether payloads live in the heap or the heap stores IDs into durable storage.
  • Bound record size; O(k) records is not O(k) bytes when payloads vary.
  • Make query snapshots atomic relative to updates if readers require a coherent top k.

Exact distributed top-k

Let shards partition immutable records into disjoint sets S_1, ..., S_p. Let T_k(S) denote the best k records in set S. The coordinator can compute:

T_k(S_1 union ... union S_p) = T_k(T_k(S_1) union ... union T_k(S_p)).

To prove this, take a record x not in T_k(S_j) for its owning shard. At least k records in S_j rank above x; those same records exist globally. Therefore x cannot be in the global top k. Every possible global winner is present in some local top k, so taking top k of at most p k candidates is exact.

Each shard spends O(n_j log k) time and sends O(k) records. A coordinator heap costs O(p k log k) time and O(k) working memory if candidates stream in. A tree reduction uses the same compositional rule and avoids one coordinator receiving all p k candidates at once.

The proof fails when:

  • records are replicated and duplicates are not deduplicated;
  • scores change after local emission;
  • a key's frequency is split across shards and must be summed;
  • shards use inconsistent score versions or tie breakers;
  • the query is "top keys by global count" rather than "top immutable records."

For global frequency top-k, first aggregate each key's partial counts, or use a mergeable frequency summary with a stated error bound. Local top-k by partial count is not generally exact: a globally frequent key can rank just below k on every shard while its sum exceeds every local winner.

A minimal counterexample uses k = 1. Shard 1 observes A:6, X:5; shard 2 observes B:6, X:5. The local winners are A and B, so merging only local top-1 candidates returns frequency six. Globally, X has frequency ten and is the true winner. Record top-k composes because each record has one owner and one score; frequency top-k does not compose until partial counts for the same key are combined.

Mutable scores, updates, and deletions

A size-k heap alone loses information needed when a retained record is deleted or its score decreases. Common exact patterns include:

  • a map from ID to current version plus a heap with lazy stale-entry removal;
  • two indexed heaps or an order-statistics tree when arbitrary updates and rank queries are frequent;
  • a durable full state store plus a materialized top-k view;
  • periodic rebuilds when lazy garbage grows beyond a threshold.

Lazy deletion stores (score, id, version) in the heap and the current version in a map. Before reading or replacing the root, pop entries whose version is stale. This removes obsolete versions but does not recover candidates that a size-k heap already discarded. Exact arbitrary decreases and deletions require all live candidates in a score index, or an authoritative store from which to refill the top-k view. Stale versions add further memory when updates outpace cleanup; rebuild when physical heap size exceeds a multiple of live state.

For windowed top-k, expiration is also deletion. Exact implementations often combine a time-indexed expiration structure with a score-indexed structure. A single heap ordered by score cannot efficiently find all expired items, and a heap ordered by time cannot answer top-k efficiently. State and index count must be included in the design estimate.

Sliding windows and the monotonic deque

A count window of width w at arrival index i contains indices [i - w + 1, i]. A monotonic deque gives the maximum using only candidates that can still win.

Maintain two invariants:

  1. indices increase from front to back;
  2. values strictly decrease from front to back.

Example status: Illustrative Python excerpt; not standalone.

from collections import deque

def sliding_max(values, window):
    if window <= 0:
        raise ValueError("window must be positive")

    q = deque()  # (arrival index, value), values decrease front to back
    for i, value in enumerate(values):
        while q and q[0][0] <= i - window:
            q.popleft()                 # expired
        while q and q[-1][1] <= value:
            q.pop()                     # dominated
        q.append((i, value))
        if i + 1 >= window:
            yield q[0][1]

When a new value x_i arrives, any older candidate at the back with value <= x_i is dominated: x_i is at least as large and expires later, so the older value can never again be the maximum. After removing expired and dominated entries, the front is the largest live candidate.

Amortized analysis

One update can pop many entries, so its worst-case time is O(w). Across n updates, however, each index is:

  • appended exactly once;
  • removed from the back at most once;
  • removed from the front at most once.

The total number of deque operations is at most 3n, so total work is O(n) and amortized work is O(1) per update. The deque stores at most w index/value pairs and accepts an iterator without retaining the full input. Values must have a consistent total order; reject or explicitly order NaNs. A minimum uses the reversed comparison. Returning both minimum and maximum uses two deques.

The deque assumes an arrival-order count window. It does not directly solve out-of-order event-time windows because a late event can be inserted into the middle of the logical order and can invalidate previously emitted results.

Approximate sliding counts with exponential histograms

The monotonic deque exploits domination and is exact for min or max. A different problem is counting the number of ones among the last W bits. An exact algorithm may need enough information to know whether every expiring bit was zero or one, which requires Theta(W) bits in the worst case. An exponential histogram compresses old arrivals while keeping recent arrivals precise.

Each bucket represents a consecutive group of one-bits and stores:

  • a size that is a power of two;
  • the timestamp of the bucket's most recent one-bit.

Buckets are ordered newest to oldest. The following conservative variant makes the relative-error bound simple to prove: for 0 < epsilon < 1, choose b = ceil(1/epsilon) + 1 and keep at most b buckets of each size. On arrival:

  1. expire buckets whose newest timestamp is outside the window;
  2. ignore a zero, or create a newest size-one bucket for a one;
  3. if a size has b + 1 buckets, merge its two oldest buckets;
  4. give the merged bucket double size and the newer of the two timestamps;
  5. cascade the same rule to larger sizes.

Return zero when no buckets remain. A size-one oldest bucket is known exactly from its timestamp, so return the full sum in that case. Otherwise sum every bucket size but count only half of the oldest bucket:

count_hat = total_bucket_size - oldest_bucket_size / 2.

Every bucket except the oldest is fully inside the window. Only the oldest bucket can straddle the boundary. If its size is C, the estimate's absolute error is at most C/2.

Why is that a relative-error bound? A bucket of size C >= 2 is created by merging two size-C/2 buckets when there are b + 1 of them. At least b - 1 newer buckets of size C/2 remain, contributing (b - 1) C/2 ones. Their mass stays newer through subsequent merges and cannot expire while this older bucket remains. Thus:

(C/2) / (1 + sum_newer_bucket_sizes) <= 1/(b - 1) <= epsilon.

The 1 is justified because the boundary bucket's newest one has not expired; otherwise the whole bucket would have been deleted. The true live count is at least that one plus all fully live newer buckets. Therefore:

|count_hat - true_count| / true_count <= (C/2) / (1 + sum_newer_bucket_sizes) <= epsilon.

This variant uses more buckets than tightly optimized exponential histograms but keeps the same asymptotic bound. There are O((1/epsilon) log W) buckets. A size needs O(log log W) bits and a timestamp stored modulo a suitable multiple of W needs O(log W) bits, giving O((1/epsilon) log^2 W) bits. Unbounded absolute timestamps instead grow with stream lifetime. With constant-time access to the oldest buckets of each size, cascading can take O(log W) for one arrival but is O(1) amortized because every merge reduces bucket count.

Worked exponential-histogram query

For epsilon = 0.5, choose b = 3. After 24 consecutive ones, one reachable bucket state from newest to oldest is [1, 1, 2, 2, 2, 4, 4, 8]. Suppose the size-eight bucket crosses the window boundary. The stored total is 24; the estimate is 24 - 8/2 = 20. The true contribution of the boundary bucket is somewhere from one through eight, so the true count is from 17 through 24. The worst absolute error is four, exactly half the uncertain bucket; the relative error stays within the stated bound.

This is a count-window algorithm. Event-time disorder still needs watermark and revision semantics. Also do not use the relative guarantee to hide near-zero behavior: when the true count is tiny, an exact sparse representation may be simpler and more useful.

Event time, watermarks, and late data

Arrival order and event timestamps disagree. With the illustrative watermark at 18, the window ending at 20 has not reached its completion boundary. Allowed lateness and the late-update policy determine retention and corrections.
Open full diagram ↗

Arrival order and event timestamps disagree. With the illustrative watermark at 18, the window ending at 20 has not reached its completion boundary. Allowed lateness and the late-update policy determine retention and corrections.

Streaming systems distinguish:

  • event time: when the source says the event occurred;
  • ingestion time: when the platform first accepted it;
  • processing time: when an operator executes it.

A fixed event-time window of width T can assign timestamp t to [floor(t / T) T, (floor(t / T) + 1) T). A sliding window has a width and a smaller slide, so one event may update several windows. A session window groups events separated by less than an inactivity gap.

A watermark W is a progress claim: the system does not expect ordinary future arrivals with event time below W. It is not proof that no such event can arrive. Once W passes a window end, the system may emit an on-time pane. Allowed lateness L keeps state until approximately window_end + L; later records are dropped, side-output, or sent to a correction workflow.

An event-time contract must define:

  1. assignment: fixed, sliding, or session windows;
  2. watermark generation: source offsets, observed timestamp lag, or explicit source progress;
  3. triggers: early speculative, on-time, and late correction emissions;
  4. accumulation: each pane contains only new changes or the full revised aggregate;
  5. finalization: when state is deleted and no further in-place corrections occur;
  6. sink semantics: append, upsert by (key, window), or retract-and-replace.

If a heavy-hitter result changes after a late event, an append-only sink that prints another list creates ambiguity. An upsert should include window_id, revision, watermark, completeness state, and estimator parameters. Consumers can then distinguish speculative results from final results.

Watermarks in a multi-partition operator usually follow the minimum non-idle input watermark. One stalled partition can therefore hold every window open. Idleness detection needs a policy because marking a truly delayed partition idle can advance the watermark and make its later records late.

Retention clocks and replay horizons

Expiration is part of correctness. A processing-time time-to-live (TTL) limits storage according to a runtime clock; an event-time timer expresses when a window may finalize. They are not interchangeable. The Apache Flink state documentation, inspected September 24, 2026, describes state TTL as processing-time based. Check the actual engine/version rather than assuming that a TTL follows watermarks.

Consider a five-minute window ending at 12:05 with 20 minutes of allowed lateness. An outage pauses event-time progress while wall-clock time advances to 12:40. Deleting its state solely because 25 wall-clock minutes elapsed can destroy the state needed to accept a replayed 12:04 event. Restore the watermark and source positions with the state; either retain the window until its declared event-time finalization or mark the result incomplete and rebuild from a retained source.

Deduplication needs its own horizon. If operators may replay seven days of input but event-ID receipts expire after one day, a two-day-old event can count twice. Longer receipts cost storage; rebuilding a historical window in a separate output epoch can be cheaper. Bind output identity to that epoch and do not let an old worker overwrite a repaired result merely because its local revision counter is larger. A monotonically ordered epoch, or a fenced writer lease, must be checked at the sink.

Worked check: a watermark remains at 12:03 while the runtime clock reaches 12:40. Is the 12:00-12:05 window final? No. Its progress contract has not reached the window end, much less the lateness boundary. A storage cap can force an incomplete result, but cannot turn missing evidence into completeness.

Check your design: exact queries

Before moving on, explain why local top-k can be merged for immutable records but not by simply summing local frequency ranks. Then specify what a late event changes in an already emitted time window. A complete answer names a total order for records, retained candidate evidence for frequencies, and a revision-aware sink for windows. The cumulative exercises later in this part give worked solutions.