SQL vs NoSQL
What relational databases guarantee, what broke at web scale, and the criteria that decide which kind of store a system needs.
The problem
For about thirty years the answer to “where does the data go?” was a relational database. Edgar Codd described the relational model at IBM in 1970, and by the late 1990s Oracle, DB2, SQL Server, MySQL and PostgreSQL sat behind almost every business application.
Now picture a social app in 2008 running on one MySQL primary. It holds 400 GB and takes 6,000 writes per second at peak, and both numbers double every year. The team does what everyone did, in this order:
- Buy a bigger machine. This works until you own the biggest machine on sale, and each step up costs more than the last.
- Add read replicas. Reads spread out, but every write still goes through the one primary. See replication.
- Split the data across many MySQL servers by user id. Writes now scale. But a join between two users on different servers has to be written in application code, a transaction cannot span servers, and a schema change has to be rolled out to 64 databases. See sharding.
After step 3 the team is running a relational database with most of the relational features switched off. That observation is where NoSQL came from. Google described Bigtable in 2006 and Amazon described Dynamo in 2007. Both systems gave up joins and general transactions on purpose, and got horizontal scale and high availability in return. Open-source systems followed within a few years (Cassandra, HBase, MongoDB, Redis), and the label “NoSQL” stuck around 2009.
What a relational database guarantees
It is worth being exact about what was given up, because these features are the reason relational databases dominated.
- An enforced schema. Column types,
NOT NULL, unique keys, foreign keys and check constraints are applied by the database. Bad data is rejected once, at the door, instead of being handled by every program that reads it. - Joins and ad hoc queries. Each fact is stored once (see normalization) and combined at query time. You can ask a question nobody planned for, and the query planner works out how to answer it.
- ACID transactions across any rows in any tables. Moving money between two accounts either happens completely or not at all. See ACID and isolation levels.
- Secondary indexes on any column, kept in step with the data automatically. See indexes and B-trees.
- Maturity. Decades of tooling for backups, point-in-time recovery, monitoring and migrations, and a large pool of people who know how to run it.
The second point is the deep one. A relational schema describes the data, not the queries. The application can change, and the data stays useful.
What broke at web scale
- Writes stop scaling. One primary means one machine’s CPU, memory and disk set the ceiling for writes.
- Sharding removes the best features. Cross-shard joins and transactions are slow or impossible, as the team above found.
- Schema changes hurt on huge tables. In older MySQL versions many
ALTER TABLEoperations rebuilt the whole table and blocked writes while they ran. Teams built tools such as pt-online-schema-change and gh-ost to work around it. - Failover interrupts writes. With a single primary, a failure means seconds to minutes during which nothing can be written, and asynchronous replicas may be missing the last few commits. Dynamo was designed so that a shopping cart could always accept a write.
- Some data fits tables badly. A product catalogue where every category has different attributes becomes a wide table full of nulls or a tangle of side tables.
These limits are real, and they sit further out than many people assume. As a rough guide, one well-provisioned PostgreSQL or MySQL primary on modern hardware stores a few terabytes and serves thousands of transactions per second, more if they are simple. Most systems never outgrow that.
The NoSQL families at a glance
| Family | Data model | Examples | Typical use |
|---|---|---|---|
| Key-value | A value looked up by its key | Redis, DynamoDB, Memcached | Sessions, carts, caches, counters |
| Document | JSON-like documents with nested fields | MongoDB, Couchbase, Firestore | Catalogues, profiles, content |
| Wide-column | Partitions of rows, sorted inside each partition | Cassandra, HBase, Bigtable | Messages, event history, high write rates |
| Graph | Nodes and edges with properties | Neo4j, Amazon Neptune | Queries that follow many relationships |
The first three are covered in key-value, document and wide-column stores, and graph databases in graph, time-series and object storage.
For all their differences, the first three families share three habits:
- They partition by key as a built-in feature. Adding nodes adds capacity without application changes.
- You design for access patterns. You list the queries first and shape the tables so that each query reads one key or one partition. A query you did not plan for can be expensive or impossible.
- Many relax consistency. Replicas may disagree for a short time so that the system stays available. See consistency models and CAP and PACELC.
“Schemaless” deserves a warning. The schema does not disappear. It moves into application code, which now has to cope with every shape of record that was ever written.
The real decision criteria
“NoSQL because it scales” is not an answer. Work through five questions.
- Access patterns. Can you list the queries? A handful of fixed lookups by key suits NoSQL. Many joins, filters on arbitrary columns or reporting need SQL.
- Consistency needs. Money, stock, bookings and unique usernames need multi-row transactions and constraints. Feeds, likes, view counts and presence tolerate a short period of disagreement.
- Scale. Put numbers on data size, write rate and growth (see estimation). A few hundred gigabytes and a few thousand writes per second fit one primary with replicas. Tens of terabytes or hundreds of thousands of writes per second need partitioning, whether you build it or buy it.
- Schema flexibility. If records vary in shape or change weekly, a document model helps. A JSON column in a relational table covers many of these cases.
- Operational maturity. What can the team run at 3 a.m.? Is there a managed service? A database nobody on the team has operated is a real cost, and it belongs in the trade-off.
When to choose each, and when not to
Choose relational when the data has relationships and rules that must hold, when you cannot predict every query, and when the volume fits one primary or shards cleanly along a natural boundary such as a tenant. Do not choose it as the only store when write volume is clearly beyond one machine and access is by key, or when writes must be accepted in several regions at once.
Choose a NoSQL store when you can name the queries, each maps to a key or key range, and the volume demands horizontal scale. Do not choose it when you need joins, ad hoc queries or rules across entities, or when the scale is small. In that case you pay the modelling cost for capacity you will not use.
Most real systems use several stores. The relational database is the system of record, and other stores hold data that suits them or copies built from the record.
In the interview
The choice of database usually comes up just after the API and data model. Do not announce a product name first. Start from the data: what the entities are, which queries matter, what must never be wrong, and how big it gets.
A strong answer takes about a minute and sounds like this: “Orders and payments are relational and need transactions, and at 500 writes per second they fit one PostgreSQL primary with replicas, so that is my system of record. The order-tracking events are different: about 50,000 appends per second, always read by order id in time order, and never updated. I would put those in a wide-column store partitioned by order id. I give up joins on that data, which is fine because I never join it.”
That answer names the default, moves only the data that needs moving, gives the number that forces the move, and says what was given up. If the interviewer asks “why not just use NoSQL for everything?”, the reply is that you would be writing joins, constraints and transactions by hand in application code, for scale the orders table does not need.
Key takeaways
- A relational database gives you an enforced schema, joins, ad hoc queries and transactions across any rows. Those are worth a lot, so it is the default choice.
- What breaks first at scale is writes on a single primary. Sharding fixes that, and takes cross-shard joins and transactions away.
- NoSQL stores accept those limits from the start. In exchange they partition by key automatically and stay available when nodes fail.
- With NoSQL you design tables around the queries. A query you did not plan for may need a new table or index.
- Decide on five things: access patterns, consistency needs, scale, schema flexibility and operational maturity.
- The line has blurred. PostgreSQL stores JSON, MongoDB and DynamoDB have transactions, and distributed SQL databases scale horizontally.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What does a relational database give you that most NoSQL stores do not?
An enforced schema with constraints, joins and ad hoc queries through a planner, and ACID transactions across any rows and tables.
What breaks first when a relational database outgrows one machine?
Write throughput, because every write goes through one primary. Read replicas do not help. Sharding does, but cross-shard joins and transactions are lost.
Name the four NoSQL families with one system each.
Key-value (Redis, DynamoDB), document (MongoDB), wide-column (Cassandra, HBase, Bigtable) and graph (Neo4j).
What does designing for access patterns mean?
List the queries first, then choose keys so that each query reads one key or one partition. A new query later may need a new table or index.
What are the five criteria for choosing a store?
Access patterns, consistency needs, scale (data size and write rate), schema flexibility, and operational maturity.
Give three examples of the SQL and NoSQL line blurring.
PostgreSQL indexes JSON documents with JSONB. MongoDB and DynamoDB added multi-item transactions. Distributed SQL databases such as Spanner and CockroachDB partition data automatically.