Video in progress

You need to find the 100 most frequent IPs in a huge log stream, but you can't count everything in memory. What's your approach?

If an exact answer is required, I partition to disk by IP hash, count each chunk separately and merge the top-Ks. If an approximate answer is enough, Count-Min Sketch with a small heap, or the Space-Saving algorithm: fixed memory, a single pass.

📖 Answer

The first question: is it really true that "you can't count everything"? IPv4 has 4 billion values, but the unique IPs in a real log are usually tens of millions. A HashMap<Integer, Integer> with 10 million entries takes ~1 GB. With a primitive map (fastutil's Int2IntOpenHashMap) it's 100-200 MB. The simple solution may well fit.

If it doesn't fit, there are two ways.

Exact, two passes. I write each IP into one of 256 temporary files by hash % 256. An IP always lands in the same file, so I can count each file independently in memory and take its top-100 with a min-heap. At the end I pick the overall top-100 from 256 × 100 candidates. This is MapReduce itself.

Approximate, one pass, fixed memory.

Count-Min Sketch is a table of counters of size d × w, with its own hash per row. On insert we increment d cells, and on query we take the minimum. The result is never less than the true value, it can only be higher.

void add(int ip) {
    for (int row = 0; row < depth; row++) table[row][bucket(ip, row)]++;
}
long estimate(int ip) {
    long min = Long.MAX_VALUE;
    for (int row = 0; row < depth; row++) min = Math.min(min, table[row][bucket(ip, row)]);
    return min;
}

The sketch itself doesn't say "which IPs are on top", so I keep a min-heap of size K next to it: if an incoming IP's estimate is bigger than the smallest in the heap, I swap it in.

The Space-Saving algorithm does this in a single structure: K counters, and when a new element finds no room, it takes over the smallest counter and inherits its value. It gives guarantees for heavy hitters.

Which one? For reporting or billing, the exact approach, since latency doesn't matter. For DDoS detection or a real-time dashboard, the approximate one: an exact answer that's a minute late is worth nothing. One more plus: approximate structures can be added together. Each server sends its sketch and the center sums them.