System Design Part 3 Storage basics

Bloom Filters and HyperLogLog: Trading a Little Error for a Lot of Memory, and What to Do When Someone Games the Estimate

Bill.Lin 21 min read

System Design series Part 3-6 | Previous: File and Object Storage | Next: Full-Text Search and Inverted Indexes | Series map

Read first: Part 2-3 Caching in Depth, Part 3-3 B-Tree vs LSM-Tree.

Scenario and problem

The platform has two needs that look unrelated:

  1. Cache penetration: as the caching post mentioned, someone hits /products/{id} with a flood of product IDs that do not exist. The cache always misses, and every request goes to the database. Caching empty results stops repeated IDs, but the attacker can generate endless distinct IDs, and the empty results end up filling the cache
  2. Unique visitors (UV): marketing wants the number of unique visitors per talk per day, and for any date range (a whole week, say). Visitors who are not logged in are identified by the visitor ID in a cookie

The exact approach is to store the elements: a Set holding every product ID, and a Redis SET holding each talk’s visitors for each day. At a rough 60 bytes per member, a popular talk with 500,000 visitors in a day takes 30 MB; 365 keys a year come to about 11 GB, and that is just one talk. To count unique visitors for a whole week, you also have to union 7 sets.

All you need is "is it there?" and "how many?"1 / 5
All you need is "is it there?" and "how many?"AttackerProduct APIDatabaseVisitorsRedisAttackerProduct APIRedisDatabaserandom IDsmissquery each timeAttackerProduct APIRedisalways new IDscache empty resultEmpties fill the cacheVisitorsRedisadd visitor ID30 MB per talk per dayVisitorsRedisa SET per talk per day11 GB a year, union of 7 a weekProduct APIRedisVisitorsis this ID in?how many?No need to store the items
  1. Product IDs that do not existSomeone calls /products/{id} with a flood of product IDs that do not exist. The cache never finds them, and every request goes to the database.
  2. Caching empty results is not enoughCaching "no such product" too stops repeated IDs; but the attacker can generate endless distinct IDs, and the empty results end up filling the cache.
  3. Unique visitorsMarketing wants unique visitors per talk per day. Put the visitor IDs in a Redis SET, and a popular talk with 500,000 people in a day takes 30 MB.
  4. A year, a weekOne talk is 365 keys a year, about 11 GB, and that is just one talk; counting unique visitors for a whole week also means a union of 7 sets.
  5. Only the answer is neededBoth needs only want "is it there?" or "how many?", not the elements themselves. If you can accept a little error, you can save several orders of magnitude of memory.

Both needs have something in common: all they need is “is it there?” or “how many?”, not the elements themselves. If you can accept a little error, you can save several orders of magnitude of memory.

The simplest approach and its limits

Approach Problem
HashSet or Redis SET Memory grows with the number of elements
Database COUNT(DISTINCT visitor_id) Scans every event each time; the page views in the B-Tree vs LSM post reach 1 billion rows a day
Caching empty results Stops repeated nonexistent IDs, but not IDs that are different every time

Core mechanism

Bloom filter: “definitely not there” or “maybe there”

A Bloom filter is an array of m bits plus k hash functions:

  • Add: run the element through the k hash functions to get k positions, and set all of them to 1
  • Query: check those k positions. If any of them is 0, the element is definitely not there; if all of them are 1, the element is maybe there (or other elements just happened to set all of those positions to 1)

So it makes only one kind of mistake: it reports an absent element as “maybe there” (a false positive). It never reports a present element as absent. After n elements are added, the false positive rate is about (1 − e^(−kn/m))^k; the best k is (m/n) × ln 2, and then each element needs −ln p ÷ (ln 2)² bits. Implement one to check the formula:

Implementation and test (java BloomFilterDemo.java)
java
import java.util.BitSet;

public class BloomFilterDemo {

    static final class Bloom {
        final BitSet bits;
        final int m;
        final int k;

        Bloom(long expected, double bitsPerItem) {
            m = (int) Math.ceil(expected * bitsPerItem);
            k = (int) Math.max(1, Math.round(bitsPerItem * Math.log(2)));   // optimal number of hashes = (m/n) ln 2
            bits = new BitSet(m);
        }

