What it is
A hash index is an array of buckets plus a hash function. To store or find a key, the database hashes it, takes the result modulo the number of buckets, and goes straight to that bucket, which holds the key and a pointer to its row or value. Lookups by exact key cost O(1) on average, independent of the table size.
Why it exists
A B-tree lookup reads one page per level; a hash lookup computes the location directly. For workloads that only ever ask "give me the value for this exact key" — session stores, caches, key-value engines, the build side of a hash join — that is the cheapest possible access path, and it needs no ordering work on insert.
How it works
Hashing. A good hash function spreads keys uniformly and unpredictably. Many implementations use a keyed (seeded) function such as SipHash so that an attacker cannot craft many keys that collide (hash-flooding).
Collisions. Different keys can land in the same bucket. Chaining keeps a small list per bucket; open addressing (linear probing, Robin Hood hashing, cuckoo hashing) puts the second key in another slot of the same array. Either way a lookup compares keys until it finds the right one.
Load factor. keys ÷ buckets. Implementations resize when it crosses a threshold — Java's HashMap at 0.75, Redis dictionaries at about 1 (or later, while a background save is running) — so average chains stay short.
Resizing. Doubling the bucket count changes hash mod n for most keys, so entries must be rehashed into the new array. Done all at once, the pause is proportional to the table size. Redis keeps the old and new tables side by side and moves a few buckets per operation (plus in a background cron step); lookups check both tables until the move completes. Database hash indexes use schemes that split one bucket at a time: linear hashing (PostgreSQL's hash index) and extendible hashing.
No order. Neighbouring keys hash to unrelated buckets. Nothing in the structure says what "the next key" is, so ranges, ORDER BY, MIN/MAX and prefix matches must scan everything.
Log-structured stores (Bitcask). Riak's Bitcask engine writes every put as a record appended to the active data file; files are never modified in place. An in-memory hash table, the keydir, maps each key to the file, offset and size of its latest record. A get is one hash lookup in memory plus one disk read. Old versions and deleted keys (tombstones) are removed by a background merge that rewrites closed files keeping only live records. After a crash the keydir is rebuilt by scanning the files, sped up by hint files written during merges. The design gives very fast writes and predictable reads, at the price of keeping every key in RAM and having no range queries.
When to use it
- In-memory key-value stores and caches (Redis, Memcached): the main dictionary is a hash table.
- Log-structured engines where all keys fit in memory and access is by key (Bitcask and similar).
- Equality-only lookups on long keys (URLs, tokens), where a PostgreSQL hash index stores only a 4-byte hash per entry and can be smaller than a B-tree.
- Inside query engines: hash joins and hash aggregation build temporary hash tables.
When not to
- Any query with ranges, sorting, prefixes or "latest N".
- Composite keys queried by a leading column only: a hash of (a, b) is useless for
WHERE a = ?. - Columns where a B-tree already exists: it serves equality nearly as well.
- Very large key sets that do not fit in memory, for Bitcask-style designs.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Hash index instead of B-tree | O(1) equality, possibly smaller for long keys | No ranges, sorting, prefixes or partial-key use |
| Lower load factor | Shorter chains, faster lookups | More memory |
| Stop-the-world resize | Simple implementation | Latency spike proportional to table size |
| Incremental resize | No pause | Two tables during the move; lookups check both |
| Append-only log + keydir | Sequential writes, one seek per read | All keys in RAM; compaction work |
Alternatives
- B-tree indexes: equality plus ranges and order; the default in relational databases.
- LSM trees (RocksDB, Cassandra): append-only writes like Bitcask, but sorted files, so ranges work and keys need not fit in memory.
- Consistent hashing: the same hashing idea applied to spreading keys over machines instead of buckets.
- Bloom filters: a hashed structure answering "definitely not present" cheaply, used alongside LSM trees.
Failure modes
- Range queries on a hash-only column silently become full scans.
- Resize pauses on large in-memory tables.
- Hash flooding: crafted keys that collide, turning O(1) into O(n), when the hash function is unseeded.
- Memory exhaustion in keydir-style stores when the number of keys grows beyond RAM.
- Slow recovery when the in-memory index must be rebuilt from large logs without hint files or snapshots.
- Compaction debt: if merges fall behind, disk usage grows with every update.
In production
In relational databases, use B-trees by default and add a hash index only for a measured equality-only hot path (PostgreSQL hash indexes are WAL-logged and crash-safe since version 10). In Redis, watch memory and avoid huge single keys whose operations or deletes block the server. For log-structured stores, monitor key count against RAM, disk usage against live data, and compaction progress; keep hint files or snapshots so restarts are fast.
Common misconceptions
- "Hash lookups are always O(1)." On average, with a bounded load factor and a good hash function. Worst case is O(n).
- "A hash index is always faster than a B-tree." For equality the difference is often small, since B-tree top levels are cached; for everything else the hash index loses completely.
- "More buckets make lookups faster." Only if chains were long; beyond that they cost memory.
- "Append-only means the disk fills up forever." Compaction reclaims superseded and deleted records.
Interview angle
When you design a key-value store or cache, a hash table is the obvious index: say O(1) equality, mention the load factor, and explain how you resize without a pause. Interviewers often follow with "now the product wants range queries" (switch or add an ordered index or an LSM-based engine) or "the keys no longer fit in memory" (Bitcask's limit; move to an LSM tree). Knowing the Bitcask design — append-only log, in-memory keydir, merge, hint files — is a compact way to show you understand storage engines.
Model assumptions
The hash table (hash function, buckets, overflow chain) and the Bitcask store (keydir, segments, merge) are scripted illustrations: scenery nodes and moving packets, not simulated. The live traffic is simulated with a cost model on one database with 10 connections: a hash lookup costs about 1 ms (lognormal, cv 0.3), and queries waiting more than 300 ms for a connection fail. The stop-the-world rehash is a 600 ms period in which every query is 100 times slower; the incremental rehash is 3 s at 1.5 times slower. The engine has one read cost per database, so the mixed workload with range queries uses an average cost (32 ms: 1 ms lookups mixed with roughly 150 ms full scans), and the B-tree fix lowers that average to 1.5 ms. Numbers are illustrative, not benchmarks.