Skip to content
SlateGitOrgPublic

About

Hot-key splitting for live-stream chat counters: Space-Saving finds the raided channel, salting spreads it, and the two-phase merge must equal the unsplit answer exactly.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

hotsalt

CI

hotsalt

hotsalt is a discrete-time simulator and reference implementation of hot-key splitting for keyed stream aggregation. A Space-Saving summary finds the channel that is suddenly taking a large share of the traffic, a router salts that channel across several workers, and a two-phase merge turns the partial aggregates back into the answer an unsplit run would give. The merge is checked as an equality, not a tolerance: every (channel, 10 s window) must match a single-pass batch oracle exactly, including windows where a channel switches between salted and unsalted routing part-way through.

The data is synthetic: a seeded generator produces 30 simulated minutes of chat and tips with injected raids.

The problem

A live-streaming platform keeps per-channel 10-second counters (messages, tips in cents, distinct chatters). They feed creator dashboards and the slow-mode trigger of the moderation system. The stream is partitioned by channel across 8 workers. When a large streamer raids a small channel, 40% of all chat suddenly lands on one key: that worker's queue grows without bound, moderation for the channel reacts minutes late, and the other seven workers are mostly idle.

Splitting the key across workers fixes the load but is easy to get subtly wrong. Some aggregates cannot be split at all (an exact median needs every value in one place), a distinct count is only splittable under the right salt, and a channel that turns hot half-way through a window must not be counted twice or dropped. hotsalt builds the whole path and tests each of those failure modes.

How it works

flowchart LR
    A[Chat and tip events<br/>5,000 channels] --> B[Space-Saving detector<br/>1 s epochs, k counters]
    B -->|hot set and fanout| C{Router}
    A --> C
    C -->|hash of channel| D[Stage-1 workers<br/>FIFO queues, partial aggregates]
    C -->|hash of channel plus<br/>hash of user_id salt| D
    D -->|per-worker watermarks| E[Stage-2 merger<br/>finalizes a window when<br/>every watermark passed its end]
    E --> F[Per channel and window results]
    G[Batch oracle<br/>single pass over the log] --> H{Equal?}
    F --> H
Loading
  1. spacesaving.py keeps a Space-Saving summary per 1 s processing-time epoch: at most k counters, each with a count and an error, deterministic eviction (lowest count, then smallest key).
  2. detector.py flags a key when its guaranteed lower bound (count - error) reaches 5% of the epoch, and releases it after 10 consecutive epochs below 2%. fanout() turns a hot key's rate into the number of workers it needs.
  3. router.py sends unflagged events to worker stable_hash(channel) mod W. A flagged channel's events get salt stable_hash(user_id) mod fanout and go to worker (stable_hash(channel) + salt) mod W, so the slices land on distinct workers. Hashing is blake2b, never the built-in hash.
  4. sim.py runs 100 ms ticks. Each worker has fixed capacity and a FIFO queue and keeps partial aggregates per (window, channel, salt). The stage-2 merger merges the partials of a (channel, window) and finalizes a window only when every worker's processed-event-time watermark has passed its end.
  5. aggregates.py declares which aggregates may be split and the registry refuses the rest. oracle.py is written separately, with plain dicts and sets, so a bug in an aggregate cannot hide on both sides of the comparison.

Quick start

python3 -m venv .venv
.venv/bin/pip install -e ".[dev]"

.venv/bin/hotsalt compare --seed 11                 # all policies side by side
.venv/bin/hotsalt compare --seed 11 --json          # the same, machine readable
.venv/bin/hotsalt simulate --policy hash --seed 11
.venv/bin/hotsalt simulate --policy salted --seed 11 --toggle-storm

.venv/bin/python -m pytest -q

The whole compare run takes a few seconds.

Example output

hotsalt compare --seed 11 (numpy 2.5.5; numpy does not freeze its random streams across versions, so the absolute counts below can differ on another numpy version; the tests assert ranges, and the mismatches: 0 equality is checked on whatever log the installed version generates):

seed 11: 268,847 events (19,835 tips), 8 workers at 56.00 events/s each, 10 s windows

policy          lag p50  lag p99  raid p99  max queue  raid queue  final p99
hash               0.1s   280.4s    289.9s     16,577      16,577     290.3s
salted             0.1s     0.2s      0.3s         39          39       0.3s
salted-toggle      0.1s    60.9s     64.9s      3,781       3,781      65.0s

hot keys (detector: k=200, enter at 5% lower bound, release after 10 s below 2%)
channel         injected   flagged   delay  released   delay  intervals
ch-0042  10:00.0-18:00.0   10:01.0    1.0s   18:10.0   10.0s          1
ch-1337  20:00.0-25:00.0   20:01.0    1.0s   25:10.0   10.0s          1
ch-0777  26:00.0-29:00.0   26:06.0    6.0s   29:10.0   10.0s          1
other channels flagged at least once: 11 (26 intervals, from the Zipf head)

oracle equality
hash          windows checked: 79,678, mismatches: 0
salted        windows checked: 79,678, mismatches: 0
salted-toggle windows checked: 79,678, mismatches: 0

