AlgoViz

SQL or NoSQL

easy 24 min

The useful question is not which is better but which questions, rules and numbers this part of the system has.

Video lesson · Chapter 1 of 5

The same customer in two representations

0:00 / 3:50

Theory

Read or listen first. About 1 min.

What it is

This is a decision topic. SQL databases keep related facts in tables and answer questions you did not plan. NoSQL databases arrange data for questions you did plan, in several shapes.

The decision is made per kind of data, not once per company. A shop can keep orders in tables, sessions in a key-value store and pictures in object storage, and be simple all the same.

Why it exists

A database is hard to change later. The data outlives the code, every service learns its habits, and moving it while people use it is a project of its own.

Most arguments about it are too general. "NoSQL scales" and "SQL is safe" are both half true. The answer appears when you write down the questions, the rules that must never break, and the numbers.

A short history

  1. 1970

    Codd's paper proposes the relational model, which separates what data means from how it is stored.

  2. 2006 to 2007

    The Bigtable and Dynamo papers show very large stores without a full relational model.

  3. 2009

    NoSQL becomes the common name after a meeting organised by Johan Oskarsson.

  4. 2011

    Martin Fowler writes about polyglot persistence: different stores for different kinds of data.

  5. 2012

    Google's Spanner paper describes a global database with transactions, and weakens the old border.

Words to know

Access pattern
One question with its key, order, size and rate.
Invariant
A rule that must always hold, such as stock not below zero.
Embed
Put related data inside the parent record.
Reference
Store the other record's key and look it up.
Schema on write, on read
Shape checked when stored, or interpreted when read.
Polyglot persistence
Using several kinds of store in one system.
Source of truth
The copy that wins when copies disagree.
Dual write
Writing two stores from the app with nothing tying them together.

How it works

Step through the idea, or press Play.

Step 1 of 4

Questions. What is read and written, by which key, how often

Understand it

Start here

Packing for a trip

A traveller packs. A fitted case has a slot for each thing: tidy, quick to check, and awkward when something new must come. A soft bag takes anything, and finding things later is the price. Neither is the better luggage.

A fitted case or a soft bag
Fitted caseSoft bag

Choose by what you carry and how you look for it.

The idea

Same data, two models

Alice ordered a book and a pen. In tables, the user and the orders are separate facts joined by a key. In a document, the orders live inside the user.

Tables: users (1, Alice) and orders

orders.iduser_idproduct
11Book
21Pen
Two tables, one fact each. The name Alice is stored once.
JSON
{  "_id": 1,  "name": "Alice",  "orders": [    { "id": 1, "product": "Book" },    { "id": 2, "product": "Pen" }  ]}
One document, read in one go. Orders that grow without end should not live inside the user: MongoDB, for example, limits a document to 16 MiB.

Who answers which question easily?

QuestionTablesThis document
Alice with the ordersJoin by keyOne read
Who bought a pen?Filter orders by productAn index inside the array, or a scan
Pens sold per monthGroup and sumAn aggregation, or another system
Rename a product everywhereOne row in productsEvery document that holds it
Add a gift note to some ordersA new nullable columnJust write the field
SQL
SELECT u.name, o.productFROM users uJOIN orders o ON u.id = o.user_idWHERE u.id = 1;-- MongoDB, the same question:-- db.users.findOne({ _id: 1 }, { name: 1, orders: 1 });

Comparison

Side by side, with care

AspectSQL tends toNoSQL tends to
Data modelTables with rows and columnsDocuments, pairs, graphs, wide columns
SchemaDeclared, checked on writeFlexible, understood on read
Scaling writesUp first, then shardsOut by partition key
TransactionsFull, over many tablesOften one key or record; some products offer more
JoinsNativeLimited or none; some have lookups
Query languageA standard with dialectsOwn language or API per product
IntegrityForeign keys, checks, uniqueMostly in the application
AgeSince the 1970sModern use of the name since 2009
Best atUnknown questions, strict rulesKnown access, uneven data, high rates
The words tends to matter in every row.

Where the border blurs

  • JSON inside SQL

    PostgreSQL's jsonb stores and indexes documents in a column.

  • Transactions in NoSQL

    MongoDB has multi-document ACID transactions. DynamoDB groups up to 100 actions.

  • SQL that scales out

    Spanner and CockroachDB spread tables over machines and keep transactions.

  • Schemas in NoSQL

    MongoDB can validate documents. Cassandra tables have declared columns.

Decide

When SQL fits

  1. 1

    Complex questions

    Joins over several tables, sums, and questions nobody has asked yet.

  2. 2

    ACID over several records

    Payments and stock: several changes must happen together.

  3. 3

    Structured data

    The shape is known and shared by many programs.

  4. 4

    Reports

    Dashboards and ad hoc analysis at moderate size. Large ones belong in OLAP.

  5. 5

    Strong consistency

    Banking and bookings, where old data causes harm. See ACID.

Decide

When a NoSQL shape fits

  1. 1

    Very high rate by key

    Hundreds of thousands of operations a second that share nothing but the key.

  2. 2

    Shapes that differ

    Each record has its own fields, or they change often and few programs read them.

  3. 3

    High write throughput

    Devices, logs and events. Stores built on an LSM tree take writes well.

  4. 4

    Nested data read whole

    A page, a profile, a form: one document.

  5. 5

    Short-lived data

    Sessions and caches in a key-value store.

