Choosing and Scaling a Database
This lesson is for software engineers preparing for system design interviews who know what SQL and NoSQL are but freeze when asked "Which database would you use, and why?" The question is not a quiz about products. The interviewer wants to see you derive the choice from the data and the queries, then explain how it grows and what it costs.
By the end you will be able to pick a storage model from access patterns, explain how indexes, replicas and shards change performance, and walk through two storage decisions with numbers.
How the database question shows up
It usually arrives during the high-level design ("Where does this data live?") and again in the deep dive ("Your messages table gets 70,000 writes a second. What happens?"). On SmartIntervu's system design rubric it feeds "deep dive and scalability" and "trade-offs". Naming a database earns nothing on its own; the points come from connecting the choice to the access pattern and naming what you give up.
Start from the access patterns, not the product
Before naming any technology, write down three things:
The entities and their relationships. Users, orders, messages. Do queries join across them, or does each read touch one entity?
The queries, with rates. "Look up a URL by short code, about 4,000 times a second." "List the 50 newest messages in a conversation." The shape of the most frequent query usually decides the model.
The correctness needs. Does a write need to be atomic across several records (moving money between accounts), or is each record independent?
Then match the pattern to a model.
Relational (PostgreSQL, MySQL)
Fits data with relationships you query in more than one way, and operations that must change several rows atomically: orders and payments, inventory, user accounts. You get joins, secondary indexes, constraints and multi-row transactions. The cost is that a single node has a ceiling, and scaling writes past it means sharding, which takes away much of what made relational attractive (more on that below). Do not undersell a single relational node, though: a well-indexed PostgreSQL instance on modern hardware handles thousands of writes per second and terabytes of data, which covers many interview systems.
Document (MongoDB, and JSON columns in relational databases)
Fits records that are read and written as a whole and whose shape varies: a product catalog where each category has different attributes, a user profile with nested preferences. You trade joins and some cross-document guarantees for flexible schemas and reads that fetch everything in one call.
Key-value (Redis, DynamoDB used simply)
Fits lookups by a single key with no queries on other fields: sessions, short-code to URL mappings, feature flags. It is the easiest model to partition, because every request names its key. The cost is that any query not by key becomes a full scan or a second index you maintain yourself.
Wide-column (Cassandra, ScyllaDB, Bigtable)
Fits very high write volume with reads that follow one known pattern: "all events for this device, newest first." You design one table per query, with a partition key that spreads load and a clustering key that orders rows inside a partition. Writes are cheap and scale nearly linearly with nodes. The cost is rigidity: a new query shape often means a new denormalized table, and there are no joins.
Search index (Elasticsearch, OpenSearch)
Fits full-text search, fuzzy matching and faceted filtering. It is almost always a secondary store fed from the primary database, because it is not designed to be the source of truth. The cost is a second copy of the data that lags behind the primary by seconds.
Time-series (TimescaleDB, InfluxDB, Prometheus)
Fits append-only measurements queried by time range and aggregated: metrics, sensor readings, prices. These stores compress heavily, roll up old data and expire it automatically. The cost is weak support for updates and for queries that are not time-bounded.
Tip
Many real systems use two or three of these. Saying "PostgreSQL is the source of truth for orders, and we feed a search index for the catalog" is a stronger answer than forcing every query into one store.
Indexes: what makes reads fast and writes slower
Every index speeds up some reads and slows every write, because each insert must update each index. Know the two main storage engine families, because interviewers ask about them when write volume is high.
B-tree engines (PostgreSQL, MySQL's InnoDB) keep data in sorted pages and update them in place. Reads are predictable: each page holds hundreds of keys, so the tree is shallow and a lookup in a billion-row table touches only three to five pages, most of them already in memory. Writes cost more than the data they change, since modifying one row rewrites a whole page, typically 8 or 16 kilobytes. That extra work is called write amplification.
LSM-tree engines (Cassandra, RocksDB, ScyllaDB) buffer writes in memory, append them to a log for durability, and flush sorted files to disk. Background compaction merges those files. Writes are fast and sequential. Reads may need to check several files to find the newest version of a row, which is read amplification; bloom filters let the engine skip files that cannot hold the key. Compaction also rewrites data, so LSM engines have write amplification too, just paid later and in the background.
The interview-ready summary: B-trees favor read-heavy workloads with point and range queries; LSM trees favor write-heavy workloads such as messages, events and logs.
Transactions and isolation, briefly
A transaction makes several changes all-or-nothing. Isolation levels say how much concurrent transactions can see of each other:
Read committed (PostgreSQL's default) never shows uncommitted data, but two reads in one transaction can see different values.
Repeatable read, implemented as snapshot isolation in PostgreSQL, gives each transaction a consistent snapshot. It still allows write skew, where two transactions each read a condition, both see it satisfied, and both write.
Serializable behaves as if transactions ran one at a time. It is the safest and costs throughput, since conflicting transactions abort and must retry.
Name an isolation level when correctness matters: "Booking a seat runs at serializable, or uses a row lock with SELECT ... FOR UPDATE, so two people cannot book the same seat."
Read replicas
Replicas copy the primary's changes and serve reads, which scales read throughput roughly with the number of replicas. With asynchronous replication, which is the common default, a replica can lag from milliseconds to seconds. That breaks read-your-writes: a user edits their profile, refreshes, and sees the old version from a replica. Fixes include reading a user's own data from the primary for a short window after they write, or tracking the write's log position and only reading from replicas that have caught up. Replicas do nothing for write throughput; every write still lands on the primary.
Sharding and what it costs
When writes or data size outgrow one primary, you split the data across shards by a shard key.
Hash sharding spreads keys evenly, but range queries across keys hit every shard.
Range sharding keeps ranges together, but sequential keys such as timestamps pile onto the newest shard.
Choose the shard key so the most frequent queries touch one shard. For chat, that is the conversation ID; for a multi-tenant SaaS, the tenant ID.
The costs are the part interviewers want you to say out loud:
Cross-shard joins disappear. You denormalize, or join in the application.
Cross-shard transactions are expensive. Two-phase commit works but adds latency and blocks if the coordinator fails. Many systems instead use a saga: a sequence of local transactions with compensating actions if a later step fails.
Resharding is painful. Hashing with
key mod Nmoves almost every key when N changes. Consistent hashing, or a fixed set of many logical shards (say 1,024) mapped onto fewer physical nodes, lets you move whole logical shards instead.Hot shards still happen. An even hash does not help when one key is hot.
Worked example 1: storage for a URL shortener
Requirements: 100 million new links a month, a 100 to 1 read to write ratio, links kept for five years.
writes: 100,000,000 / (30 x 86,400 s) = about 40/s
reads: 40 x 100 = about 4,000/s
rows: 100,000,000 x 12 x 5 = 6 billion
size: 6,000,000,000 x 500 bytes = about 3 TBWeak answer: "NoSQL, because it scales."
Strong answer: The only hot query is "get the long URL for this short code," a pure key lookup, and records never relate to each other. A key-value or wide-column store keyed by short code fits exactly and partitions trivially. PostgreSQL would also work, since 40 writes a second is light, but 3 TB over five years pushes toward sharding eventually, and we would gain nothing from joins. I would use a key-value store with the short code as the key, put a cache in front because popular links take most of the reads, and keep analytics (click counts) in a separate store so they never slow the redirect path. If the product later needs "list all links for this user," I would add a second table keyed by user ID rather than scanning.
Worked example 2: storage for chat messages
Requirements: 2 billion messages a day, about 200 bytes each, read as "newest messages in this conversation, page backward."
write rate: 2,000,000,000 / 86,400 s = about 23,000/s (peak about 70,000/s)
daily data: 2,000,000,000 x 200 bytes = about 400 GB
yearly: 400 GB x 365 = about 146 TB before replicationStrong answer: This is write-heavy, append-only and read by one pattern, which is what LSM-based wide-column stores do well. The table is partitioned by conversation ID and clustered by a per-conversation sequence number, descending, so "the newest 50" is one sequential read inside one partition. A busy group conversation could grow a single partition without bound, so the partition key becomes conversation ID plus a time bucket such as the month; paging backward crosses into the previous bucket when needed. With three replicas that is roughly 440 TB a year, which argues for moving messages older than a year to cheaper storage. Conversation metadata and membership, which are small and relational, live in PostgreSQL.
Mistakes that cost points
Choosing by brand. "MongoDB because it is fast" says nothing. Derive the choice from the query and the write rate.
Sharding too early. If the numbers fit one node with replicas, say so. Premature sharding adds cost without benefit.
Ignoring replica lag. If you add replicas, say how a user sees their own writes.
Forgetting the partition that grows forever. Unbounded partitions are a classic wide-column mistake; bucket by time.
Practice it
Pick any app you used today and write its three most frequent queries with rough rates, then choose a storage model for each in five minutes.
Design a URL Shortener tests the key-value reasoning from the first example.
Design a Real-Time Chat System tests the partitioning choices from the second.
Next in this series: Caching in Depth.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Design a URL ShortenerSystem Design · Medium
- Design a Rate Limiter ServiceSystem Design · Medium
- Design Live Score Alert FanoutSystem Design · Medium
- Design a Video Upload and Transcoding PipelineSystem Design · Medium
Read next
- Caching in Depth
Place a cache, choose its read and write pattern, TTL and eviction, handle stampedes, hot keys and lookups for missing keys, and calculate how much load it takes off the database.
8 min read
- Load Balancing in Depth
Choose between Layer 4 and Layer 7, match the algorithm to the traffic, design health checks, drain long-lived connections, remove the load balancer as a single point of failure, and route users across regions.
8 min read
- Queues and Event Streams in Depth
Choose between a message queue and an event log, state delivery semantics and ordering scope, size partitions and consumers, and handle lag, poison messages and the dual-write problem.
9 min read
- Search and Geospatial Indexes in Depth
Explain inverted indexes, analyzers and ranking, keep a search index in sync with change data capture, support partial-word search, and size a find-nearby feature with geohashes or quadtrees.
8 min read
