Choosing a Database
Every system design has a box labeled "DB," and sooner or later your interviewer points at it and asks: which database, and why? A weak answer names a fashionable product. A strong answer starts from the data and how it's accessed, picks a category of database that fits, names a concrete product in that category, and states what the choice costs.
The good news is that the decision is much less mysterious than the number of databases suggests. There are about ten categories that matter, each built around a particular storage layout and access pattern. Once you know what each layout is good and bad at, the choice usually falls out of three or four questions about the workload.
We'll go through:
- The questions that drive the choice.
- Each category: how it stores data, what it's good at, where it breaks, and which product to name.
- Using several databases together, and keeping them in sync.
- Defaults and common mistakes in interviews.
Start With the Questions
Before naming anything, get answers to these. Most come straight from your requirements and back-of-the-envelope numbers:
- What are the access patterns? Lookups by a single key? Range scans ("the last 50 messages in this chat")? Ad-hoc filtering on many fields? Joins across entities? Full-text search? Aggregations over billions of rows? Graph traversals? List the 2-3 hottest queries explicitly.
- What consistency do you need? Are there invariants that must never break (no overselling, balances never negative, unique usernames)? Do you need multi-row transactions? Or is eventually consistent fine (likes, view counts, feeds)?
- How much data, how many reads and writes? 100 GB and 1,000 writes per second fits on one server of almost anything. 100 TB and 500,000 writes per second narrows the field to systems built to shard.
- How structured and stable is the data? Fixed entities with relationships, or varied documents whose shape changes per record?
- What's the read/write ratio and latency target? Sub-millisecond reads point toward memory. Write-heavy workloads point toward log-structured storage.
A useful interview habit: before choosing, say the hottest query out loud and design the storage for it. "The main read is 'get the 20 most recent posts by user X,' so we want posts clustered by user and sorted by time." That sentence alone often decides between a relational table with an index and a wide-column partition.