A path through the decision

SQL is the default because it keeps the most questions open. A default is not a law.

Examples

Six real cases

DataChoiceReason
Shop ordersSQLPayment and stock must agree
User sessionsKey-value, such as RedisLookup by id, with a lifetime
Social feedWide-column, such as CassandraMany writes, read by user and time
Financial reportsSQL, or an OLAP copy of itJoins and exact sums
Product catalogueDocument, such as MongoDBAttributes differ by product
BookingsSQLA unique rule prevents double booking
Each has exceptions. A catalogue of 20,000 products is also comfortable in PostgreSQL with a JSON column.

Numbers

Let a number decide

A shop: one million orders a day

1,000,000100,000=10/s×3=30/s at peak×4 rows=120 row writes/s\frac{1{,}000{,}000}{100{,}000} = 10/\text{s} \qquad \times 3 = 30/\text{s at peak} \qquad \times 4 \text{ rows} = 120 \text{ row writes/s}
Assume four rows per order. Scale is not an argument here, so rules and questions decide: SQL.

A feed: 100 million posts a day, 200 followers each

100,000,000×200100,000=200,000/s×3=600,000/s at peak\frac{100{,}000{,}000 \times 200}{100{,}000} = 200{,}000/\text{s} \qquad \times 3 = 600{,}000/\text{s at peak}
Copying each post into the feeds of its followers. Every write is by user, none depends on another, and losing order for a second is harmless: a store that spreads by key.

Measure what one machine of yours can take with your own rows and indexes. A load test is worth more than any number on a web page, including the ones here.

Together

Polyglot persistence

Using several stores, each for what it does best, is called polyglot persistence. This is how a large shop could look.

Seven stores in one shop

Shoppers send requests to the services of a shop. The services fetch pictures from object storage, check logins in Redis, read product pages from MongoDB and write checkouts to PostgreSQL, which holds users and orders. Changes flow from the catalogue to a search engine, and from orders to an analytics store and a graph of suggestions.
Solid arrows are part of a request. Dashed arrows are copies that arrive a little later.

Who keeps what

ServiceStoreIs it the truth?
User accountsPostgreSQLYes
OrdersPostgreSQLYes
SessionsRedisYes, but losing it only logs people out
Product catalogueMongoDBYes
SearchElasticsearchNo, a copy of the catalogue
Event analyticsCassandraNo, a copy; large sums fit OLAP better
RecommendationsNeo4jNo, rebuilt from orders
MediaS3 (object storage)Yes
Eight services share seven stores. For a small team most of this is too much: PostgreSQL, a cache and object storage go a long way.

What you gain

  • Each question is fast
  • Parts scale separately
  • A failure can stay local

What it costs

  • More systems to run, patch and back up
  • Data that disagrees for a while
  • More skills in the team
  • Harder monitoring and debugging

Keep copies in step without dual writes

One write by the app. The copy follows the log, so it cannot be silently skipped. See change data capture.

Moving

Migration in both directions

SQL to NoSQL

  • Decide what to embed and what to reference
  • Redesign queries that used joins
  • Move integrity checks into the app
  • Plan for copies that lag

NoSQL to SQL

  • Normalise records into tables
  • Define a strict schema, and clean old shapes
  • Add foreign keys after the data is clean
  • Shard later if the size asks for it

Moving while people use it

An app reads and writes the current store, which is the source of truth. Its changes go through a change stream that applies every change to the new store. The app also compares reads from the new store.
The current store stays the truth until the comparison is clean for days.
  1. 1

    Model the questions

    Write each access pattern against the new model before copying a byte.

  2. 2

    Copy and follow

    Take a snapshot at a known point, then apply changes from that point. Updates carry a version.

  3. 3

    Compare

    Read both for a share of requests and count differences. Counts and sums catch what samples miss.

  4. 4

    Switch reads

    In small steps, with a switch back.

  5. 5

    Switch writes

    Once. Feed the former store from the new one for a while, so that you can return.

  6. 6

    Remove

    After the agreed time, and after a restore test of the new store.

The migration, and its way back

Until writes switch, going back costs nothing. After that, reverse replication keeps the way open.

Embed or reference?

An address inside an order: embed. All orders inside a user: reference.

Summary

The whole topic in one minute.

Start from questions, rules and numbers. Related facts, unknown questions and rules across records point to SQL. A single known access by key, uneven records, or a write rate beyond one machine point to a specific NoSQL shape.

Both sides borrowed from each other, so compare products and settings. Add a second store only when a number or a question forces it, keep one source of truth, and feed the others from its changes.

  • Decide per kind of data: questions, rules, numbers.
  • SQL keeps unknown questions and cross-record rules easy.
  • A NoSQL shape pays off for one known access at scale or uneven data.
  • Compare products and settings; the old border has blurred.
  • Several stores need one source of truth and copies fed from its changes.
  • Migrate by snapshot, change stream, comparison, then small switches.

Sources