Serving Inventory From Spinning Disks With Tiny RAM
System DesignModel answerLast updated
Design an inventory service on hard drives with little memory: layout records to minimize seeks, pin the index, cache hot items, batch writes, and keep reservations correct.
You are asked to build an inventory service for a machine that has rotational hard disks and only a couple of gigabytes of RAM — no SSDs, no large in-memory store. Records are keyed by item ID and hold fields like available quantity, reserved quantity, a version counter, and some variable-length descriptive metadata. Clients can read a record, update counters, and perform an atomic conditional operation such as "reserve one unit only if at least one is available." Reservations can later be committed or released, and the same request may be retried.
Explain your design end to end: how you lay data out on disk, how you index it so lookups do not cost many seeks, what you cache given the small RAM budget, what the read and write paths look like, how you make concurrent reservations safe, how you guarantee durability and crash recovery, and how you handle disks that answer only ~100–200 random I/Os per second. State your assumptions about scale with concrete numbers and justify each decision in terms of seek counts and throughput. The interviewer wants trade-offs, not slogans.
Hints
Hint 1
Start from the physics: a random disk read is 5–10 ms, so count seeks per operation and design to make that number small and constant.
Hint 2
Splitting small hot counters from bulky metadata makes each cached page carry many useful records — think about how many records fit in a 4 KB page.
Hint 3
A conditional reserve is a read-modify-write, so cheapest-write structures like LSM trees do not save you; the read dominates.
Hint 4
One fsync per write caps you near 100 writes/s; batching many writes behind a single fsync changes that by orders of magnitude.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a storage-engineering problem under physical constraints. The dominant fact is that a spinning disk serves roughly 100–200 random I/Os per second (5–10 ms per seek plus rotation) and streams 150–250 MB/s sequentially. Nearly every decision below should either remove a random seek, turn random I/O into sequential I/O, or share one seek across many requests. I would narrate the design in those terms.
Assumptions
- Catalog: 100M items, sparse 64-bit IDs.
- Hot record:
item_id (8B) | available (4B) | reserved (4B) | version (8B) | flags + checksum (8B)≈ 32B, padded to 64B. - Metadata: 500B–2KB variable length, rarely needed on the reservation path.
- Hardware: 2 GB RAM, 4 HDDs.
- Traffic: ~5–10K req/s, Zipfian (about 1% of items take 80% of traffic), reads outnumber writes ~4:1.
- Correctness: never oversell; an acknowledged reservation survives a crash; retries are safe.
- Latency: p50 under 2 ms for cached items, p99 around 30 ms.
API
get(item_id) -> {available, reserved, version, metadata?}
update(item_id, delta, expected_version?) -> ok | conflict
reserve(item_id, qty, idempotency_key, ttl) -> reservation_id | insufficient
commit(reservation_id) / release(reservation_id)
A reservation moves units from available to reserved; commit consumes reserved; release or TTL expiry returns them to available. The idempotency key makes client retries safe.
Layout: separate hot counters from cold metadata
Store counters as fixed 64B records in 4KB pages, 64 records per page — a 6.4 GB file for 100M items. Keep variable-length metadata in a separate append-friendly heap, with the counter record holding a pointer.
This is the single most important layout decision: the reservation path touches only the dense counters file, and each cached page carries 64 useful records instead of 2–4 records surrounded by metadata padding. Place the counters file on outer tracks (higher throughput, shorter seeks within a band), stripe pages across 3 data disks by hash(item_id) so random I/Os proceed in parallel, and give the 4th disk exclusively to the write-ahead log so its head stays purely sequential.
Indexing: one seek per cold lookup
- Dense IDs: direct addressing,
offset = item_id * 64. No index at all; one I/O when cold. - Sparse IDs: a B+tree on
item_id. At 4KB nodes and ~250 keys per node, 100M keys need ~400K leaf pages; the internal levels above are ~1,600 pages, about 6.5 MB. Pin all internal nodes in RAM, so a cold lookup costs exactly one disk read for the leaf, which holds the records themselves.
A fixed-bucket hash table also gives one seek but loses range scans (e.g. "all SKUs in a warehouse") and needs rehashing as the catalog grows, so the B+tree with pinned internals is the safer default.
Why not an LSM tree? LSM makes blind writes cheap, but reserve is a read-modify-write — you must read the current value, so read cost dominates. LSM reads can touch several levels, Bloom filters for 100M keys cost ~120 MB of RAM, and compaction steals the same scarce seeks. Update-in-place plus a WAL fits this workload better.
Caching
Budget the ~2 GB explicitly: ~10 MB B+tree internals, ~100 MB recent idempotency keys and active reservations with TTLs, ~50 MB WAL buffers, ~1.5 GB record cache.
- Cache records, not pages. Because of Zipf skew, a hot item's page neighbors are usually cold — page caching wastes ~98% of each page. At ~80B per entry including hash overhead, 1.5 GB holds ~18M records, covering the hot set at well above 95% hit rate.
- Scan-resistant eviction (CLOCK-Pro, 2Q, segmented LRU) so a nightly reconciliation scan cannot flush the hot set.
- Never evict dirty records before a checkpoint persists them; durability comes from the WAL, not the data file.
- Leave metadata mostly uncached, or give it a small separate LRU, since it is off the latency-critical path.
Write path
- Route by
hash(item_id) % Nto a single-writer shard thread — the check-and-decrement needs no locks and cannot race. - Load the record: cache hit, or one random read that blocks only that request.
- Check the condition (
available >= qty); on failure returninsufficientwith no disk write. - Mutate in memory and append a logical WAL record
{lsn, item_id, op, qty, reservation_id, idem_key}; mark dirty. - Group commit: every 2–5 ms or when the buffer fills, write the buffer sequentially and fsync once, acknowledging the whole batch after the fsync. A per-write fsync costs about one rotation (~8 ms), capping you near 120 writes/s; batching lets thousands of writes share one fsync.
- Checkpoint in the background: sort dirty pages by disk offset and write in elevator order (approaching sequential throughput), advance the checkpoint LSN, truncate the WAL, and rate-limit so foreground reads keep headroom.
Recovery: load the last checkpoint, replay the WAL from its LSN; logical ops are idempotent via a per-page LSN check. Torn pages: page checksums plus a double-write buffer or a full page image logged on a page's first modification after each checkpoint. Expiry: a RAM timer wheel emits a logged release; active reservations are logged too so they rebuild on recovery.
Read path
- Cache hit returns in microseconds — the common case.
- Miss: walk in-RAM B+tree internals to the leaf, issue one async read to the owning disk, insert into the cache.
- Metadata requests fetch through the append heap pointer and are treated as best-effort.
Concurrency and failure edges
Because each key has a single writer thread, the conditional check is trivially atomic. If I later shard across machines, I would keep affinity per key and use the version field for optimistic concurrency in update. The durable ordering is "log then mutate," so a crash mid-flight simply loses unacked requests — clients retry with the idempotency key.
Common mistakes
Caching whole pages on a skewed workload; putting metadata inline so pages hold few useful records; forgetting that fsync dominates write throughput; letting compaction or checkpoints compete with foreground seeks; and reasoning about throughput without counting seeks per operation. If you can say "this lookup is one seek because the index is pinned" and "this batch of 2,000 writes is one fsync," you have the right mental model.