Given a stream of updates with and total weight , the -heavy hitters are the items with . There are at most of them. A one-pass algorithm that reports exactly this set needs memory linear in the number of distinct items, so the problem is relaxed with a second parameter . The algorithm must report every item with , may report items with , and must not report any item with . The top- problem asks instead for the items of largest frequency, which is the same problem with a threshold set by the data. Both are usually solved through a frequency estimate with , from which the report is the set of items whose estimate clears the threshold.

Two kinds of structure solve it. Counter-based summaries (Misra–Gries, Space-Saving and their relatives) keep about items with a counter each and decide on every update which items to keep. Their guarantees are deterministic, hold for every arrival order, and require insertions only. Linear sketches (Count-Min and Count Sketch, from HyperLogLog and Count-Min) keep an array of counters that is a linear function of the frequency vector. They accept negative updates and merge by addition, but they store no item identities, so reporting heavy hitters needs a separate set of candidates, and their guarantees hold with a stated probability over the hash functions.

The measurements below run every structure over the series’ benchmark stream, 160,961,718 hourly records of 60,974,808 Wikimedia pages with views. In that stream 134 pages are -heavy hitters (at least 44,596 views) and 3,437 are -heavy hitters (at least 4,460). The 100th most viewed page has 54,747 views. The distribution is flatter than the Zipf laws often assumed in analyses of these algorithms. The 1,000 most viewed pages hold 9.1% of the views and the 64,000 most viewed 29%.

The space bound

Berinde, Indyk, Cormode and Strauss (2010) show that no counter-based algorithm with counters can guarantee an error below on every stream, where is the total weight of all items except the heaviest. With the bound is , so an error of needs at least counters, half of what Misra–Gries uses. Counting bits instead of counters, Bhattacharyya, Dey and Woodruff (2016) give a randomized algorithm for the problem in bits for a universe of items and a stream of length , and show that this is optimal. In that bound a -bit identity is paid only for items, and the term costs bits per counter.

Misra–Gries

The algorithm of Misra and Gries (1982) keeps at most pairs (item, counter). An arriving item that has a counter increments it. An item without a counter takes a free one with value 1. If all counters are taken, the arriving item and every counter are decremented by one, and counters that reach zero are freed. With this is the majority vote algorithm of Boyer and Moore (1991).

Guarantee. Let be the number of decrement steps. Each removes one unit from each of counters and discards the arriving unit, so it removes units of weight in all. If is the sum of the counters at the end, then , and every estimate satisfies

with for an item without a counter. The error is at most , so counters suffice, and since every estimate is an underestimate, reporting the items with returns every -heavy hitter and nothing below .

Weighted updates follow the same rule (Berinde et al. 2010). An item of weight arriving at a full summary whose smallest counter is decrements every counter and itself by , and keeps the remaining in a freed counter if . The identity , with now the total decrement, still holds.

The algorithm was rediscovered twenty years later as Frequent (Demaine, López-Ortiz and Munro 2002; Karp, Shenker and Papadimitriou 2003), with a structure that makes each unit update . Counters with equal values share a group in a list ordered by value, and a decrement of every counter becomes a change of one offset. The implementation measured here keeps the counters in a binary min-heap with a hash index and represents the decrement as a global offset, so a weighted update costs and a decrement frees counters by popping the heap.

Space-Saving

Space-Saving (Metwally, Agrawal and El Abbadi 2005) keeps triples (item, count, error). An item with a counter adds its weight. An item without one, arriving at a full summary, takes over the counter with the smallest count . The counter’s item is replaced, its count becomes and its error becomes .

Guarantee. The counts always sum to , so . A monitored item’s count overestimates its true count by at most its recorded error, and an item that is not monitored has a true count of at most :

Every item with is therefore monitored, and the items whose lower bound clears the threshold form a report with no false positives. Metwally et al. organize the counters in a stream-summary, a list of buckets ordered by count, each holding the items with that count, so the smallest counter is the head of the list and a unit increment moves an item to the next bucket in time.

Misra–Gries is Space-Saving shifted by . Agarwal, Cormode, Huang, Phillips, Wei and Yi (2013, Lemma 2.3) show that after the same stream, the Misra–Gries summary with counters is the Space-Saving summary with counters with subtracted from every count and the counters that reach zero removed, and that . The two differ only in the direction of their error. Space-Saving reports upper bounds and Misra–Gries lower bounds, and the width of the interval is the same. On the benchmark stream, the Space-Saving summary with counters minus equalled the Misra–Gries summary with counters in all 25 comparisons (5 sizes, recorded order and 4 shuffles, weighted updates), and equalled the Misra–Gries bound to the view.

