Sub topic 2
Hashing items into uniform random bits
This chapter assumes you know basic Python, how integers look in binary, and what a hash function does at a conceptual level. HyperLogLog never looks at your items directly. It looks only at their hashes, so the quality of the hash decides whether the later estimates are trustworthy.
Why HyperLogLog hashes first
Real items are strings, user IDs, or URLs, and they are rarely random. Sequential IDs such as user-1, user-2, user-3 share long prefixes. If the sketch read those bits directly, the patterns it relies on would follow your data's structure instead of chance.
A hash function fixes this. It maps any item to a fixed-size integer, here 64 bits. A good hash has three properties that matter for HyperLogLog:
- Deterministic: the same item always produces the same hash. Duplicates therefore collapse to one value, which is how the sketch ignores repeats.
- Uniform: each of the 64 bits is 0 or 1 with probability 1/2.
- Independent: knowing some bits of a hash tells you nothing about the others.
Together these mean that distinct items behave like independent random 64-bit strings. The next chapter uses this: the chance that a hash starts with k zero bits is exactly 2^-k.
Checking uniformity yourself
You can test a hash by hashing many items and measuring how often each bit position is 1. This is the same hash function the implementation chapter uses: SHA-1, truncated to its first 8 bytes.
import hashlib
def hash64(item):
digest = hashlib.sha1(item.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big")
N = 20_000
ones = [0] * 64
for i in range(N):
x = hash64(f"user-{i}")
for bit in range(64):
if (x >> (63 - bit)) & 1:
ones[bit] += 1
for bit in (0, 1, 2, 31, 63):
print(f"bit {bit}: {ones[bit] / N:.3f}")Every printed fraction should be close to 0.500, typically within about 0.01. The input strings are perfectly sequential, yet the output bits look like coin flips. Bit 0 is the most significant bit, so this also shows that the leading bits are well mixed.
A bad hash: Python's built-in `hash`
Python's hash() is tempting but wrong for this job. Test it on small integers:
MASK = (1 << 64) - 1
for i in (1, 2, 3, 1000):
x = hash(i) & MASK
print(f"{x:064b}")For integers, hash(i) returns i itself. Every output starts with dozens of zeros, so the leading bits carry no randomness. A sketch fed these values would see the same "rare" pattern for every item and badly overestimate.
There is a second problem. For strings, hash() is salted per process (controlled by PYTHONHASHSEED). Two machines, or two runs, hash the same string differently. Sketches built in separate processes could then never be merged, because the same user would look like different items.
Choosing a hash in practice
Use a hash that is well mixed, stable across processes, and wide enough. The table compares common choices.
| Hash | Stable across runs | Good bit mixing | Notes |
|---|---|---|---|
| Python `hash()` | No for strings | No for integers | Do not use |
| SHA-1 / SHA-256 (`hashlib`) | Yes | Yes | Slow, but fine for learning and moderate volumes |
| MurmurHash3, xxHash | Yes | Yes | Fast non-cryptographic choices used in production |
You don't need a cryptographic hash. You only need uniform, independent-looking bits. Speed matters more at high volume, because every item is hashed once.
Why 64 bits
The sketch consumes the hash in two parts. The first p bits choose a register. The remaining 64 − p bits are searched for the first 1-bit. With p = 12, that leaves 52 bits, enough to represent ranks far beyond any real cardinality. A 32-bit hash would leave only 20 bits, and the sketch would saturate near a billion distinct items. This is one reason production variants moved to 64-bit hashes, as a later chapter explains.
What can still go wrong
- Different encodings:
"café"encoded as UTF-8 and as Latin-1 gives different hashes. Encode consistently everywhere sketches might be merged. - Normalization:
"Alice"and"alice"are different items to a hash. Decide what counts as the same item before hashing. - Poor hash functions: weak mixing skews the bit statistics, and the error stays above the theoretical figure.
Exercise
You run a distinct-user count on two servers, each using Python's built-in hash() on string user IDs, and merge the two sketches. Give two reasons the merged count can be wrong.
Show answer
First, hash() on strings is salted per process, so the same user ID produces different hashes on the two servers. The merge then counts that user as two different items and overestimates the union. Second, hash() is not designed for well-mixed bits, and for integer inputs it returns the value itself, so the leading bits are not uniform. Use a stable, well-mixed hash such as MurmurHash3 or a truncated SHA-1 on every server.