Algorithms · Counting & data
Bloom filter
How Chrome checked millions of bad links without downloading them. A list that can say “definitely not” instantly, and only sometimes says “maybe”.
The problem
You click a link. Before the page loads, your browser should know whether it's a known phishing or malware site. The list of known-bad URLs is huge and keeps changing.
Asking Google's servers about every link would be slow, and it would mean telling a server every page you visit. Chrome's Safe Browsing wanted to answer most checks locally, on your own machine.
The obvious way
Ship the browser a plain list of every bad URL and look each link up. It works, but every URL is a long string, so the list grows with the number of bad sites. Millions of strings means a big download, big memory use, and constant updates, all on your laptop or phone.
The clever idea
Picture a wall of light switches, all off. To remember a bad URL, you don't write it down. You run it through three scrambling machines, and each one tells you a switch to flip on. To check a new URL, run the same three machines: if all three switches are on, it's maybe bad. If even one is off, it's definitely not on the list.
Different URLs can accidentally flip overlapping switches, which is where false positives come from. But a bad URL always flips its own three, so the filter never misses one (no false negatives). On a "maybe", Chrome asks Google's servers to be sure. Burton Bloom invented this in 1970.
How the code does it
The hash step turns a URL into three positions between 0 and 511. Adding a URL just switches those three bits on, and checking asks whether all three are on. Nothing about the URL itself is stored.
Run it and look at the grid: the lit cells are the filter's whole memory. Then compare the exact list, which finds no false alarms, with the filter, which may flag a few good URLs. The last bar chart shows what that buys: 512 bits against thousands for the raw strings.
Trade-offs
You pay with certainty: false positives happen, and the more items you add to a fixed array, the more bits are on and the more often they happen. You can't list what's inside, and you can't easily remove an item, since its bits may be shared. Don't use one when a wrong 'yes' is costly and there's no cheap way to double-check.
Where else you'll see it
Databases like Apache Cassandra and Google Bigtable use Bloom filters to skip disk reads for keys that aren't there. A quick 'definitely not' saves a slow trip to disk, the same way it saved Chrome a trip to the server.
maybe_bad(url) returns False. What do you know for sure?
- The URL was definitely never added
- The URL is probably safe, but unsure
- The URL was added, but hashed badly
Show the answer
The URL was definitely never added. At least one of its three bits is off. Adding the URL would have switched all three on, so it can't have been added.
- Change M from 512 to 128
- Change K from 3 to 1
- Raise range(50) to range(150)
The code
Python, with what each line means beside it. It compares the clever way with a plain list of every URL.
import hashlibBorrow tools for hashingimport randomBorrow tools for randomness M, K = 512, 3 # bits in the filter, number of hash functionsPick 512 bits and 3 hash functionsbits = [0] * MStart with every bit switched off def spots(url):Define: where does a URL point? # K positions in the bit array for this URLThree positions come from three hashes return [int(hashlib.sha256(f"{i}:{url}".encode()).hexdigest(), 16) % MHash the URL with a number prefix for i in range(K)]Do that once per hash function def add(url):Define: remember a bad URL for s in spots(url):Visit each of its three spots bits[s] = 1Switch that bit on def maybe_bad(url):Define: is this URL maybe bad? return all(bits[s] for s in spots(url))Yes only if all three bits are on random.seed(7)Fix the randomness so results repeatbad = [f"evil{n}.example/login" for n in range(50)]Make 50 fake bad URLsgood = [f"site{random.randint(0, 10**6)}.example/home" for _ in range(200)]Make 200 random good URLs for url in bad:Go through each bad URL add(url)Add it to the filter # obvious way: scan the full list of stringsObvious way: scan the full listexact = sum(u in bad for u in good)Count good URLs wrongly found in listfooled = sum(maybe_bad(u) for u in good)Count good URLs the filter flagsmissed = sum(not maybe_bad(u) for u in bad)Count bad URLs the filter misses print("Obvious list false alarms:", exact)Report the list's false alarmsprint("Bloom false positives:", fooled, "of 200")Report the filter's false positivesprint("Bloom misses of real bad URLs:", missed)Report misses, which should be zeroshow([bits[r*32:(r+1)*32] for r in range(M // 32)], "Bloom bit array")Draw the bit array as a gridlist_bits = sum(len(u) for u in bad) * 8Count bits needed to store raw stringsshow([list_bits, M], "bits used: full list vs Bloom filter")Compare memory in a bar chart- three hashes from one lines 9–10Prefixing the URL with 0, 1, 2 makes SHA-256 act like three different hash functions. The modulo squeezes each into 0–511.
- all, not any line 17One off bit proves the URL was never added. Only all three on means 'maybe', so a wrong yes is possible, a wrong no never.
- the exact way line 27Scanning the real strings is never wrong, which is why it's the baseline. The cost shows up in the memory chart.
- no false negatives line 29Every bad URL set its own bits, so this count is always 0.
Read more
- en.wikipedia.org: Bloom filter
- Ask Bento: How do I pick M and K?
- Ask Bento: Can a Bloom filter delete items?
- Ask Bento: What is a hash collision?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.