Tail guarantee. The bound is attained only when the weight is spread evenly. Berinde et al. prove that both algorithms satisfy, for every ,

so on a stream whose heaviest items hold most of the weight, the error falls far below . The bound holds for weighted updates as well. On the pageview stream it gives little, because the heaviest items hold a small share of , and at the tail bound is 6,409 views against , with an observed smallest counter of 6,365 to 6,366.

Linear sketches with candidates

A Count-Min or Count Sketch array answers a point query for any item, but it cannot list the items it has seen. Two methods produce a report. The first keeps a set of candidates. After each update the item’s estimate is computed and the item enters the set if its estimate exceeds the smallest estimate in the set, which is the arrangement Charikar, Chen and Farach-Colton (2004) describe for Count Sketch. The second, for streams with deletions (Cormode and Muthukrishnan 2005), keeps one sketch per level of a dyadic decomposition of the key space and descends from the root into ranges whose estimated weight clears the threshold; it needs keys from an ordered universe and times the space.

The two sketches bound the error in different norms. Count-Min, with width and depth , overestimates by at most with probability for each query. Count Sketch’s estimate has variance at most in each row, so by Chebyshev’s inequality a row errs by more than with probability at most and the median of 5 rows with probability at most . On the benchmark stream , so at equal width Count Sketch’s bound is smaller than Count-Min’s by a factor of , which exceeds 1 for every below about 16,000.

Conservative update (Estan and Varghese 2002) raises each of an item’s cells only as far as the new minimum, so Count-Min’s estimates fall and still never underestimate. It makes the sketch depend on the arrival order and removes its linearity. A deletion cannot be applied, and the sum of two such sketches still overestimates every item but is not the sketch of the combined stream.

Measured recall, precision and error

Each structure ran over all 160,961,718 records with weighted updates, in the recorded order (hour by hour, and within an hour grouped by project and largely in title order) and in 4 uniformly random permutations of the records. Memory is counted in units of 16 bytes, an 8-byte key and an 8-byte count, so a budget of units gives Misra–Gries and Space-Saving counters each. Space-Saving’s error field is not counted, and with it Space-Saving uses 1.5 times the memory shown. The sketches spend three quarters of the same bytes on 4-byte cells (depth 5 for Count Sketch, 4 for Count-Min) and a quarter on candidates of 16 bytes. The rows labelled conservative update are Count-Min with conservative update. In the tables below, the first value in a cell is the recorded order and the second the range over the 4 permutations, and a single value means the two agree. The sketches ran with 4 hash seeds in the recorded order, so their first value is also a range, and each permutation used its own seed for the hashes.

-heavy hitters (134 pages). An item is reported when its estimate is at least . Recall is the percentage of the 134 pages reported, and precision the percentage of reported items that are among them.

Recall, in percent. At 4 kB no structure found more than 16% of the 134 pages in any order.

16 kB64 kB256 kB1,024 kB
Misra–Gries6 / 7–827 / 24–2551 / 51–5484 / 82–83
Space-Saving25 / 25–3464 / 70–75100100
Count Sketch8–10 / 8–1156–59 / 55–5996–10099–100
Count-Min25–30 / 25–2897–99 / 93–96100100
Conservative update35 / 39–4387–88 / 94–96100100

Precision, in percent:

16 kB64 kB256 kB1,024 kB
Misra–Gries100100100100
Space-Saving3 / 3–52 / 2–390 / 93–9597 / 98–100
Count Sketch4–5 / 4–68 / 7–857–72 / 59–6998–99 / 97–99
Count-Min13–16 / 14–1513 / 12–1313 / 13–1481–83 / 81–84
Conservative update19 / 21–2312 / 1396 / 96–9999 / 99–100

The most viewed pages. Top-100 recall is the percentage of the 100 most viewed pages among the 100 largest counters or candidates. Misra–Gries and Space-Saving list the same 100. At 4 kB no structure listed more than 19 of them.

16 kB64 kB256 kB1,024 kB
Counter summaries31 / 31–4260 / 72–7493 / 97–99100
Count Sketch8–931–33 / 32–3382–88 / 81–8797–100 / 97–99
Count-Min30–32 / 29–3378–82 / 75–8197–98 / 97–9998–100
Conservative update38–41 / 41–4874–77 / 83–8496 / 98–100100

The errors on these pages, in the recorded order, in thousands of views: the largest over the 100 most viewed pages, then the mean over the 1,000 most viewed. At 4 kB the largest error of Count Sketch, 152 to 221 thousand views, was the smallest of the five, against 1,712 thousand for Space-Saving.

