Choosing a Database

How the main database categories store data, what each is good and bad at, how to choose from your queries, and what interviewers ask about it.

16 minLesson 1 of 7
On this page
  1. Where databases sit in a system
  2. How to choose
  3. The database categories
  4. SQL or NoSQL
  5. When one relational database is enough
  6. Using more than one store
  7. Nuances that interviewers probe
  8. In the interview
  9. What to practise next

Choosing a database means matching the way your application reads and writes data to a storage engine built for that pattern. The main categories are relational, key-value, document, wide-column, graph and time-series databases, plus search indexes. They differ in how they organise data, which queries they answer quickly, and how much consistency they guarantee. In an interview you pick one, give a reason that refers to a query or guarantee, and say what it costs.

If you pick the wrong category, the system fights its own storage. Sensor readings kept in an ordinary relational table force the database to maintain its indexes on every insert, and expiring old data means deleting millions of rows individually, while a store built for time-ordered appends drops an expired time range in one operation.

Where databases sit in a system

Application servers read and write a primary database, and other stores hold copies of data in shapes that suit other queries.Client to App servers; App servers to Primary database (reads and writes); App servers to Cache (hot reads); Primary database to Search index (copy of changes), asynchronous.ClientApp serversPrimary databaseCacheSearch indexreads and writeshot readscopy of changes

request and replyasynchronous message

Application servers read and write a primary database, and other stores hold copies of data in shapes that suit other queries.

The primary database is the system of record, the store that holds the authoritative copy. The other stores are derived from it and can be rebuilt from it.

How to choose

Start from the queries, because each category is fast at one kind of query and slow at others. Write down the three or four most important reads and writes, as described in data modeling. Then ask three questions.

  1. What are the access patterns? Records may be fetched by one key, by a time range, by following relationships, by text search, or by filters and joins that you cannot predict.
  2. What consistency does the data need? If two writes must succeed or fail together, such as taking stock and creating an order, you need transactions. If a slightly old read is acceptable, more designs are open. See transactions.
  3. How large will it get? Measure the data size and the write rate. One server handles more than most people expect.

The database categories

The boundaries between categories are not sharp, because many products support more than one data model. Each subsection below covers the data model, what the category is good at, what it is bad at, and a typical use.

Relational

A relational database stores data in tables of rows and columns with a fixed schema. Tables refer to each other through keys, queries combine them with joins, and the database enforces constraints and supports transactions that make several changes succeed or fail together. PostgreSQL and MySQL are examples. It is the best choice when the data is related, when correctness matters, and when you do not know all the queries in advance, because indexes and joins let you ask new questions without changing the storage. Data is normally normalised, so each fact is stored once. It suits orders, payments and bookings. Its weakness is that writes scale by making the primary server larger. Beyond that you need replicas for reads and sharding for writes, which loses easy joins and transactions across shards.

Key-value

A key-value store maps a key to a value that the database treats as opaque. The fast operations are get, put and delete by key, plus expiry. Redis and DynamoDB are examples. Because every request names one key, the data partitions across many nodes easily and a lookup takes about a millisecond or less. It suits sessions, carts, feature flags and lookups by id. It cannot answer "find all carts containing this product", because there is no query over the values, so such a query needs a second key that acts as an index or a different category. Secondary indexes, where a product offers them, cost extra writes and are less flexible than relational ones.

Document

A document store keeps each record as a self-contained document, usually JSON, and can index and query fields inside it. A product with its variants and attributes is one document, so one read returns everything a product page needs, and documents in a collection may have different fields. MongoDB is the common example. It fits records that are read and written whole and whose shape varies, such as a catalog. The cost appears when data is shared between documents: if a seller's name is copied into every product, renaming the seller updates all of them, and looking it up instead is a join you write yourself. Transactions across documents are limited or slower than in a relational database, so keep data that changes together inside one document.

Wide-column

A wide-column store keeps rows under a partition key, so all rows with the same key live together on the same nodes, sorted inside the partition by a clustering key. You design each table for one query. Messages might use the chat id as partition key and the message time as clustering key, so the latest 50 messages of a chat are one read from one partition. Cassandra and HBase are examples. These stores take very high write rates across many nodes and tolerate node failures, which suits messages, activity logs and event histories. They can only query efficiently by partition and clustering key, so you often keep one copy of the data per query, each with a different key, and transactions across partitions are weak or missing.

Graph

A graph database stores nodes and the relationships between them as first-class data, and queries follow relationships directly. Finding friends of friends who like a band walks edges without a join per hop. Neo4j is an example. Pick it when the important questions are paths several hops deep, such as fraud rings or recommendations. For one or two hops a relational join table is enough. Graph databases are also hard to spread over many machines, because a traversal can cross any partition.

Time-series

A time-series database is built for records stamped with a time that are appended and rarely updated, such as metrics, sensor readings and prices. It writes data in blocks ordered by time, compresses it well, computes roll-ups such as averages per minute, and expires old data by dropping whole blocks. InfluxDB and TimescaleDB are examples. It is a poor fit for data that is updated in place or looked up by anything other than time and a few labels. A relational table partitioned by day can do the job at moderate rates, because dropping an old partition is cheap, so a dedicated store is justified mainly by the write rate or the roll-up features.

Search index