        void add(long item) {
            long h1 = mix(item);
            long h2 = mix(h1) | 1;                                  // two hash values combine into k positions
            for (int i = 0; i < k; i++) {
                bits.set(index(h1 + i * h2));
            }
        }

        boolean mightContain(long item) {
            long h1 = mix(item);
            long h2 = mix(h1) | 1;
            for (int i = 0; i < k; i++) {
                if (!bits.get(index(h1 + i * h2))) {
                    return false;                                   // any position is 0: definitely not there
                }
            }
            return true;                                            // all 1: maybe there
        }

        int index(long hash) {
            return (int) Long.remainderUnsigned(hash, m);
        }
    }

    static long mix(long z) {                                       // the SplitMix64 mix function
        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
        return z ^ (z >>> 31);
    }

    public static void main(String[] args) {
        int n = 1_000_000;
        System.out.printf("Insert %,d IDs, then test with another %,d IDs that do not exist%n", n, n);
        for (double bitsPerItem : new double[] {4.79, 9.59, 14.38}) {
            report(n, bitsPerItem, n);
        }
        System.out.println();
        System.out.println("Designed for a 1% false positive rate, but more items inserted than designed for:");
        for (int actual : new int[] {n, 2 * n, 4 * n}) {
            report(n, 9.59, actual);
        }
    }

    static void report(int designed, double bitsPerItem, int inserted) {
        Bloom bloom = new Bloom(designed, bitsPerItem);
        for (long id = 0; id < inserted; id++) {
            bloom.add(id);
        }
        int falsePositives = 0;
        for (long id = inserted; id < inserted + 1_000_000L; id++) {
            if (bloom.mightContain(id)) {
                falsePositives++;
            }
        }
        double theory = Math.pow(1 - Math.exp(-(double) bloom.k * inserted / bloom.m), bloom.k);
        System.out.printf("  %5.2f bits per item, k = %2d, %,9d inserted: %,6.0f KB, false positives measured %6.3f%% | theory %6.3f%%%n",
                bitsPerItem, bloom.k, inserted, bloom.m / 8.0 / 1024, falsePositives / 10_000.0, theory * 100);
    }
}
text
Insert 1,000,000 IDs, then test with another 1,000,000 IDs that do not exist
   4.79 bits per item, k =  3, 1,000,000 inserted:    585 KB, false positives measured 10.119% | theory 10.083%
   9.59 bits per item, k =  7, 1,000,000 inserted:  1,171 KB, false positives measured  1.010% | theory  1.001%
  14.38 bits per item, k = 10, 1,000,000 inserted:  1,755 KB, false positives measured  0.100% | theory  0.100%

Designed for a 1% false positive rate, but more items inserted than designed for:
   9.59 bits per item, k =  7, 1,000,000 inserted:  1,171 KB, false positives measured  1.010% | theory  1.001%
   9.59 bits per item, k =  7, 2,000,000 inserted:  1,171 KB, false positives measured 15.732% | theory 15.720%
   9.59 bits per item, k =  7, 4,000,000 inserted:  1,171 KB, false positives measured 67.869% | theory 67.827%
  • A 1% false positive rate takes only about 9.6 bits per element: 1 million IDs take 1.1 MB, while a HashSet holding 1 million Longs takes tens of MB. Each 10x drop in the false positive rate costs about 4.8 more bits
  • Measurement and theory match almost exactly
  • Going past the designed capacity makes it degrade fast: put 2 million into a filter designed for 1 million, and the false positive rate jumps from 1% to 15.7%; put in 4 million and it reaches 68%, which makes the filter almost useless
  • No deletes: one bit may be shared by several elements, and clearing it would make other elements wrongly read as “definitely not there”. When you need deletes, rebuild periodically, switch to a counting Bloom filter, or switch to a Cuckoo filter

The code combines two hash values, h1 + i × h2, into k positions instead of actually computing k hashes. Kirsch and Mitzenmacher proved that this trick does not affect the false positive rate. The SSTables in the B-Tree vs LSM post also use Bloom filters to skip files that “definitely do not have this key”.