16 kB64 kB256 kB1,024 kB
Largest, top 100
Misra–Gries43710826.46.37
Space-Saving40999.523.75.10
Count Sketch64–14325.6–40.86.2–12.73.3–6.1
Count-Min592–604142–15035.4–37.18.4–9.0
Conservative update22855.412.92.45–2.49
Mean, top 1,000
Misra–Gries32.726.017.45.92
Space-Saving44.328.59.560.45
Count Sketch16.2–17.26.0–6.52.1–2.30.75–0.83
Count-Min538–53912829.76.6
Conservative update21637.52.100.21

In the shuffled orders the errors of Misra–Gries were within 6% of these, and those of Count Sketch and Count-Min were the same, since their counters do not depend on the order. The errors of Space-Saving and conservative update were smaller in most shuffled runs, most of all at 256 kB and above. Space-Saving’s largest error on the top 100 fell to 4.2 to 17.8 thousand views at 256 kB and 0.96 to 3.8 thousand at 1,024 kB, and conservative update’s to 2.2 to 9.6 and 0.52 to 1.8 thousand. The full ranges are in analyze.txt.

  • A counter summary separates heavy hitters only once its smallest counter falls below the threshold. Space-Saving’s was 107,853 at 64 kB, above , so every counter cleared the threshold and the report was the whole summary (4,000 items, precision 2%). At 256 kB was 26,403 and precision rose to 90%. The counts sum to and the 16,000 most viewed pages hold only 19% of the views, so stayed between 0.91 and 0.99 of at every size, and the summary separated the heavy hitters only once exceeded about . For (3,437 pages) the 1,024 kB summary had , above the threshold of 4,460, and reported every counter (precision 5%). Its lower bounds certified 2,114 of the 3,437 pages with no false positives.
  • Misra–Gries never reports a false positive and misses the pages near the threshold. Its estimates are Space-Saving’s minus , so its top-100 list is the same, and its thresholded report is the subset whose lower bound clears , 84% of the 134 pages at 1,024 kB. In the recorded order its largest error on the top 100 was within 1% of its bound at every size.
  • Count Sketch had the smallest error at small sizes and the poorest report. At 4 and 16 kB its largest error on the top 100 was the smallest of the five structures, 8 to 11 times below Space-Saving’s at 4 kB, and at 16 and 64 kB its mean error on the top 1,000 was the smallest. This follows from . Its report is limited by its candidates. At 4 kB the set has 62 places, so at most 62 of the top 100 can be listed, and an item displaced from the set returns only when a later update raises its estimate above the smallest candidate’s. Its two-sided error also admits pages below the threshold, which kept its precision at 57 to 72% at 256 kB.
  • Count-Min with conservative update gave the best report at 256 kB and above. At 256 kB it found all 134 pages with 96% precision, against 90% for Space-Saving and 13% for plain Count-Min, whose overestimates of up to admitted about 820 to 900 pages below the threshold. At 1,024 kB its errors on the top 100 and the top 1,000 were the smallest of the five structures in the recorded order, its mean error on the top 1,000 was also the smallest in the shuffled orders, and at it found all 3,437 pages with 73 to 77% precision.
  • The recorded order is harder for the order-dependent structures than a random one. At 64 kB, Space-Saving listed 60 of the top 100 in the recorded order and 72 to 74 in the shuffled orders, and conservative update 74 to 77 against 83 to 84. At 1,024 kB, Space-Saving’s largest error on the top 100 was 5,098 views in the recorded order and 962 to 3,784 shuffled. The guarantee is the same in both orders ( differed by less than 0.1%). Within each hour the stream is grouped by project, so a page’s records from one project arrive between long runs of records from other projects.

Update cost

Update cost for one thread over the whole stream in the recorded order, median of 3 runs, in nanoseconds per record. For the sketches it includes the query that follows each update and the offer to the candidate set.

16 kB1,024 kB
Misra–Gries109181
Space-Saving148207
Count Sketch7685
Count-Min2937
Conservative update4861

At least 60,974,808 of the 160,961,718 records, those that are the first of their page, find no counter, and each of them causes a replacement or a decrement that moves a counter through the heap in steps, and at 1,024 kB the 64,000-entry heap and its index no longer fit in the 2 MiB L2 cache. The sketches touch a fixed number of cells per update. In these measurements Count-Min with conservative update was 3 to 4 times faster per record than Space-Saving at both sizes.

Merging and deletions

Counter summaries computed on separate parts of a stream can be combined. Agarwal et al. (2013) merge two Misra–Gries summaries of counters by adding their counters item by item, subtracting the -th largest resulting value from every counter, and keeping the positive ones. The merged summary has at most counters and the same bound for the combined stream, so a tree of merges of any shape loses nothing against a single pass. By the isomorphism, the same procedure applies to Space-Saving. Linear sketches with the same hash functions merge by adding their arrays, and their candidate sets by taking the union and re-estimating each item from the merged array.