A search index stores text in an inverted index that maps each word to the documents containing it, so it can answer full-text queries, rank by relevance, and filter and count by field. Elasticsearch and OpenSearch are examples. It is not a system of record: it is filled from the primary database, can be rebuilt from it, and shows new writes after a short delay. It is a poor choice for frequent updates and for transactions. See search systems for the mechanics.

SQL or NoSQL

"SQL or NoSQL" is a common opening question, and the weak answer picks one by reputation. NoSQL is a label for every category except relational, and those categories share few properties, so a good answer compares the two on what the system needs.

A relational database gives you an enforced schema, joins and transactions. A NoSQL store gives up some of those in exchange for something specific, such as easier partitioning, a flexible record shape or a layout fitted to one access pattern. If the data is related and must stay consistent, choose relational. If one access pattern dominates and the volume exceeds what one primary can write, choose the NoSQL category that fits that pattern, and keep the transactional data in a relational database.

When one relational database is enough

For most systems, and for many interview problems, a single relational database is the right answer. As a rough guide, one well-configured server handles thousands to tens of thousands of simple writes per second and several terabytes of data, and read replicas multiply the read capacity.

Moving away from it needs a reason from the numbers or the access pattern: the write rate exceeds one primary, the data is many times larger than one machine, or one simple pattern is cheaper in a partitioned store. Each extra store is another system to run, back up and keep consistent.

Using more than one store

Many real systems use several stores, each for the data it suits. A shop might keep orders and stock in a relational database, carts in a key-value store, and product search in a search index. The rule that keeps this manageable is to have one system of record for each piece of data, and to treat every other store as a copy that is derived from it.

Orders are written to the relational database, and the search index and the metrics store are filled from it asynchronously.Shop service to Orders (relational) (1. write order); Orders (relational) to Change events (2. publish change), asynchronous; Change events to Search index (3. update copy); Change events to Metrics (time-series) (3. record metric).Shop serviceOrders(relational)Change eventsSearch indexMetrics(time-series)1. write order2. publish change3. update copy3. record metric

request and replyasynchronous message

Orders are written to the relational database, and the search index and the metrics store are filled from it asynchronously.

The usual mistake is a dual write, where the application writes to the database and then to the search index in two calls. If the second call fails, the stores disagree and nothing records it. The safer pattern is to write only to the system of record and let the other stores be updated from its changes, through a change stream or an outbox table that is read and published to a queue.

Nuances that interviewers probe

A hot partition from a poor partition key

Partitioned stores spread data by hashing the partition key, so the choice of key decides whether load is even. If a chat app partitions messages by the chat id, one very busy group chat sends all its traffic to one node while others sit idle. A key such as the date puts every write of the day on one partition. Choose a key with many distinct values and an even spread of traffic, and for an unavoidably hot key add a small random suffix, accepting that reads then query several partitions.

Schemaless does not mean no schema

A document store does not check the shape of what you write, so the schema moves into the application code, and every reader must handle every old shape. Keep a version field in each document and migrate old ones in the background.

Consistency in distributed stores

Many partitioned stores replicate each record to several nodes and let you choose per request how many replicas must confirm a read or a write. Requiring a majority of replicas for both reads and writes means a read sees the latest acknowledged write, at the price of latency and lower availability during failures, while requiring one replica is faster but a read may return an old value.

In the interview

Choose the database right after you have listed the access patterns and the size of the data. Name the category, give one reason that refers to a specific query, guarantee or number, and say what would make you change your mind. Relational is the safe default, so only leaving it needs a stronger argument.

Questions to expect:

  • "SQL or NoSQL?" It depends on the access patterns and consistency needs, not on the label. For related data that needs transactions I would use a relational database. If a single access pattern dominates and the write volume is beyond one primary, I would use the NoSQL category that fits that pattern, and keep transactional data in the relational database.
  • "Can a relational database scale?" Yes, further than most people assume. Read replicas spread reads, caches absorb hot reads, and sharding spreads writes. The cost is operational work and harder queries and transactions across shards, so I would do it only when the numbers require it.
  • "How do you keep two stores in sync?" I treat one as the system of record and update the others from its change stream, or from an outbox table that is published to a queue. I avoid writing to both stores from the application, because a failure between the two writes leaves them different and nothing detects it.
  • "How would you choose a partition key?" It must appear in the main query and have many distinct values with an even share of traffic. For chat messages I would use the chat id, and I would watch for a very large group chat that becomes a hot partition.
  • "What do you lose by choosing a NoSQL store?" Usually some combination of ad hoc queries, joins and multi-record transactions. You also design the data for the queries you know, so a new query can mean a new table or a data migration.
Picking the store for a chat appStrong answer
Interviewer

Where do you store the messages?

You

The main read is the latest 50 messages of one chat, and I estimate 20,000 writes a second. So I would use a wide-column store partitioned by chat id and sorted by message time, which makes each page one partition read and spreads the writes across nodes. Users, billing and group membership need constraints and transactions, so they go in a relational database.

Interviewer

Why not put everything in the relational database?

You

At 20,000 writes a second a single relational primary would be under heavy pressure, and I would have to shard it myself. At a tenth of that load I would keep everything in one relational database, because running one store is simpler.

Quick check

A wallet app moves money between two users' balances. Which property should decide the choice of store?

A service keeps product data in a relational database and needs typo-tolerant full-text search with ranking. What is the best design?

What to practise next

The speed of whichever store you choose depends on its indexes, which Indexing covers. To see several stores chosen inside a full design, work through Design a Chat App.