HyperLogLog: estimating counts from leading zeros

Imagine flipping a coin over and over: if someone tells you they once got 20 tails in a row, you would probably guess they flipped it a million times or more. HyperLogLog uses the same intuition to estimate the number of distinct elements:

  1. Hash each element first. The same element always has the same hash, so repeated elements do not affect the result
  2. The first 14 bits of the hash decide which of the 16,384 registers it belongs to
  3. Each register remembers only “the most leading zeros seen in the remaining bits of any hash”
  4. One register on its own has a large error, so the 16,384 registers are combined with a harmonic mean; for small counts it switches to linear counting

Redis implements exactly this: 16,384 6-bit registers, 12,288 bytes in total, with a standard error of 1.04 ÷ √16384 ≈ 0.81%. For small counts it starts with a sparse representation, which is even smaller. Implement a version with the same parameters:

Implementation and test (java HyperLogLogDemo.java)
java
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HyperLogLogDemo {

    static final int P = 14;                                        // 2^14 = 16,384 registers, same as Redis
    static final int M = 1 << P;
    static final double ALPHA = 0.7213 / (1 + 1.079 / M);

    static final class Hll {
        final byte[] registers = new byte[M];

        void addHash(long hash) {
            int index = (int) (hash >>> (64 - P));                  // the first 14 bits pick the register
            long rest = hash << P;
            int rank = Math.min(Long.numberOfLeadingZeros(rest), 64 - P) + 1;   // leading zeros in the remaining bits
            if (rank > registers[index]) {
                registers[index] = (byte) rank;
            }
        }

        long estimate() {
            double sum = 0;
            int zeros = 0;
            for (byte r : registers) {
                sum += 1.0 / (1L << r);
                if (r == 0) {
                    zeros++;
                }
            }
            double e = ALPHA * M * M / sum;                         // harmonic mean
            if (e <= 2.5 * M && zeros > 0) {
                e = M * Math.log((double) M / zeros);               // small counts: switch to linear counting
            }
            return Math.round(e);
        }

        void merge(Hll other) {
            for (int i = 0; i < M; i++) {
                registers[i] = (byte) Math.max(registers[i], other.registers[i]);
            }
        }
    }

    public static void main(String[] args) throws GeneralSecurityException {
        System.out.println("Estimation error (16,384 registers):");
        for (int n : new int[] {1_000, 100_000, 1_000_000, 10_000_000}) {
            Hll hll = new Hll();
            for (long id = 1; id <= n; id++) {
                hll.addHash(mix(id));
            }
            long estimate = hll.estimate();
            System.out.printf("  actual %,11d | estimate %,11d | error %+.2f%%%n", n, estimate, (estimate - n) * 100.0 / n);
        }

        Hll monday = new Hll();
        Hll tuesday = new Hll();
        for (long id = 1; id <= 6_000_000; id++) {
            monday.addHash(mix(id));
        }
        for (long id = 4_000_001; id <= 10_000_000; id++) {
            tuesday.addHash(mix(id));
        }
        monday.merge(tuesday);
        System.out.printf("%nMonday 6 million, Tuesday 6 million, 2 million came on both days: merged estimate %,d (actual 10,000,000)%n",
                monday.estimate());

        // The attacker knows the hash function and picks the visitor ID: work backward to IDs whose hashes have many leading zeros
        long[] crafted = new long[M];
        for (int j = 0; j < M; j++) {
            long wantedHash = ((long) j << (64 - P)) | (1L << 30);  // put a value with many leading zeros in every register
            crafted[j] = unmix(wantedHash);
        }
        Hll plain = new Hll();
        Hll keyed = new Hll();
        Mac hmac = Mac.getInstance("HmacSHA256");
        hmac.init(new SecretKeySpec("server-side-secret".getBytes(), "HmacSHA256"));
        for (long id : crafted) {
            plain.addHash(mix(id));
            keyed.addHash(ByteBuffer.wrap(hmac.doFinal(ByteBuffer.allocate(8).putLong(id).array())).getLong());
        }
        System.out.printf("%nThe attacker sends %,d crafted IDs:%n", M);
        System.out.printf("  public hash function: estimate %,d people%n", plain.estimate());
        System.out.printf("  HMAC with a server-side key first: estimate %,d people%n", keyed.estimate());
    }

    static long mix(long z) {
        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
        return z ^ (z >>> 31);
    }

    /** mix is invertible: given the hash you want, you can compute the input. */
    static long unmix(long z) {
        z = unxorshift(z, 31);
        z *= inverse(0x94d049bb133111ebL);
        z = unxorshift(z, 27);
        z *= inverse(0xbf58476d1ce4e5b9L);
        return unxorshift(z, 30);
    }

    static long unxorshift(long z, int shift) {
        long x = z;
        for (int i = 0; i <= 64 / shift; i++) {
            x = z ^ (x >>> shift);
        }
        return x;
    }

    static long inverse(long odd) {                                 // multiplicative inverse mod 2^64 (Newton's method)
        long x = odd;
        for (int i = 0; i < 6; i++) {
            x *= 2 - odd * x;
        }
        return x;
    }
}
text
Estimation error (16,384 registers):
  actual       1,000 | estimate       1,009 | error +0.90%
  actual     100,000 | estimate      99,786 | error -0.21%
  actual   1,000,000 | estimate     997,596 | error -0.24%
  actual  10,000,000 | estimate   9,921,965 | error -0.78%