Worker capacity is three times the average total rate divided by 8, which is 56 events per second per worker for this log. Lag is measured per event from its event time to the tick in which a worker processed it. "raid p99" restricts the lag percentile to events that arrived during the raid of ch-0042 (10:00 to 18:00). Queue depths are events waiting at one worker. "final p99" is how long after its end a window was finalized.

Reading the table:

  • Under hash, the worker that owns ch-0042 receives more than its capacity for the 8 minutes of the raid. Its queue reaches 16,577 events and the raid-time p99 lag is 289.9 s. Because a window closes only when every worker's watermark passes it, the one stalled worker also delays finalization of every other channel's windows (p99 290.3 s).
  • Under salted, the detector flags ch-0042 one epoch after the raid starts, the fanout is computed from the observed rate, and the largest queue anywhere is 39 events. The raid-time p99 lag is 0.3 s.
  • salted-toggle is a correctness stress, not a policy to run: it forces every hot key to flip between salted and unsalted every 3 s, so half of the time the key is unsplit and the queue grows again. Its result is still equal to the oracle.
  • The detector also flags 11 other channels from the head of the Zipf distribution, mostly near the 5% line. They are included in every run and have no effect on the checks above.

Design decisions

  • Detection is independent of routing. The detector sees only the input stream, so the hot set is identical under every policy and the hash run reports the same detection delays as the salted run. A flag takes effect when the epoch that justified it closes; the first event of the next epoch is the first to be routed with it. Entering uses the lower bound (count - error), which never exceeds the true count, so a key only enters in an epoch where its true share is at least 5%; staying hot uses the overestimate, so a key is released only when even the overestimate is under 2%. The cost is up to one epoch of delay plus 10 s of hysteresis before release.
  • The salt is a hash of user_id, and the distinct count is a set union. With this salt every chatter lands in exactly one slice at a fixed fanout, so each salted partial holds about 1/fanout of the user set. A salt unrelated to the user would give every partial a share of every user, so the partials would no longer be disjoint and each would carry the whole set instead of a slice. The union would still be exact, but the state would be no smaller than unsalted, so DistinctExact("user_id") refuses to register under such a salt. The stage-2 merge still takes a union of sets rather than a sum of sizes, because a channel that flips between salted and unsalted routing, or changes fanout, inside a window can put one user in two partials. That is what the toggle-storm run exercises. The price is that partials carry sets, not counters.
  • An exact median is refused, not approximated. ExactMedian is holistic: no combination of per-slice medians gives the whole median. Registering it on a salted pipeline raises HolisticAggregateError. It works on an unsalted pipeline, where each (channel, window) lives on one worker.
  • Fanout follows the observed rate each epoch. fanout = ceil(hot_rate / (headroom x capacity - background_rate)), capped at the worker count. It raises CapacityError when background load alone uses all the headroom; the simulator then spreads the key over every worker. A fanout of 1 is not a split. The slices go to consecutive workers by hash, so a slice can land on a worker that already carries another heavy channel; the headroom factor (0.8) is the margin for that, and the simulator does not rebalance on load.
  • One global watermark, one unbounded merger. Windows close on the minimum worker watermark, which is what makes finalization correct and also what makes one overloaded worker hold every window open. The stage-2 merger has no queue of its own: partials are few (about 80 thousand (channel, window) results from 270 thousand events), so it is modelled as unbounded. A real merger would need its own capacity and back-pressure.

Testing

.venv/bin/python -m pytest -q          # 80 tests, about 20 s
.venv/bin/ruff check . && .venv/bin/ruff format --check .

The suite runs on a 30 minute log built once per session. It covers the Space-Saving fixture (a a b c a d a b a, k = 2 gives {a: 5/0, b: 4/3}) and, with Hypothesis, its guarantees (no false negatives above N/k, count - error <= true <= count, counts sum to N); detection of the three injected channels and the 5% entry rule against the true per-epoch counts; the aggregate merge property over random splits; refusal rules; committed blake2b worker ids that are also checked in a subprocess with a different PYTHONHASHSEED; the fanout fixtures (7, 8 capped, CapacityError); equality with the oracle for hash, salted and the toggle storm; load and queue bounds during the raid; finalization order and watermarks; and a byte-identical compare --seed 11 --json.

Project layout

src/hotsalt/
  spacesaving.py   Space-Saving summary and per-epoch summaries
  detector.py      HotKeyDetector with hysteresis, fanout(), CapacityError
  aggregates.py    Count, Sum, Min, Max, DistinctExact, ExactMedian, registry and refusals
  router.py        stable_hash, HashOnly, Salted
  sim.py           tick simulator: queues, stage-1 partials, watermarks, stage-2 merge
  oracle.py        single-pass batch aggregation and the comparison
  gen.py           seeded chat and tip generator with raids and a flapping channel
  report.py        policy runs, metrics, text and JSON rendering
  cli.py           typer commands: simulate, compare
  events.py        the Event record
tests/             pytest and Hypothesis suites

License

MIT. See LICENSE.

About

Hot-key splitting for live-stream chat counters: Space-Saving finds the raided channel, salting spreads it, and the two-phase merge must equal the unsplit answer exactly.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages