Hashing and Hash Tables Questions
How hash tables and hash-based structures work internally, and how to reason about their performance and correctness. Covers hash function properties (determinism, uniform distribution, speed, avalanche effect), cryptographic versus non-cryptographic hash choices, collision resolution (separate chaining, open addressing: linear probing, quadratic probing, double hashing, Robin Hood hashing, cuckoo hashing), load factor and amortized-cost resizing, and what makes an object hashable (the __hash__/__eq__ contract, immutability, custom composite keys). Covers hash-map-backed cache design (LRU and LFU eviction, TTL) and thread-safe concurrent hash maps (lock striping, CAS-based updates, safe concurrent resizing). Also covers hash-based structures beyond arrays and strings: consistent hashing for distributed routing and sharding, hash joins, hash-flooding and algorithmic-complexity security attacks and their mitigations, and probabilistic membership/cardinality structures such as Bloom filters, Cuckoo filters, Count-Min Sketch, and HyperLogLog. Excludes using a hash map purely as an optimization trick inside an array or string problem (two-sum, group anagrams, longest substring without repeating characters); that pattern belongs to Arrays, Strings, and Hashing. This topic is about the hash table itself: how it is built, how it fails under skewed or adversarial input, and how it scales.
Extend an LRU cache design to support per-entry TTL (time-to-live) and safe concurrent reads/writes from multiple threads. Describe the data structures, locking or sharding strategies to minimize contention, eviction rules when TTL expires, and how to handle race conditions between expiry and access.
Sample Answer
Direct answer
Extending an LRU (least-recently-used) cache with per-entry time-to-live (TTL, a lifespan after which an entry is no longer considered valid) means treating expiry and eviction as two independent mechanisms layered on the same structure: TTL decides whether an entry is even valid to serve at all, LRU decides who gets removed when the cache is full, regardless of whether that entry's TTL has expired yet. Safe concurrent access comes from sharding the cache into N independently locked pieces by key hash, so unrelated keys never contend for the same lock, rather than one global lock serializing every request. The one genuine race to guard against is a reader and an expiry-driven cleanup touching the same key at the same instant, which a single lock per shard around each operation's full check-then-mutate sequence eliminates by construction.
Structured elaboration
Data structures. Per shard: an ordered map (a doubly linked list plus a hash index, or collections.OrderedDict in Python) storing key -> (value, expires_at). get first checks expires_at against the current time; if expired, the entry is deleted and treated as a miss, never served stale. If still valid, it is moved to the most-recently-used end, same as a plain LRU. put inserts or updates the entry with a fresh expires_at, then evicts from the least-recently-used end while the shard is over capacity, exactly as a TTL-unaware LRU would, an unexpired entry can still be evicted early purely for space if it is cold enough.
Locking and sharding to minimize contention. A single lock around the whole cache serializes every request regardless of which key it touches, the same contention problem as a naive shared counter. The fix is the same: partition keys across N shards by hash(key) % N, each with its own lock, so two threads touching different shards never block each other; within a shard, the critical section (a dict lookup, a move, maybe an eviction) is small enough that a simple mutex around the whole operation is both correct and fast, a lock-free linked-list-based LRU is real engineering effort that rarely pays for itself compared to just adding more, smaller shards.
Eviction rules on TTL expiry. Two independent triggers remove an entry: lazily, on access, if its expires_at has passed; and capacity-driven, on put, evicting the least-recently-used entry regardless of that entry's own TTL state once the shard is full. A background sweep thread that proactively scans for and removes expired-but-never-accessed entries is an optional memory-hygiene addition, not a correctness requirement, lazy expiry alone already guarantees an expired entry is never served, it just might sit unreclaimed in memory until LRU pressure or a sweep removes it.
Race conditions between expiry and access. Because the expiry check and the touch-or-evict mutation both happen inside the same lock acquisition as one atomic operation, no other thread on that shard can observe a half-expired state in between. Two remaining subtleties matter: use a monotonic clock (one that only ever moves forward, unaffected by wall-clock adjustments) for expiry comparisons, since a wall-clock adjustment (an NTP correction, a daylight-saving shift) can jump time backward and silently corrupt TTL math; and treat the exact boundary consistently, an access at precisely expires_at should be treated as expired, not as a coin flip.
Code
import threading, time
from collections import OrderedDict
class TTLLRUCache:
def __init__(self, capacity, default_ttl):
self._capacity = capacity
self._default_ttl = default_ttl
self._store = OrderedDict() # key -> (value, expires_at)
self._lock = threading.Lock()
def get(self, key, now=None):
now = time.monotonic() if now is None else now
with self._lock:
entry = self._store.get(key)
if entry is None:
return None
value, expires_at = entry
if now >= expires_at:
del self._store[key]
return None
self._store.move_to_end(key)
return value
def put(self, key, value, ttl=None, now=None):
now = time.monotonic() if now is None else now
ttl = self._default_ttl if ttl is None else ttl
with self._lock:
if key in self._store:
del self._store[key]
self._store[key] = (value, now + ttl)
self._store.move_to_end(key)
while len(self._store) > self._capacity:
self._store.popitem(last=False)
class ShardedTTLLRUCache:
def __init__(self, shard_count, capacity_per_shard, default_ttl):
self._shards = [TTLLRUCache(capacity_per_shard, default_ttl) for _ in range(shard_count)]
self._shard_count = shard_count
def _shard_for(self, key):
return self._shards[hash(key) % self._shard_count]
def get(self, key, now=None):
return self._shard_for(key).get(key, now=now)
def put(self, key, value, ttl=None, now=None):
self._shard_for(key).put(key, value, ttl=ttl, now=now)
if __name__ == "__main__":
# basic TTL expiry
cache = TTLLRUCache(capacity=2, default_ttl=10)
cache.put("a", 1, now=0)
print("get a at t=5 (not expired) ->", cache.get("a", now=5))
print("get a at t=15 (expired, ttl=10) ->", cache.get("a", now=15))
# LRU eviction independent of TTL (long ttl so eviction is purely LRU-driven)
cache2 = TTLLRUCache(capacity=2, default_ttl=100)
cache2.put("x", 100, now=0)
cache2.put("y", 200, now=1)
cache2.get("x", now=2) # touch x -> y becomes LRU
cache2.put("z", 300, now=3) # evicts y (LRU), not due to TTL (ttl=100, still valid)
print("y evicted by LRU (not TTL) ->", cache2.get("y", now=4) is None)
print("x survived ->", cache2.get("x", now=4) == 100)
# concurrency check: 16 threads, 200 put-then-get round trips each, shared 8-shard cache
shared = ShardedTTLLRUCache(shard_count=8, capacity_per_shard=64, default_ttl=1000)
errors = []
def worker(tid):
for i in range(200):
key = f"t{tid}-{i}"
shared.put(key, (tid, i), now=0)
val = shared.get(key, now=0)
if val != (tid, i):
errors.append((key, val))
threads = [threading.Thread(target=worker, args=(t,)) for t in range(16)]
for th in threads:
th.start()
for th in threads:
th.join()
print("concurrent put/get across 16 threads, errors ->", len(errors))
# exact boundary: an access at precisely expires_at counts as expired
cache3 = TTLLRUCache(capacity=2, default_ttl=1.0)
cache3.put("k", 42, now=0.0)
print("exactly-at-expiry (t=1.0) counts as expired ->", cache3.get("k", now=1.0) is None)
Output (executed as shown, using an injected clock so TTL behavior is deterministic and reproducible):
get a at t=5 (not expired) -> 1
get a at t=15 (expired, ttl=10) -> None
y evicted by LRU (not TTL) -> True
x survived -> True
concurrent put/get across 16 threads, errors -> 0
exactly-at-expiry (t=1.0) counts as expired -> True
The concurrency check ran 16 threads, each performing 200 put-then-get round trips against a shared 8-shard cache, and confirmed every value was read back exactly as written with zero errors, evidence the sharded locking is actually safe under real concurrent access, not just single-threaded correctness.
Trade-offs and pitfalls
- Lazy-only expiry can leave cold, expired entries resident indefinitely if the cache has generous capacity and that key is never looked up again; add a background sweep if bounding memory tightly matters more than the extra CPU cost of scanning.
- Shard count is a real tuning knob, not a fixed choice. Too few shards under-spreads lock contention; too many wastes memory on mostly-empty per-shard structures and adds bookkeeping overhead.
- Distributed sharding is the same idea one layer up. The identical hash-the-key-to-a-shard principle extends from in-process locks to independent nodes in a distributed cache: shard by consistent hashing across nodes so the cache's total capacity and throughput scale past one machine, with a routing layer (client-side or proxy-side) sending each request to the node that owns its key's shard.
- Persistence across restarts should stay proportionate to what TTL data actually needs. Since every entry already has a bounded lifespan, a periodic best-effort snapshot to disk or an external store, reloaded at startup and immediately filtered to discard anything whose
expires_athas already passed relative to current wall-clock time, is sufficient; treating this like a database's durability guarantee (distributed consensus, write-ahead logs) is usually over-engineering for data that was always meant to expire. - A common wrong turn: using wall-clock time (
time.time()) instead of a monotonic clock for TTL comparisons. It works in every normal test run and fails exactly once, silently, during a real clock adjustment in production, which is precisely why it is easy to ship and hard to catch without deliberately testing for it.
You're implementing membership checks for a user ID blacklist that receives thousands of queries per second. Compare using a hash set versus a sorted array with binary search for membership tests. Discuss time/space complexity, cache locality, update costs, and when to prefer each in a backend service.
Sample Answer
Direct answer
A hash set gives O(1) average membership checks regardless of blacklist size, which is the right
choice for a high-query-rate service; a sorted array with binary search gives O(log n)
membership checks, slower per query but with better cache locality and much lower per-entry
memory overhead. The real deciding factor is usually update frequency: a hash set tolerates
frequent updates cheaply, while a sorted array's inserts require shifting elements and are
expensive at scale.
Structured elaboration
Membership test complexity. A hash set computes one hash and does O(1) average work to
confirm or deny membership, independent of how many entries are in the set. A sorted array with
binary search needs ceil(log2(n)) comparisons in the worst case; for n = 1{,}000{,}000
entries, that is 20 comparisons, small in absolute terms but structurally always growing (however
slowly) with blacklist size, unlike the hash set's flat cost.
Cache locality. Binary search on a sorted array has excellent locality in one specific sense:
the array itself is one contiguous block, so each individual access is cheap, though the ACCESS
PATTERN (jumping to the middle, then a quarter point, etc.) is not sequential and does not
prefetch as well as a straight linear scan would. A hash set's single lookup touches one (or a
handful of, under collision) location directly, without the multi-step probe pattern binary
search requires, at the cost of that location being determined by a hash rather than a
predictable arithmetic position.
Update costs, the real differentiator. Inserting a new id into a SORTED array requires
finding its position and shifting every element after that position by one slot to keep the array
sorted; for a mid-range insert into a million-element array, that means moving on the order of
half a million elements. Inserting into a hash set touches exactly one new slot (amortized,
ignoring occasional resizing) with no shifting at all. For a blacklist that is updated
frequently (new abusive users added continuously), this asymmetry usually dominates the decision
far more than the query-time gap between O(1) and O(log n).
When to prefer each, concretely for a backend service. Prefer a hash set when the blacklist
updates frequently and query volume is very high (the question's "thousands of queries per
second" scenario clearly favors this). Prefer a sorted array with binary search when the
blacklist is effectively static or updated in large infrequent batches (rebuild the sorted array
wholesale on each batch update rather than incrementally), AND you specifically need the array's
side benefits, such as efficient RANGE queries (all ids between X and Y) or a smaller, more
predictable memory footprint per entry, neither of which a hash set provides at all.
Worked example
import bisect
def counting_bisect_left(sorted_list, target, counter):
lo, hi = 0, len(sorted_list)
while lo < hi:
mid = (lo + hi) // 2
counter[0] += 1
if sorted_list[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
n = 1_000_000
blacklist_sorted = [2 * i for i in range(n)]
blacklist_set = set(blacklist_sorted)
counter_hit = [0]
idx_hit = counting_bisect_left(blacklist_sorted, 500_000, counter_hit)
print("HIT comparisons:", counter_hit[0], "found:", blacklist_sorted[idx_hit] == 500_000)
counter_miss = [0]
idx_miss = counting_bisect_left(blacklist_sorted, 999_999_501, counter_miss)
found_miss = idx_miss < n and blacklist_sorted[idx_miss] == 999_999_501
print("MISS comparisons:", counter_miss[0], "found:", found_miss)
print("hash set: 500,000 in set ->", 500_000 in blacklist_set)
print("hash set: 999,999,501 in set ->", 999_999_501 in blacklist_set)
# Update cost: inserting a new odd id into the sorted array shifts everything after it
new_id = 1_000_001
pos = bisect.bisect_left(blacklist_sorted, new_id)
shifted = len(blacklist_sorted) - pos
blacklist_sorted.insert(pos, new_id)
print(f"inserting {new_id} into the sorted array shifts {shifted} existing elements")
before_size = len(blacklist_set)
blacklist_set.add(new_id)
print(f"hash set size before: {before_size}, after: {len(blacklist_set)} (one new entry, no shifting)")
Instrumenting binary search to count actual comparisons against a sorted array of 1,000,000 even
ids: a HIT lookup (id 500,000, present) takes 19 comparisons, and a MISS lookup (id 999,999,501,
an odd number genuinely absent from the array) also takes 19 comparisons, both within the
ceil(log2(1{,}000{,}000)) = 20 theoretical bound. A hash set confirms the same membership
answers for both queries (True and False respectively) in a single in check. For the update
cost: inserting a new odd id (1,000,001) into the middle of the sorted array requires shifting
499,999 existing elements to keep it sorted, while inserting the same id into the hash set
touches exactly 1 new entry, no shifting, directly demonstrating the update-cost asymmetry the
"structured elaboration" section describes.
Trade-offs and pitfalls
- Do not decide this purely on the O(1) vs O(log n) query gap. At realistic blacklist sizes,
20 comparisons versus 1 hash lookup is rarely the bottleneck; update pattern is usually the
deciding factor in practice. - A sorted array shines for range queries ("give me every blacklisted id between X and Y"), a
query shape a hash set cannot answer efficiently at all (it would require scanning every entry);
if that capability is ever needed, it tips the decision toward the array (or a hybrid, keeping
both). - Batch-rebuilding a sorted array (collect updates, then rebuild the whole sorted array
periodically) sidesteps the expensive per-insert shifting cost, if the update latency
requirement tolerates a delay between when an id is added and when it takes effect. - Per-entry memory overhead is usually lower for a plain sorted array of fixed-size values
than for a hash set's backing table (which reserves extra capacity to keep its load factor
low); at very large scale with a memory-constrained service, this can matter as much as the
update-cost argument.
Design a caching layer for API responses in a microservice using a hash-based in-memory store. Explain what you would include in the cache key, how you would decide which entries to evict under memory pressure, how you would keep the cache from serving stale data, and how your approach changes once the service runs on multiple instances.
Sample Answer
Direct answer
A hash-based response cache needs four separate decisions: what goes into the key, what gets evicted when memory is tight, how staleness is bounded, and what changes once the cache is no longer sitting in a single process. Treat those as independent axes: conflating "eviction" with "invalidation" is the most common design mistake here.
Structured elaboration
Cache key composition. Include everything that changes the response: route template, path parameters, query parameters (sorted, so ?page=2&status=active and ?status=active&page=2 collide to the same key), the relevant subset of headers (tenant id, Accept-Language), and an API/schema version. Hash that canonical tuple with a fast non-cryptographic hash (xxHash or MurmurHash) rather than a cryptographic one: you need speed and uniform distribution, not preimage resistance.
Eviction under memory pressure. Least-recently-used (LRU: evict the entry that has gone longest untouched) is the default, built as a hash map plus a doubly linked list so both lookup and the recency update are O(1). If a single bulk scan (a report job hitting thousands of distinct keys once) should not be allowed to evict everything a real user needs, use a segmented cache: a small probationary segment for first-seen keys and a protected segment for keys accessed at least twice, so one-off scans age out of probationary without ever touching the protected set. Critically, gate eviction on an actual memory budget (bytes), not entry count: response payloads vary by orders of magnitude in size, so a 10,000-entry cap can still OOM if a handful of entries are large paginated lists.
Keeping it fresh. Combine a TTL (so worst-case staleness is bounded even if invalidation is missed) with active invalidation on writes: on a write, delete the cache key rather than trying to update it in place (update-then-cache races when a slow commit finishes after a fast concurrent read repopulates the cache with stale data). Embedding an upstream version or ETag in the key is a cheap third layer: a byte-level change to the underlying data naturally produces a new key with no explicit bust needed.
Once there is more than one instance. A single process's in-memory map has no relationship to another instance's map. Four real options, roughly cheapest to most consistent: (1) keep per-instance local caches with a short TTL and accept staleness bounded by that TTL; (2) move to one shared external cache (e.g. Redis) all instances query, trading a network hop for a single source of truth; (3) shard the keyspace across a cache tier with consistent hashing so each cache node owns a partition of keys, which also solves the "same key cached N times" memory waste; (4) a two-tier design, a small local L1 for latency plus a shared L2 for consistency, with a pub/sub invalidation broadcast so a write on one instance evicts the key from every L1. Within one instance, if request handling is itself multi-threaded, a single lock guarding the whole map serializes unrelated requests; shard the map into N independently-locked segments (the same idea Java's ConcurrentHashMap uses) so a write to key A never blocks a read of unrelated key B. At very large scale, even the LRU bookkeeping (moving a linked-list node on every touch) becomes contended; production caches like Redis instead sample a handful of random entries and evict the oldest-looking one by an approximate recency counter, trading a slightly worse eviction choice for removing that contention entirely.
Worked example
For GET /users/42/orders?status=active&page=2 with schema version 3, the key is built from the canonical string "GET|/users/{id}/orders|id=42|page=2|status=active|v=3" and hashed: key = xxhash64(canonical_string). Two requests differing only in query-param order produce the same canonical string and therefore the same key (a hit); a request after a schema bump to v=4 produces a different key (a clean miss, no explicit invalidation required).
Trade-offs and pitfalls
- No TTL ceiling: staleness becomes unbounded the moment any write path forgets to invalidate (a very common regression when a new mutation endpoint ships).
- Update-in-place on write invites the classic race described above; delete-then-lazy-repopulate avoids it at the cost of one extra miss per write.
- A cache key that omits a relevant query parameter serves the wrong data to some requests; one that includes something irrelevant (a request id) turns every request into a guaranteed miss.
- Entry-count eviction caps can both over-evict (many tiny entries) and under-evict (few huge entries) relative to actual memory pressure.
Design a consistent hashing scheme for sharding keys across cache nodes that supports node additions and removals with minimal remapping. Explain ring construction, virtual nodes (vnodes), lookup algorithm, how to handle replication and node heterogeneity, and how you would integrate this into an ingestion pipeline that routes writes and reads.
Sample Answer
Direct answer
Consistent hashing places both keys and server nodes onto the same circular hash space (a "ring");
a key belongs to the first node found walking clockwise from the key's position. Adding or removing
one node only reassigns the keys that fall between that node and its predecessor on the ring, roughly
1/N of all keys for N nodes, instead of the near-total reshuffle a naive hash(key) % node_count
scheme causes on every membership change.
Structured elaboration
Why plain modulo hashing fails under scaling. With hash(key) % N, changing N from 4 to 5
changes the modulus for essentially every key, most keys land on a completely different node than
before, even though only one node was added. That means a near-total cache/data migration on every
single scale-up or scale-down event, unacceptable for any system trying to add capacity smoothly.
The ring construction. Hash every node's identifier onto the same circular space (say, a 0 to
2^32-1 integer range, wrapping around). To find which node owns a given key, hash the key onto that
same space and walk clockwise until you hit the first node hash you encounter, that node owns the
key. Removing a node only affects the keys that were mapped to it, they now belong to the NEXT node
clockwise, nothing else on the ring moves. Adding a node only affects the keys that fall between the
new node's position and its predecessor's, those transfer to the new node, everyone else's ownership
is untouched.
Why virtual nodes (vnodes) matter. With only one ring position per PHYSICAL node, the ring can be
badly unbalanced by chance, one node might own a much larger arc than another purely from where its
single hash happened to land. The standard fix is to hash each physical node into MANY positions on
the ring (say 100-200 per node, e.g. hash("node-A#0"), hash("node-A#1"), ...), so each physical
node's TOTAL owned arc length is the sum of many smaller, independently-placed slices, which averages
out toward a much more even split by the law of large numbers, and lets you allocate a node MORE
vnodes if it has more capacity than its peers (the weighted-consistent-hashing extension).
Replication. For fault tolerance, a key's replicas are typically the NEXT R distinct physical
nodes found walking clockwise past the key's primary owner (skipping any vnode belonging to a
physical node already chosen as a replica), so losing any one node still leaves the key available
from its other replicas.
Worked example
The measurement that matters here is HOW MUCH gets remapped when scaling:
import hashlib, bisect
def h(s):
return int(hashlib.md5(s.encode()).hexdigest(), 16)
class Ring:
def __init__(self, nodes, vnodes=100):
self.ring = {}
for node in nodes:
for i in range(vnodes):
self.ring[h(f"{node}#{i}")] = node
self.sorted_positions = sorted(self.ring.keys())
def get_node(self, key):
pos = h(key)
idx = bisect.bisect(self.sorted_positions, pos)
if idx == len(self.sorted_positions):
idx = 0
return self.ring[self.sorted_positions[idx]]
nodes3 = ["node-A", "node-B", "node-C"]
ring3 = Ring(nodes3, vnodes=100)
ring4 = Ring(nodes3 + ["node-D"], vnodes=100)
keys = [f"key-{i}" for i in range(10000)]
moved = sum(1 for k in keys if ring3.get_node(k) != ring4.get_node(k))
print(f"consistent hashing: {moved}/{len(keys)} = {moved/len(keys)*100:.2f}% remapped when adding a 4th node")
moved_mod = sum(1 for k in keys if h(k) % 3 != h(k) % 4)
print(f"naive modulo hashing: {moved_mod}/{len(keys)} = {moved_mod/len(keys)*100:.2f}% remapped for the same transition")
Running this against 10,000 sample keys with 3 nodes at 100 vnodes each, then adding a 4th node
(also with 100 vnodes), shows 20.38% of keys remapped under consistent hashing, in the same
ballpark as the naive theoretical 1/(3+1) = 25% expectation (a single hash-based ring instantiation
has real sampling variance around that figure; more vnodes per node tightens it further), versus
74.86% of keys remapped under naive modulo hashing for the identical 3-to-4 transition, since
k % 3 and k % 4 only coincidentally agree for a small, unrelated fraction of keys. The roughly
3.7x gap between 20% and 75% is the actual value proposition of consistent hashing, not a full
reshuffle on every scaling event.
Integrating into an ingestion pipeline
The write path looks up the ring once per incoming record (hash the record's shard key, e.g. a user
id or cache key, and walk clockwise to the owning node plus its R-1 replicas) and forwards the write
to that primary node, replicating to the replicas synchronously or asynchronously depending on the
consistency model. The read path performs the identical ring lookup, so reads and writes for the
same key always resolve to the same physical node without a separate coordination service. Only the
ingestion workers doing this lookup need to hold the ring's vnode mapping in memory, loaded once at
startup and refreshed whenever a membership-change event (a node add or remove) fires, rather than
every downstream consumer needing its own copy of ring state.
Trade-offs and pitfalls
Too few vnodes per physical node (say, 1) can leave the ring meaningfully imbalanced by chance, some
nodes owning far more than 1/N of the keyspace, which is exactly why production systems use 100+
vnodes per node rather than treating one hash-position-per-node as sufficient. A second pitfall is
forgetting that replica placement must SKIP vnodes belonging to a physical node already selected,
naively taking "the next R vnode owners clockwise" without that check can select the SAME physical
node as two of a key's replicas, defeating the entire purpose of replication.
Describe an approach to detect duplicates in a high-volume streaming feed of user events using hash-based structures. Include memory considerations, approximate alternatives (e.g., Bloom filters), and strategies for time-bounded duplicate detection (for instance, dedupe only within the last 24 hours).
Sample Answer
Direct answer
Compute a stable identifier (a natural event id, or a hash of the event's content if none exists) for each incoming event, and check it against a set of identifiers already seen within the dedup window before processing; present means drop it as a duplicate, absent means process it and record the identifier. An exact hash set gives zero false positives but grows linearly with the number of distinct events currently tracked, which becomes the memory bottleneck at high volume; a probabilistic structure like a Bloom filter trades a small, tunable false-positive rate for an order-of-magnitude smaller footprint, usually the right trade at streaming scale. Bounding the structure to a fixed time window, for instance the last 24 hours, keeps memory from growing without limit.
Exact approach: hash set
Maintain a hash set of event identifiers already processed. On each new event, look it up: present means duplicate, absent means new (insert, then process). This is exact, no false positives and no false negatives, but memory scales directly with how many distinct events are currently tracked, which is the first thing to break at high volume.
Memory considerations
A language-level hash set rarely stores just the raw identifier bytes: object headers, pointers, and the underlying hash table's own load-factor slack add real per-entry overhead on top of the identifier itself. Because that overhead is roughly constant per entry, total memory scales linearly and directly with how many distinct events are being remembered at once, which is exactly the quantity that grows fastest in a high-volume feed.
Approximate alternative: Bloom filters
A Bloom filter trades a small, controllable false-positive rate for dramatically less memory: it answers "definitely not seen" with certainty, or "possibly seen" with a bounded error rate, and it never produces a false negative (a genuinely new event is never mistakenly dropped as a duplicate). Given a target false-positive probability p and expected item count n, the optimal bit-array size and hash-function count are:
m=−(ln2)2nlnpk=nmln2
Time-bounded (e.g. 24-hour) dedup
Tracking duplicates forever is usually the wrong goal for a streaming feed: you rarely need to know an event duplicates something from months ago, and unbounded tracking only makes the memory problem worse over time. Common ways to bound the window:
- Rotating filters: keep several Bloom filters (or hash sets), one per time bucket (for example hourly), check an incoming event against the last 24 buckets, insert it into the CURRENT bucket, and drop the oldest bucket as a new one opens. This gives an approximate sliding window at the cost of checking several filters per lookup.
- TTL-backed store: with a real key-value store (Redis and similar), attach a 24-hour time-to-live to each recorded event id and let the store expire entries automatically. Simpler operationally, but back to exact-set memory costs unless the store itself offers a probabilistic structure.
- Counting/decay variants: a Counting Bloom Filter supports removal (increment counters instead of flipping bits, decrement or expire on a per-slot timer), letting entries actually age out of the SAME structure rather than rotating separate ones, at the cost of a bit more memory per slot.
Worked example
import hashlib
import math
import random
class BloomFilter:
def __init__(self, n_expected, target_fp_rate):
self.n_expected = n_expected
self.m = math.ceil(-(n_expected * math.log(target_fp_rate)) / (math.log(2) ** 2))
self.k = max(1, round((self.m / n_expected) * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
h = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(h[:8], "big")
h2 = int.from_bytes(h[8:16], "big") | 1
for i in range(self.k):
yield (h1 + i * h2) % self.m
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= (1 << (pos % 8))
def __contains__(self, item):
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
if __name__ == "__main__":
random.seed(123)
N_EVENTS = 200_000
TARGET_FP = 0.01
bf = BloomFilter(N_EVENTS, TARGET_FP)
print(f"n={N_EVENTS} target_fp={TARGET_FP} -> m={bf.m} bits ({bf.m/8/1024:.1f} KiB), k={bf.k}")
seen_ids = [f"evt-{i}-{random.randint(0, 1_000_000)}" for i in range(N_EVENTS)]
for eid in seen_ids:
bf.add(eid)
false_negatives = sum(1 for eid in seen_ids if eid not in bf)
print("false negatives among inserted ids (must be 0):", false_negatives)
unseen_ids = [f"unseen-{i}-{random.randint(0, 1_000_000)}" for i in range(100_000)]
false_positives = sum(1 for eid in unseen_ids if eid in bf)
print(f"empirical false-positive rate over {len(unseen_ids)} unseen ids: "
f"{false_positives/len(unseen_ids):.4f} (predicted ~{TARGET_FP})")
exact_set_bytes_estimate = N_EVENTS * 64
print(f"bloom filter bytes: {len(bf.bits)} vs exact set (rough estimate): {exact_set_bytes_estimate}")
Output:
n=200000 target_fp=0.01 -> m=1917012 bits (234.0 KiB), k=7
false negatives among inserted ids (must be 0): 0
empirical false-positive rate over 100000 unseen ids: 0.0102 (predicted ~0.01)
bloom filter bytes: 239627 vs exact set (rough estimate): 12800000
Sized for 200,000 tracked events at a 1% target, the formula calls for about 234 KiB and 7 hash functions; the empirical false-positive rate measured against 100,000 never-inserted ids comes out to 1.02%, matching the 1% target closely, and every one of the 200,000 actually-inserted ids is correctly recognized (zero false negatives, which is the guarantee that must never break). The Bloom filter's roughly 234 KiB footprint against a rough per-entry estimate of about 12.8 MB for an equivalent exact set is a roughly 53x reduction for this workload, which is the trade being made: about 1% of genuinely new events get incorrectly treated as duplicates and dropped.
Trade-offs and pitfalls
- A Bloom filter's false positives mean some genuinely new events get silently dropped; fine for many analytics or logging use cases, but the wrong choice if losing even a small fraction of new legitimate events is unacceptable (billing events, for instance), where an exact structure or a verification step on filter hits is warranted instead.
- Sizing a Bloom filter for the wrong n (underestimating peak event volume in the window) silently degrades the false-positive rate well past what was designed for, since m and k were chosen assuming a specific n; monitor actual load and re-provision rather than assuming a static estimate holds forever.
- Rotating multiple time-bucketed filters multiplies lookups per event (checking every open bucket); a Counting Bloom Filter with per-slot decay avoids that at the cost of a bit more memory per slot.
Unlock Full Question Bank
Get access to all Hashing and Hash Tables interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.