Monday 6 million, Tuesday 6 million, 2 million came on both days: merged estimate 9,921,965 (actual 10,000,000)

The attacker sends 16,384 crafted IDs:
  public hash function: estimate 12,391,023,608 people
  HMAC with a server-side key first: estimate 16,282 people

(The last two lines of the output are explained in the security section.)

  • The error stays under 1%, whether the count is 1,000 or 10 million
  • Merging is lossless: when two HyperLogLogs are merged, each register takes the maximum. The estimate after merging Monday and Tuesday is exactly the same as counting 1 to 10 million directly, and the 2 million people who came on both days are not counted twice. This is why “unique visitors for any date range” can be computed by merging 7 daily keys
  • Adding the same element again does not change the result: a visitor who refreshes 100 times gives the same result, so retries are safe (idempotency is covered in detail in Part 5)

What it cannot do: list the members, delete a member, or compute an exact intersection (subtracting with the inclusion-exclusion principle amplifies the error).

Other probabilistic data structures

Question Data structure Error behavior
Is it there? Bloom filter, Cuckoo filter (supports deletes) Only false “it’s there” answers
How many distinct? HyperLogLog About ±0.81% (16,384 registers)
How many times does an element appear? Count-Min Sketch Only overestimates, never underestimates
Top K most frequent Top-K Approximate
Quantiles (e.g. p99) t-digest Approximate, more accurate at the tails

Besides HyperLogLog, Redis also offers Bloom filters, Cuckoo filters, Count-Min Sketch, Top-K, and t-digest as probabilistic data types. Top-K can find hot keys (the caching post); t-digest can compute p99 (the latency post).

Comparing options

Exact set (Set) Bloom filter HyperLogLog
Question it answers Is it there, how many, which ones Is it there How many
Memory Grows with the number of elements About 10 bits per element (1% false positives) Fixed, at most 12 KB
Error None Only false “maybe there” answers About ±1%
Delete Yes No (a Cuckoo filter can) No
List members Yes No No
Merge A union has to read out every element Filters of the same size can be ORed Max of each register, lossless

Ways to stop cache penetration:

Parameter validation Caching empty results Bloom filter
Stops Malformed and out-of-range IDs Repeated nonexistent IDs All nonexistent IDs (about 1% slip through)
Cost Almost none Takes cache space; an empty result cached before a new product launches lasts until its TTL expires Needs maintenance and rebuilds

The three stack: validate parameters first, then ask the Bloom filter, and only then check the cache and the database.

In Java

1. Blocking nonexistent product IDs

java
package catalog;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import java.util.function.Supplier;
import java.util.stream.LongStream;