None of the counter algorithms accepts negative updates, since a deletion of an item whose counter was taken over cannot be undone. Count-Min and Count Sketch accept them directly, though the Count-Min bound then holds for of the net frequency vector only when no frequency becomes negative, and a candidate set built from estimates during the stream can hold items whose frequency later fell. The dyadic method above avoids the candidate set altogether.

Later designs

  • Lossy counting (Manku and Motwani 2002) divides the stream into windows of items and at each window boundary deletes the entries whose count plus maximum undercount does not exceed the window number. It uses entries in the worst case and fewer on skewed data. The survey and benchmark of Cormode and Hadjieleftheriou (2008) found Space-Saving the most accurate of the counter-based algorithms at a given space on their data sets.
  • Decrement by a sampled quantile. The frequent-items sketch of Anderson, Bevan, Lang, Liberty, Rhodes and Thaler (2017), used in the DataSketches library, decrements a full Misra–Gries summary by the median of a sample of its counters (1,024 in the implementation) instead of by the arriving weight, so each decrement frees about half the counters and decrements are rare even for weighted streams.
  • HeavyKeeper (Gong et al. 2018) targets top- flows on network hardware. Each bucket of a sketch holds a fingerprint and a count, and an item that collides with a bucket owned by another item decays that count with probability for a base near 1.08, so small flows rarely displace large ones.
  • heavy hitters. Items with include every heavy hitter and, on a flat stream, many more. Count Sketch finds them in words; BPTree (Braverman et al. 2017) does so in insertion streams in words.

The figure

The figure runs the four structures in the browser on a substream of the benchmark, the 39,986 records whose key hash falls in a fixed 1/4,096 of the hash range, which keeps every record of the 14,880 pages it selects and none of any other. The substream is more skewed than the full stream, with its heaviest page holding 24% of its 147,216 views, so small summaries already separate the first few pages from the rest. At 64 counters and the end of the day, Space-Saving lists 14 of the 20 most viewed pages among its 20 largest counters, with a largest error of 976 views against its guarantee of 1,551. Stepping through records shows the event each update causes, which is an increment, a counter taken over with the error it inherits, or a Misra–Gries decrement of every counter.

1101001,00010,000100,000views (log scale)true top 20 so farKurds (en.m)United Arab Emirates (en)Gerald Ford (en)Anna Wintour (en.m)Chloé Zhao (en)Moisés Arias (en.m)Vanessa Paradis (en.m)Chris Murphy (en.m)Ахматова, Анна Андреевна (ru.…Саввина, Ия Сергеевна (ru.m)HİSAR (hava savunma sistemi) …Aum Shinrikyo (en.m)Dark Enlightenment (en.m)Art the Clown (en.m)Aaron Swartz (en)Хатами, Амир (ru.m)滝沢秀明 (ja.m)Louis Slotin (en.m)Dammam (en.m)Exocet (en)

After all 39,986 records (147,216 views), Space-Saving with memory for 64 counters reports 14 of the 20 most viewed pages among its 20 largest counters. The largest error on those pages is 976 views (0.66% of the views so far). Space-Saving guarantees an overestimate by at most its smallest counter, 1,551 views.

The summaries run in the browser on a recorded substream of the benchmark: the 39,986 records, in file order, whose key hash falls in a fixed 1/4,096 of the hash range (14,880 pages, 147,216 views over the 24 hours). Memory is counted in 16-byte counters; Count Sketch and Count-Min spend three quarters of it on 4-byte cells (5 and 4 rows) and a quarter on 16-byte candidate entries. Space-Saving and Misra–Gries intervals are deterministic; the sketch intervals hold for each key with the stated probability over the hash functions. "As recorded" is hour by hour; within an hour the records are grouped by project and listed largely in title order.

Consequences for implementations

For heavy hitters in an insertion-only stream with a threshold fixed in advance, Space-Saving with somewhat more than counters gives a report with a certificate. The items whose lower bound clears are heavy hitters, the items whose upper bound does not are not, and only those in between are uncertain. On the pageview stream the summary became informative at , because remained near on a distribution this flat; on more skewed streams the tail guarantee places the point lower. The same counters read as Misra–Gries lower bounds give a report without false positives at the cost of recall near the threshold.

When the stream has deletions, when summaries are merged by addition or when the report must not depend on the arrival order, a linear sketch is required. On this stream Count Sketch gave smaller errors than Count-Min at small sizes because is about 1% of , and its report was limited by its candidate set. Where order dependence and the loss of linearity are acceptable, Count-Min with conservative update gave the most accurate report at 256 kB and 1,024 kB of the structures measured.