Course contents

04. Database Fundamentals Lesson 5 of 10

Hash Indexes

How hash indexes give O(1) lookups, why they cannot do ranges, how collisions and resizing work, and how Bitcask pairs a hash index with an append-only log.

14 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A hash index computes a key’s bucket instead of searching for it: O(1) equality lookups on average.
  • Hashing destroys key order, so ranges, sorting and prefixes cannot use it.
  • Collisions are normal; a bounded load factor keeps chains short.
  • Growing the table means rehashing; doing it incrementally avoids a stop-the-world pause.
  • Bitcask-style stores pair an append-only log with an in-memory hash of every key; compaction reclaims space.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. A key, a hash, a bucket

    A hash index keeps an array of buckets. To store or find a key, the database runs it through a hash function, which turns any key into a number, and takes that number modulo the bucket count: hash("user:42") mod 4 = 2. Bucket 2 holds the entry: the key and where its row lives.

    The hash function scatters keys pseudo-randomly, so similar keys land in unrelated buckets. That is what spreads them evenly, and, as we will see, what rules out range queries. (Scripted illustration; the 300 lookups per second behind it are simulated at about 1 ms each.)

    Scene: Illustration: the database hashes the key user:42, the hash modulo 4 is 2, and bucket 2 returns the row location. Behind it, the app sends 300 simulated lookups per second.

    Key idea: A hash index computes where a key lives instead of searching for it.

  2. 2. Constant-time point lookups

    Every lookup is the same two steps: hash the key, read one bucket. It does not matter whether the index holds a thousand keys or a billion: as long as buckets stay short, the cost is O(1), and there is no tree to descend.

    The packets show four lookups landing in four different buckets, each in two hops. The simulated traffic agrees: 300 lookups per second keep the database almost idle, with P95 a few milliseconds, mostly network.

    Scene: Illustration: four lookups, each hashing its key and reading exactly one bucket. The simulated database serves 300 lookups per second with a P95 of a few milliseconds and is almost idle.

    Key idea: Hash lookups cost the same at any size, as long as buckets stay short.

  3. 3. Collisions and load factor

    With more keys than buckets, some keys must share: user:42 and user:977 both hash to bucket 2. The bucket keeps a short chain (or, in open addressing, the second key goes to the next free slot). A lookup for user:977 reads bucket 2, compares keys, and follows the chain to the overflow entry: one extra step.

    The average chain length is the load factor: keys ÷ buckets. Implementations keep it bounded (Java’s HashMap resizes at 0.75, Redis around 1) so lookups stay O(1) on average. A bad hash function, or keys chosen by an attacker, can pile many keys into one bucket; that is why modern implementations use seeded hash functions such as SipHash. (Scripted illustration.)

    Scene: Illustration: user:977 hashes to bucket 2, which already holds user:42. The lookup compares keys and follows the chain to an overflow entry, one extra step.

    Key idea: Collisions are normal; a bounded load factor keeps chains short and lookups O(1) on average.

  4. 4. Growing the table: rehash everything

    The table keeps growing and the load factor passes its limit, so the index doubles to 8 buckets. The bucket for a key is hash mod 8 now, so every key may move: all entries must be rehashed and copied.

    Done all at once, that is a pause proportional to the table size. One second in, a 600 ms rehash starts; in this model every lookup during it is about 100 times slower. Connections fill up, P95 jumps from a few milliseconds to hundreds, and lookups that wait too long fail. After the rehash, lookups are fast again.

    Scene: The table doubles to eight buckets and every key is rehashed at once. From 1.0 to 1.6 seconds lookups are very slow: connections fill up, latency spikes and some lookups fail. Afterwards they are fast again.

    Key idea: Hash tables must resize as they grow; a stop-the-world rehash turns into a latency spike.

  5. 5. Rehash a little at a time

    Redis does it differently: during a resize it keeps both tables, and every operation moves a few buckets from the old table to the new one (plus a background step when idle). Lookups check the new table, then the old one, so they are slightly slower, but only for the duration of the migration, and nothing pauses.

    Here the same resize runs incrementally from 1 s to 4 s, with lookups about 1.5 times slower. P95 barely moves and nothing fails. Linear hashing and extendible hashing, used by some databases, achieve the same by splitting one bucket at a time.

    Scene: The same resize, done incrementally between 1 and 4 seconds. Buckets move one at a time; lookups are slightly slower meanwhile, latency barely changes and nothing fails.

    Key idea: Spread the rehash over many operations: a small, long slowdown instead of a spike.

  6. 6. A hash index cannot do ranges

    A new admin page asks for WHERE id BETWEEN 1000 AND 2000 and ORDER BY id, 80 times per second from 1 s on. Keys 1000 and 1001 hash to unrelated buckets, so the hash index has no idea where "the next key" is. The database can only scan everything (the packets visit every bucket).

    Each range query is a full scan, about 150 ms here. Averaged with the 1 ms lookups, the workload’s query cost rises from 1 ms to about 32 ms: more work than 10 connections can do, so every query, lookups included, starts to wait and some fail.

    Scene: An admin page starts sending 80 range queries per second. The hash index cannot serve ranges, so each is a full scan that visits every bucket. The database saturates and queries start to fail.

    Key idea: Hashing destroys order: equality only, no ranges, no sorting, no prefixes.

  7. 7. Ranges need an ordered index

    We add a B-tree index on id. One second in it is ready: range queries descend once and walk the sorted leaves, and equality lookups use it too. The average query cost drops to about 1.5 ms, the backlog clears and the errors stop.

    This is why PostgreSQL defaults to B-trees even though it has hash indexes: a B-tree does equality almost as well and also ranges, sorting and prefix matches. A hash index earns its place only when lookups are strictly by equality and the slight speed or size advantage matters, as in in-memory stores.

    Scene: One second in, a B-tree index on id is ready. Range queries walk the index, average cost drops to about 1.5 ms, the backlog clears and nothing fails.

    Key idea: B-trees cover equality and order; choose a hash index only for pure equality access.

  8. 8. A hash index over an append-only log

    Hash indexes shine in log-structured stores such as Bitcask (Riak’s storage engine). Data files are append-only: a write adds a record at the end of the active segment and never edits old data, which is fast on any disk. An in-memory hash table, the keydir, maps every key to the file and offset of its latest record.

    Watch a write: append to Segment 2, then update the keydir. Then a read: one keydir lookup in memory gives the offset, then one disk read fetches the value from Segment 1. The catch: every key must fit in memory, and ranges are still impossible. (Scripted illustration.)

    Scene: Illustration: a write appends a record to the active log segment and updates the in-memory keydir. A read looks up the key in the keydir, then reads the value from a closed segment at the stored offset.

    Key idea: Append-only log + in-memory hash index: one sequential write per put, one seek per get.

  9. 9. Compaction and recovery

    Append-only means old versions pile up: updating a key ten times leaves ten records. A background merge reads the closed segments, keeps only the latest record per key (dropping deleted keys, marked by tombstones), writes a merged segment and points the keydir at it; the old segments are then deleted.

    After a crash the keydir is gone, since it lived in memory. It is rebuilt by scanning the segments; Bitcask writes small hint files during merges so startup reads those instead of all the data. (Scripted illustration.)

    Scene: Illustration: a merge copies only the latest record per key from the closed segment into a merged segment and updates the keydir; later reads go to the merged segment.

    Key idea: Log-structured stores trade background compaction and memory for very cheap writes.

  10. 10. Hash or B-tree?

    Choose a hash index when every access is by exact key and you never need order: in-memory key-value stores (Redis, Memcached), Bitcask-style engines, join hash tables inside query engines, and occasionally PostgreSQL hash indexes on long equality-only keys.

    Choose a B-tree for almost everything else: it serves equality nearly as well, plus ranges, sorting, prefixes and composite keys, and it does not need all keys in memory. For write-heavy data larger than memory, look at LSM trees, which build sorted files from an append-only log.

    Scene: The database with both a hash and a B-tree index serves lookups and range queries; the log-structured illustration shows a keydir and its segments.

    Key idea: Hash: fastest equality, nothing else. B-tree: equality plus order, the safe default.