/**
 * Blocks product IDs that "definitely do not exist" in front of the cache.
 * It only mistakes a missing ID for "might exist", at the cost of one extra cache or database lookup; it never blocks a product that exists.
 */
public final class ProductExistenceFilter {

    private record Snapshot(BloomFilter<Long> filter, long maxId) {}

    private volatile Snapshot snapshot;

    /** Rebuild periodically (every 10 minutes, say) from all product IDs in the database. A Bloom filter cannot delete, so removed products drop out on rebuild. */
    public void rebuild(Supplier<LongStream> allIds, long expectedCount) {
        BloomFilter<Long> filter = BloomFilter.create(Funnels.longFunnel(), Math.max(expectedCount * 2, 1_000), 0.01);
        long[] maxId = {Long.MIN_VALUE};
        allIds.get().forEach(id -> {
            filter.put(id);
            maxId[0] = Math.max(maxId[0], id);
        });
        snapshot = new Snapshot(filter, maxId[0]);                // swap the whole thing; readers need no lock
    }

    public boolean mightExist(long productId) {
        Snapshot current = snapshot;
        // A product added after the rebuild is not in the filter, but its ID is always above maxId, so it must not be treated as missing
        return productId > current.maxId() || current.filter().mightContain(productId);
    }
}

Checked with 1 million products (IDs are multiples of 7, to simulate gaps between IDs):

text
Existing products blocked: 0
Nonexistent IDs let through: 1,529 / 6,000,000 (0.025%)
ID 7000007, added after the rebuild: let through
  • Size it at twice the count: set the expectedInsertions of BloomFilter.create to twice the current count, so the filter does not degrade sharply like in the earlier measurement as the number of products keeps growing. With 1 million actually inserted, the false positive rate is only 0.025%
  • Rebuild instead of delete: a removed product disappears from the filter only at the next rebuild. Until then it is just “might exist” and costs one extra database lookup; correctness is not affected
  • maxId handles products added after the rebuild: this is the only direction in which a Bloom filter can go wrong. If the filter is missing an element that exists (a product added after the rebuild, say), it answers “definitely does not exist”, and a real product becomes a 404. Product IDs increase over time (IDENTITY, or time-ordered distributed IDs), so any ID above maxId is let through, and machines that each rebuild on their own do not need to sync with each other. This trick does not work if IDs are random UUIDs; instead, publish an event when a product is added, so every machine adds it to its filter

2. Unique visitors on talk pages

java
package stats;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.util.HexFormat;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.data.redis.core.StringRedisTemplate;

/** Daily unique visitors on talk pages. Each key is at most 12 KB, however many visitors there are. */
public class UniqueVisitorCounter {

    private final StringRedisTemplate redis;
    private final SecretKeySpec hashKey;                              // injected from the secrets manager, never written in the code

    public UniqueVisitorCounter(StringRedisTemplate redis, byte[] secret) {
        this.redis = redis;
        this.hashKey = new SecretKeySpec(secret, "HmacSHA256");
    }

    public void record(long lectureId, String visitorId, LocalDate day) {
        String key = key(lectureId, day);
        redis.opsForHyperLogLog().add(key, keyedHash(visitorId));
        redis.expire(key, 400, TimeUnit.DAYS);
    }

    public long count(long lectureId, LocalDate day) {
        return redis.opsForHyperLogLog().size(key(lectureId, day));
    }

    /** PFCOUNT over several keys gives the union: a visitor who came on several days counts once. */
    public long countBetween(long lectureId, LocalDate from, LocalDate to) {
        String[] keys = from.datesUntil(to.plusDays(1)).map(day -> key(lectureId, day)).toArray(String[]::new);
        return redis.opsForHyperLogLog().size(keys);
    }

    /** {lecture:42} is a hash tag: all keys for one talk land in the same cluster slot, so multi-key commands can run. */
    private static String key(long lectureId, LocalDate day) {
        return "uv:{lecture:" + lectureId + "}:" + day;
    }

