Sometimes you need to ask “have I seen this before?” about millions of items, using very little memory. A Bloom filter answers with a bit array and a few hash functions. Its answers are either “definitely not” or “probably yes”. It never forgets something it has seen, but it can occasionally say yes for something it has not: a false positive. In exchange, it uses a small fraction of the memory a hash table would. Web browsers have used Bloom filters to check unsafe-site lists, and databases use them to skip disk reads.
In this lesson you will learn
- How a Bloom filter sets and checks bits
- Why there are false positives but no false negatives
- Building k hash functions from two with double hashing
- The false positive formula and choosing m and k
- When a Bloom filter is the right tool
You should know hashing and bit manipulation.
A Tiny Bloom Filter
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#define M 32 /* number of bits (tiny, to show a false positive) */
#define K 3 /* number of hash functions */
uint64_t bits = 0; /* all M bits fit in one integer */
/* FNV-1a string hash, with a different starting value for each of the K hashes */
uint32_t hash(const char *s, uint32_t seed) {
uint32_t h = 2166136261u ^ seed;
for (; *s; s++) { h ^= (unsigned char)*s; h *= 16777619u; }
return h;
}
void add(const char *s) {
printf("add %-10s sets bits:", s);
for (uint32_t i = 0; i < K; i++) {
unsigned b = hash(s, i * 0x9e3779b9u) % M;
bits |= (uint64_t)1 << b;
printf(" %2u", b);
}
printf("\n");
}
/* false = definitely not added; true = probably added */
bool mightContain(const char *s) {
for (uint32_t i = 0; i < K; i++)
if (!(bits & ((uint64_t)1 << (hash(s, i * 0x9e3779b9u) % M)))) return false;
return true;
}
int main(void) {
const char *added[] = { "dhaka", "sylhet", "khulna", "barishal", "rangpur" };
for (int i = 0; i < 5; i++) add(added[i]);
const char *queries[] = { "sylhet", "rangpur", "comilla", "bogura", "feni", "kishoreganj" };
for (int i = 0; i < 6; i++)
printf("%-11s -> %s\n", queries[i],
mightContain(queries[i]) ? "probably present" : "definitely absent");
return 0;
}
Output
add dhaka sets bits: 16 11 18
add sylhet sets bits: 4 9 18
add khulna sets bits: 6 19 8
add barishal sets bits: 31 14 21
add rangpur sets bits: 18 13 16
sylhet -> probably present
rangpur -> probably present
comilla -> definitely absent
bogura -> definitely absent
feni -> definitely absent
kishoreganj -> probably present
- The filter is just m bits, all 0 at first. Here m = 32, small enough to fit in one integer.
- Add: hash the item with k different hash functions (k = 3 here) and set those k bits to 1.
- Check: hash the item the same way. If any of its k bits is 0, the item was definitely never added. If all are 1, it was probably added.
- Added items always find all their bits set, so there are no false negatives.
- “kishoreganj” was never added, but its three bits happen to have been set by other words, so the filter wrongly says “probably present”. That is a false positive. With only 32 bits for 5 words, the filter is crowded on purpose to show this.
- You cannot delete an item: clearing its bits could also clear bits that other items need.
Sizing a Real Filter
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
/* A bigger Bloom filter, with false positives measured against theory */
typedef struct { uint8_t *bits; size_t m; int k; } Bloom;
static uint64_t mix(uint64_t x) { /* splitmix64: spreads bits well */
x += 0x9e3779b97f4a7c15ull;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebull;
return x ^ (x >> 31);
}
/* Double hashing: K positions from just two hash values, h1 + i*h2 */
void bloomAdd(Bloom *b, uint64_t key) {
uint64_t h1 = mix(key), h2 = mix(h1) | 1;
for (int i = 0; i < b->k; i++) {
size_t pos = (h1 + (uint64_t)i * h2) % b->m;
b->bits[pos / 8] |= (uint8_t)(1u << (pos % 8));
}
}
int bloomHas(const Bloom *b, uint64_t key) {
uint64_t h1 = mix(key), h2 = mix(h1) | 1;
for (int i = 0; i < b->k; i++) {
size_t pos = (h1 + (uint64_t)i * h2) % b->m;
if (!(b->bits[pos / 8] & (1u << (pos % 8)))) return 0;
}
return 1;
}
int main(void) {
const int n = 10000; /* items we will add */
size_t sizes[] = { 40000, 100000, 200000 };
printf("%8s %3s %12s %12s %10s\n", "bits(m)", "k", "measured FP", "theory FP", "bytes");
for (int s = 0; s < 3; s++) {
size_t m = sizes[s];
int k = (int)round((double)m / n * log(2.0)); /* best number of hashes */
Bloom b = { calloc((m + 7) / 8, 1), m, k };
if (!b.bits) return 1;
for (int i = 0; i < n; i++) bloomAdd(&b, (uint64_t)i); /* keys 0..9999 */
int fp = 0, tests = 100000;
for (int i = 0; i < tests; i++) fp += bloomHas(&b, 1000000 + (uint64_t)i); /* never added */
double theory = pow(1 - exp(-(double)k * n / m), k);
printf("%8zu %3d %11.2f%% %11.2f%% %10zu\n", m, k, 100.0 * fp / tests, 100 * theory, (m + 7) / 8);
free(b.bits);
}
printf("Storing 10000 eight-byte keys directly would need 80000 bytes.\n");
return 0;
}
Output
bits(m) k measured FP theory FP bytes
40000 3 14.94% 14.69% 5000
100000 7 0.80% 0.82% 12500
200000 14 0.01% 0.01% 25000
Storing 10000 eight-byte keys directly would need 80000 bytes.
- Double hashing creates k positions from just two hash values:
h1 + i × h2. This works almost as well as k independent hash functions and is much cheaper. - The best number of hash functions is about
k = (m / n) × ln 2, where n is the number of items. Too few hashes check too few bits; too many fill the array too quickly. - The expected false positive rate is about
(1 - e-kn/m)k. The measured rates match this formula closely. - With 20 bits per item (25,000 bytes), only about 1 in 10,000 lookups is a false positive. Storing the 10,000 keys themselves would need 80,000 bytes, and a hash table even more.
| Bits per item (m / n) | Best k | False positive rate |
|---|---|---|
| 4 | 3 | about 15% |
| 8 | 6 | about 2% |
| 10 | 7 | about 0.8% |
| 20 | 14 | about 0.01% |
When to Use One
Use a Bloom filter as a fast first check before an expensive step. A database can check the filter before reading a file from disk: a “definitely not” skips the disk read completely, and a rare false positive only costs one wasted read. Do not use it when a wrong “yes” would cause real harm, or when you need to list or delete the stored items.
Common Mistakes
- Trusting a “yes” without a follow-up check when correctness matters.
- Using hash functions that are not independent, such as the same function k times, which sets the same bit repeatedly.
- Adding far more items than planned. The false positive rate rises quickly once the filter fills up.
- Trying to delete by clearing bits, which can create false negatives. Use a counting Bloom filter if you need deletion.
Practice Exercises
Exercise 1. You expect 1 million items and can spend 1.2 MB on the filter. How many bits per item is that, and roughly what false positive rate should you expect?
Show answer
1.2 MB is about 9.6 million bits, so about 9.6 bits per item. From the table, that gives roughly a 1% false positive rate, with k = 7.
Exercise 2. Why can a Bloom filter never give a false negative?
Show answer
Adding an item sets its k bits to 1, and bits are never changed back to 0. When the same item is checked later, it hashes to the same k bits, which are all still 1.
Frequently Asked Questions
How is a Bloom filter different from a hash set?
A hash set stores the items themselves, so it gives exact answers and can list and delete items. A Bloom filter stores only bits, so it uses much less memory but can only answer “definitely not” or “probably yes”.
What is a counting Bloom filter?
It replaces each bit with a small counter. Adding increases the k counters and deleting decreases them, so items can be removed. The cost is several times more memory.
Summary
- A Bloom filter sets k bits per item in an m-bit array.
- Answers are “definitely not” or “probably yes”: false positives are possible, false negatives are not.
- About 10 bits per item with k = 7 gives roughly a 1% false positive rate.
- It is ideal as a cheap first check in front of slow storage.
