Membership Service for a Growing ID Set: Latency, Memory, Durability
System DesignModel answerLast updated
Design a check-and-insert service for ~1 million user IDs, covering data structure choice, atomic concurrency, probabilistic filters, and crash-safe on-disk storage.
Membership Service for a Growing ID Set
A backend service maintains a registry of user IDs. Every incoming request carries one ID. The service must answer a single question: has this ID been seen before? If the answer is no, the ID must be recorded so future requests can find it.
Your job is to design that service end-to-end, starting from the simplest working solution and evolving it as constraints tighten. Be explicit about your assumptions, your numbers, and the trade-offs you accept at each step.
Constraints and clarifications
- The ID format, the request rate, and whether state must survive a restart are left open. State your assumptions before designing.
- Check-and-insert is one logical operation. A caller must get a consistent answer: if the ID was absent, it must be present after the call returns.
Good clarifying questions to raise
- What do IDs look like — 64-bit integers, UUIDs, opaque strings? Are integer IDs dense within a bounded range?
- What is the request rate, and what share of requests carry a brand-new ID?
- Is an occasional wrong answer acceptable? If so, which error direction is tolerable: falsely reporting "already seen" or falsely reporting "new"?
- Must the registry survive a process restart? Is it shared across multiple service instances?
- Will the registry grow well beyond 1 million entries, and can IDs ever be removed?
Part 1 — Single-machine baseline
Design the simplest solution that correctly handles 1 million IDs on one machine.
Cover:
- A concrete data structure, its time complexity per operation, and a memory estimate for the ID format you assumed
- How you make check-and-insert atomic when requests arrive concurrently, both within a single process and when multiple processes share the same store
- Any alternative structures that become attractive for special ID shapes or heavily read-biased workloads
Part 2 — Approximate membership when memory is scarce
Assume memory is limited, or the set is expected to grow by several orders of magnitude. An exact in-memory structure holding every ID is no longer viable. How do you keep most lookups fast while accepting some imprecision?
Cover:
- A compact probabilistic structure, the specific kind of error it can produce, and how to tune its size to hit a target error rate
- How the overall system still produces an exact final answer — or what the consequences are if it does not
- What happens to error rates as the set expands past its initial design capacity, and how deletions complicate things
Part 3 — Persistent storage that scales
The authoritative copy of the registry must now live on disk, survive crashes, and keep accepting inserts at a steady rate without making lookups slow.
Cover:
- The write path: how you achieve durability, how you buffer writes in memory before flushing to disk
- The read path: what you search first, what you search next, and how you avoid reading most of it most of the time
- Background work that keeps read performance from degrading over time, and how the system recovers after a crash
Hints
Hint 1
For Part 1, nail down the ID format before estimating memory — a 128-bit UUID stored as a raw string costs 3–4× more than one stored as bytes. Then think about what 'atomic' means at the process level versus the host level.
Hint 2
For Part 2, a Bloom filter can tell you an ID is definitely absent, but it can never tell you it is definitely present. Work out which error direction is safe for this operation, and what must sit behind the filter to guarantee correctness.
Hint 3
For Part 3, think about why appending to a log and sorting in the background is friendlier to disks than in-place updates, and what small index structure lets you skip most on-disk files without reading them.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Starting with requirements
Before designing anything, lock down three numbers: ID size, request rate, and durability requirement. A reasonable baseline: 64-bit integer IDs, 10 000 requests per second, state must survive restarts, single service instance for now. These assumptions drive every sizing estimate that follows.
Part 1 — Single-machine baseline
Data structure. A hash set is the natural choice. With 64-bit integer IDs, each entry costs roughly 8 bytes for the key plus 8–16 bytes of overhead for the bucket pointer or open-addressing metadata. At 1 million entries that is 16–24 MB — comfortably in memory. If IDs are dense integers in a known range (say 0–10 M), a bitmap collapses that to 1.25 MB and makes the check a single bit read, which is hard to beat.
For UUID or opaque-string IDs, memory rises sharply. A 16-byte UUID stored as raw bytes in a hash set costs around 50–80 bytes per entry (key + load-factor slack), so ~80 MB for 1 million entries — still fine. Storing UUIDs as 36-character hex strings triples that; always convert to bytes first.
Atomic check-and-insert. Within one process, a single mutex (or a read-write lock with an upgrade path) around the hash set is enough. A common mistake is using a read lock for the check and a write lock for the insert separately — another thread can insert the same ID between those two steps. The entire check-and-insert must execute under a single write lock, or you need a compare-and-swap idiom if the language runtime supports it.
Across processes, you need an external store with atomic semantics. Redis SET key NX (set if not exists) returns whether the key was actually inserted, making the whole operation one round trip. At 10 K RPS, a single Redis instance with pipelining handles this easily. SETNX is older and requires a separate GET, introducing a race — use SET NX instead.
Latency. In-memory hash set: sub-microsecond. Redis over a local socket: ~100 µs. Redis over a LAN: 0.5–2 ms. These numbers matter when discussing whether an external store is acceptable.
Part 2 — Approximate membership with a Bloom filter
How a Bloom filter works. A Bloom filter uses a bit array of size m and k independent hash functions. On insert, all k bit positions are set to 1. On lookup, if any of the k positions is 0, the ID is definitely absent. If all are 1, the ID is probably present — false positives are possible, false negatives are not.
For this service, a false positive means the filter says "already seen" when the ID is actually new — causing the insert to be skipped and the ID to be lost. That is a serious correctness problem. A false negative is impossible by construction.
Consequence for design. You cannot use a standalone Bloom filter as the authoritative store. The correct pattern is: use the filter as a fast-reject layer in front of the exact store. If the filter says "absent", the ID is guaranteed new — insert it (and also add it to the filter). If the filter says "present", fall through to the exact store to confirm.
Sizing. The standard formula for false-positive rate is p ≈ (1 − e^(−kn/m))^k, minimized at k = (m/n) ln 2. At 1% false-positive rate, you need about 9.6 bits per element. For 1 million IDs: ~1.2 MB — versus ~20 MB for the hash set. For 100 million IDs: ~120 MB versus ~2 GB. The filter's advantage grows with scale.
Growth and deletions. A standard Bloom filter's false-positive rate creeps up as you insert beyond its design capacity — budget for 2× expected size. Deletions are not supported; you cannot un-set a bit because multiple IDs may share it. Counting Bloom filters support deletions by replacing each bit with a small counter, at ~4× the memory cost. Cuckoo filters support deletions more efficiently and have better cache behavior; they are a good alternative to mention.
Part 3 — Durable on-disk storage
The design here mirrors an LSM-tree (Log-Structured Merge-tree), the structure behind LevelDB, RocksDB, and Cassandra.
Write path. Every insert is appended to a write-ahead log (WAL) on disk before being acknowledged. This gives crash durability: even if the process dies mid-operation, the WAL can replay the insert. Simultaneously, the insert is written into an in-memory sorted buffer (the memtable). Once the memtable reaches a size threshold (e.g., 64 MB), it is flushed to disk as an immutable sorted file (an SSTable). The WAL segment corresponding to that memtable can then be discarded.
The key insight: appending to a log is sequential I/O, which is fast on both spinning disks and SSDs. In-place updates would cause random writes and are avoided entirely.
Read path. On lookup, search in this order:
- The in-memory memtable (a hash map or sorted tree — O(1) or O(log n)).
- Bloom filters for each on-disk SSTable (one filter per file, kept in memory). If the filter says the ID is absent, skip that file entirely — this eliminates the vast majority of disk reads.
- Any SSTable whose filter gave a positive — do a binary search within the file.
A two-level index (sparse in-memory index pointing into each SSTable's block index) makes step 3 O(log n) within a file without loading the whole file.
Background compaction. Over time, many SSTables accumulate. Reads must check more files, and deleted or overwritten keys waste space. Compaction merges SSTables into larger ones, deduplicating keys and dropping tombstones. This trades background I/O for faster reads. Tiered compaction (RocksDB default) is write-optimized; leveled compaction (LevelDB default) keeps read amplification low — choose based on your read/write ratio.
Crash recovery. On restart, replay the WAL to reconstruct the memtable, then load the Bloom filters and sparse indexes for all SSTables into memory. The service is ready once that in-memory state is rebuilt — typically seconds for a moderate dataset.
Common mistakes to avoid
- Treating the Bloom filter as the authoritative store rather than a pre-filter
- Checking and inserting under separate locks, introducing a race window
- Forgetting that
SETNXin Redis is not atomic with a follow-up read — useSET NXinstead - Ignoring the WAL and relying only on periodic snapshots, which creates a gap where inserts can be lost
- Not accounting for Bloom filter degradation as the set grows past its initial design size