    /** The visitor ID comes from the client; HMAC it with a server-side key first, so an attacker cannot choose the hash. */
    private String keyedHash(String visitorId) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");                 // Mac is not thread-safe; create one per call
            mac.init(hashKey);
            byte[] digest = mac.doFinal(visitorId.getBytes(StandardCharsets.UTF_8));
            return HexFormat.of().formatHex(digest, 0, 16);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
}
  • One key per talk per day: for UV over any range, run PFCOUNT on several keys together to get an estimate of the union, with no separate weekly or monthly stats to store
  • hash tag: multi-key commands in Redis Cluster require all keys to be in the same slot; {lecture:42} keeps one talk’s keys together
  • HMAC: the reason is in the security section

Pitfalls and gotchas

  • Building a Bloom filter without estimating capacity: once the number of elements reaches twice the designed capacity, a 1% false positive rate becomes 15.7%
  • Assuming a Bloom filter can delete: clearing a bit turns the elements that share it into “definitely not there”, an error that could never happen otherwise
  • A Bloom filter missing elements: data skipped during a rebuild, or new elements never added, both make things that exist read as absent. This is the only way a false negative can happen, and it is far worse than a false positive
  • Using HyperLogLog for intersections, or to find out “who”: it can only answer how many
  • Multi-key PFCOUNT and PFMERGE in Redis Cluster: keys in different slots fail with an error right away; use a hash tag
  • Using an estimate where you need an exact number: settling ad fees or handing out rewards by UV turns an error of about 1% into a dispute over money. These cases need exact counts or auditable records
  • Underestimating 12 KB: one key per product, per day, per dimension: 1 million products × 365 days × 12 KB is about 4.5 TB (worst case; low-traffic keys use the sparse representation and are much smaller). Design the key dimensions, and set a TTL on old data

Security

  • The estimate can be inflated: a HyperLogLog estimate depends entirely on the leading zeros of the hashes. If the hash function is public (the Redis implementation’s source code is open) and the client decides the elements (the visitor ID of a visitor who is not logged in, for example), an attacker can pick elements whose hashes have unusually many leading zeros. In the measurement above, the attacker sent only 16,384 requests and pushed the estimate to 12.4 billion; with an HMAC under a server-side key applied before adding, the attacker cannot control the hash, and the estimate goes back to 16,282. Once UV affects trending rankings, recommendations, or rewards, inflating it is fraud. The countermeasures are HMAC, visitor IDs issued by the server (a signed cookie), plus rate limiting
  • Bloom filters can be manipulated too: if an attacker can decide which elements get added, they can pick elements that set many different bits and push the false positive rate up until the filter stops working (pollution); if they know the hash function, they can also compute elements that will be wrongly reported as “maybe there”. The product filter in this post holds only IDs from the database, so attackers cannot add elements and the risk is lower; when elements come from users, add a server-side key or a random seed to the hash, and monitor what fraction of the bits is set
  • Do not use a Bloom filter for an “allow” decision: for example, storing a JWT revocation list in a Bloom filter and letting a token through because it is “not on the list”. If the filter misses even one entry (sync lag, a failed rebuild), a revoked token gets through; in the other direction, false positives get legitimate users’ tokens rejected. It only fits as a fast path: when a token “might be revoked”, check the authoritative source (token revocation is covered in detail in Part 8)
  • Hashed data can still be personal data: Bloom filters and HyperLogLog store hashes, which do not look like personal data; but when the hash function is public, anyone who gets the structure can test, one by one, whether “a given email is in it”. Before exporting it or sharing it with a third party, still treat it as personal data; a keyed hash also lowers the risk

When to use it, and when not to

  • Bloom filter: when “definitely not there” saves an expensive operation (disk, network, database), and a false positive only costs one extra check. For example, LSM SSTables, cache penetration, a crawler checking whether a URL was already fetched, and excluding already-seen products from recommendations
  • HyperLogLog: distinct counts over large amounts of data where about 1% error is acceptable. For example, UV, distinct search keywords, and how many different ports one IP has connected to (to detect scanning)
  • Do not use them: when you need exact values (payments, billing, inventory), when you need to list or delete members, or when the data is small enough to fit in a HashSet

References

Comments