Skip to content

SQL vs NoSQL: How to Choose

Intermediate 17 min read Part 5 of 18

Choosing between relational and NoSQL databases by data shape, relationships, consistency, scale, query flexibility and team skill; myths, NewSQL and polyglot.

Summary#

Choose a database by asking six questions: what shape is the data, how related is it, how much consistency do you need, what scale (writes per second, data size), how flexible must queries be, and what does the team already run well. Relational databases win on relationships, transactions and ad-hoc queries; NoSQL databases win on very high write volume, simple key access at huge scale, flexible documents and specialised workloads. "NoSQL always scales better" is a myth: sharded SQL runs some of the largest sites, and NewSQL systems (Spanner, CockroachDB) offer SQL with automatic sharding. Most real systems use polyglot persistence. In an interview, start with PostgreSQL and switch only for a reason you can state with numbers.

Why It Exists#

Database choice is one of the hardest decisions to reverse; migrating a live product off a database can take a team months. It is also one of the most common interview questions, and the most common weak answer is a brand name with no reasoning. This page turns the choice into explicit criteria. It builds on NoSQL Database Types.

How It Works#

Decision criteria#

CriterionPoints to SQL (relational)Points to NoSQL
Data shapeStructured, consistent fieldsVaried or nested documents; time-series; graphs; blobs of text or vectors
RelationshipsMany entities linked many ways; joins neededFew relationships; data read as self-contained units or by one key
ConsistencyMulti-row transactions, invariants, money, inventoryEventual consistency acceptable; per-key consistency enough
ScaleUp to roughly 10k-20k writes/s and a few TB per primary (more with sharding)100k+ writes/s, hundreds of TB, multi-region active-active
Query flexibilityAd-hoc queries, reporting, unknown future questionsAccess patterns known and stable up front
Team skillTeam knows SQL and the operational toolingTeam has run the chosen NoSQL system in production

Work through them in order, and write down the deciding factor. Often one dominates: "we need multi-row transactions" or "we need 500k writes per second across three regions".

A short history: from SQL to NoSQL and back to the middle#

Knowing how the field got here explains why the advice today sounds balanced.

  • 1970s-1990s: relational wins. Codd's model, System R and commercial products (Oracle, DB2, later SQL Server, MySQL and PostgreSQL) displaced hierarchical and network databases. For thirty years, "database" meant "relational database".
  • 2004-2008: web scale. Google, Amazon and Facebook hit workloads no single machine could serve. They published Bigtable (2006) and Dynamo (2007), and open-sourced Cassandra (2008). These systems gave up joins and general transactions to partition across thousands of cheap machines and stay available through failures.
  • 2009-2012: the NoSQL wave. The term "NoSQL" was popularised by a 2009 San Francisco meetup organised by Johan Oskarsson on open-source distributed databases. MongoDB (2009), Redis (2009), Riak, CouchDB and HBase spread quickly, helped by the rise of JSON APIs and agile development. For a few years many teams adopted them by default, sometimes for workloads a single PostgreSQL server would have handled.
  • 2011-2015: the correction. Teams discovered the cost of missing transactions and joins as their products grew. Analyst Matthew Aslett coined "NewSQL" in 2011 for systems seeking SQL and ACID at scale. Google published Spanner (2012) and F1 (2013), showing that global, consistent SQL was possible. CockroachDB, TiDB and YugabyteDB followed.
  • 2015-today: convergence. NoSQL systems added transactions, schemas, SQL-like query languages and stronger consistency options. Relational systems added JSON, horizontal scaling layers, and managed cloud versions with distributed storage (Aurora, AlloyDB). The categories now overlap so much that the useful question is about specific properties: partitioning, replication, transaction scope and query model.

The pattern repeats a lesson from the IMS-versus-relational era: specialised models win for specific access paths, and general models win when requirements change. Most organisations need both.

Hybrid designs inside one relational database#

Before adding a second database for flexibility, consider mixing models within PostgreSQL. A product catalogue where every category has different attributes can keep its common fields typed and constrained, and put the variable part in a JSONB column:

CREATE TABLE products (
  id          bigint PRIMARY KEY,
  category    text NOT NULL,
  name        text NOT NULL,
  price_cents integer NOT NULL CHECK (price_cents >= 0),
  attributes  jsonb NOT NULL DEFAULT '{}'    -- e.g. {"screen_in": 6.1, "color": "blue"}
);
CREATE INDEX products_attrs ON products USING gin (attributes jsonb_path_ops);
-- find blue phones under 500 dollars
SELECT id, name FROM products
 WHERE category = 'phone' AND price_cents < 50000
   AND attributes @> '{"color": "blue"}';

Price and category keep their types and constraints. The GIN index makes containment queries on attributes fast. A frequently filtered attribute can be promoted to a generated column with a normal B-tree index once it proves important. This hybrid captures most of the document model's flexibility, while orders, inventory and payments in the same database still get joins and transactions. The limits appear at very large scale or with heavy partial updates to big JSON values, because PostgreSQL rewrites the whole value on every change.

Applying the criteria: three worked decisions#

The criteria are easiest to learn by watching them decide real cases. In each one, a single criterion ends up dominating.

1. A ticket-booking system. Entities: events, venues, seats, bookings, payments. Peak load is high but short: a popular on-sale might bring 50,000 booking attempts per minute, about 800 per second, though reads of seat maps are 100 times higher. The deciding criterion is consistency. If a network partition lets two users each see seat 14C as free and both book it, two people turn up for one seat. That is a business failure, not a glitch. The same reasoning applies to e-commerce inventory (one toothbrush left, shown as available to many buyers) and to financial systems such as trading order books, where a stale view leads to trades at the wrong price. Choice: a relational primary with transactions and a unique constraint on (event, seat). Seat-map reads come from a cache that may be a second stale, and the final check happens in the transaction.

2. A chat service with 1 billion messages a day. That is about 11,600 writes per second on average, perhaps 50,000 at peak, and growing. Messages are self-contained, always read by conversation in time order, rarely updated, and losing strict ordering across conversations is acceptable. The deciding criterion is scale with a known access pattern. Choice: a wide-column store such as Cassandra or ScyllaDB, partitioned by (conversation, time bucket). User accounts and group membership, which are relational and change rarely, stay in PostgreSQL.

3. An ad-click analytics dashboard. At 10,000 clicks per second, the naive design stores each click as a row in the transactional database and answers advertiser queries with SELECT COUNT(*), COUNT(DISTINCT user_id) ... WHERE ad_id = 123 AND ts BETWEEN ... GROUP BY .... That design fails twice over. The write stream alone is 864 million rows a day, which bloats indexes and competes with transactional traffic. Each dashboard query scans millions of rows, which is far too slow for interactive use. The deciding criterion is query shape: analytical aggregation, not transactional lookup. Choice: a write-optimised event store or a stream, plus pre-aggregation into an OLAP engine built for GROUP BY over billions of rows.

Notice that "SQL or NoSQL" was never the real question. The answers were "a relational database for invariants", "a partitioned log-structured store for a firehose of append-only data", and "a columnar analytics engine for aggregation". Naming the workload type precisely is the skill being tested.

Data shape and relationships#

If your entities reference each other in many directions (users, orders, products, reviews, coupons), the relational model fits naturally: store each fact once, join when reading. In a document store, the same data either duplicates (product name copied into every order) or needs several queries and joins in application code.

If data is naturally a self-contained unit, such as a product with hundreds of optional attributes, a game save, or a chat message, documents or key-value records fit and avoid needless tables.

Data shape and relationships in depth#

The debate is fifty years old. Before relational databases, IBM's IMS (1960s) stored data as hierarchies, trees of records much like nested JSON documents, and CODASYL "network" databases linked records with pointers. Both were fast for the access paths they were designed for and painful for new ones, because a program had to navigate the pointers by hand. Codd's relational model won in the 1980s largely because declarative queries made new access paths cheap. Document databases revived the hierarchical model in the 2000s for the same reason it was attractive in the 1960s: when data really is a tree read as a whole, a tree is the fastest representation. The lesson carries forward: trees are great until the relationships stop being trees.

How products drift towards many-to-many. A product often begins with data that looks hierarchical. A user has posts, and a post has comments. Then features arrive. Comments mention other users. Posts are shared into groups. Users follow tags. A recommendation feature needs "posts liked by people similar to me". Each step adds a cross-cutting relationship that does not belong inside any single document. In a document store you then choose between duplicating data, which brings update anomalies when a user renames themselves and must be fixed in thousands of embedded copies, and storing references, which means joins in application code with many round trips. Sarah Mei's widely read 2013 essay "Why You Should Never Use MongoDB" described exactly this drift in a social network project, and it remains a useful caution. The reverse case is real too: a product catalogue where each category has different attributes is awkward as a table with hundreds of mostly null columns, and natural as documents or a JSONB column.

The object-relational mismatch. Application code works with nested objects, and relational tables are flat. ORMs bridge the gap but can hide costs, such as the "N+1 queries" problem, where loading 100 orders and then each order's items issues 101 queries. Document stores reduce this mismatch for data read as a unit, which is a genuine productivity benefit. Relational databases have narrowed the gap with JSON columns and JSON aggregation functions (json_agg in PostgreSQL) that return nested results in one query.

A useful test. List your top ten queries. If nearly all of them fetch one entity and its children by ID, the data is document-shaped. If several of them filter, sort or aggregate across entities ("all orders over 100 dollars this week with products in category X"), it is relational-shaped. If one or two queries dominate traffic by orders of magnitude and are simple key lookups, consider a key-value store for those paths specifically.

Consistency#

Relational databases give ACID transactions over any rows by default. Many NoSQL systems give atomicity per item or partition, with eventual consistency across replicas. DynamoDB and MongoDB now offer transactions, but with limits (item counts, performance cost). If correctness depends on several records changing together (debit and credit, booking and seat), prefer relational or NewSQL. See ACID and Isolation Levels.

Consistency in depth#

Decide per piece of data, not per system. Consistency requirements differ even within one product, so the question to ask is, for each kind of data, "what happens if a user sees an old value, or if two writes conflict?"

DataCost of staleness or conflictNeeded
Seat or ticket bookingDouble booking, refunds, angry customersStrong, transactional
Inventory at checkoutOverselling, cancelled ordersStrong at the decrement
Account balances, paymentsMoney lost or createdStrong, transactional, auditable
Trading order bookTrades at wrong pricesStrong, low latency
Product listing page stock badgeSlight confusion, fixed at checkoutSeconds-stale is fine
Social feed, likes, view countsNobody noticesEventual
User's own profile editUser thinks the save failedRead-your-writes
Comments on a postA reply shown before its parent looks brokenCausal

This table usually produces a mixed design: a strongly consistent store for the first few rows, and caches, replicas or eventually consistent stores for the rest.

Here is what goes wrong when a booking system runs on a store that favours availability during a partition:

A consistency-first design would make one side refuse or wait: replica B cannot reach the majority, so it rejects the booking. User 2 sees an error, which is far cheaper than a double booking. The same reasoning tells you not to pay that price for likes or view counts.

Connecting this to CAP. During a network partition, a replicated system must either refuse some requests (choosing consistency) or answer them with possibly stale data (choosing availability). Booking, inventory and finance systems should usually choose consistency, failing a few requests rather than selling one seat twice. Feeds, likes and reviews should choose availability. PACELC adds the everyday trade-off: even with no partition, stronger consistency costs latency, because a write must reach more replicas before it is acknowledged. See CAP Theorem and PACELC.

What "strong" costs in each family.

  • A single relational primary gives strong consistency on the primary almost for free, but reads from asynchronous replicas are stale by the replication lag.
  • DynamoDB's strongly consistent reads cost twice the capacity of eventual ones and are served only from the partition leader.
  • Cassandra at QUORUM waits for the second-fastest of three replicas, so its p99 latency tracks the slower nodes.
  • NewSQL systems give serializable transactions at the price of consensus round trips, within a region a few milliseconds and across regions tens to hundreds.

A common trap is to choose an eventually consistent store for scale and then rebuild transactions on top of it in application code, with locks in Redis, retries and compensation logic. If you find yourself designing a distributed lock to keep two rows in step, that is usually a sign the data belongs in a transactional database, or that the two rows should live in one partition where the store can update them atomically.

Scale#

Run the numbers. A product with 10 million daily users posting twice a day makes about 230 writes per second on average, perhaps 1,000 at peak. One Postgres primary handles that easily. NoSQL becomes the right answer at sustained write rates in the tens or hundreds of thousands per second, data sizes in the hundreds of terabytes, or when every region must accept writes during a network partition. See Back-of-the-Envelope Estimation.

Scale in depth#

Three different kinds of scale. "Will it scale?" hides three separate questions, and they have different answers:

  1. Read throughput. Relational databases scale reads well. Add indexes so queries touch few pages, upgrade hardware so the working set fits in RAM, denormalise hot joins, add read replicas (each adding roughly the primary's read capacity), and put a cache in front, which commonly absorbs 90% or more of reads. This ladder handles hundreds of thousands of reads per second without changing the database. See Pattern: Scaling Reads.
  2. Write throughput. Every write must reach the primary that owns the row. One well-provisioned PostgreSQL or MySQL primary commonly handles thousands to tens of thousands of transactional writes per second. Beyond that, you shard, either by hand or with Vitess or Citus, or choose a system that partitions natively: Cassandra, DynamoDB, or a NewSQL database. See Pattern: Scaling Writes.
  3. Data volume. A single node holds a few to perhaps tens of TB comfortably. Past that, backups, restores, index builds and replica creation take hours to days, which hurts recovery time even if queries are fine. Partitioning by time with archiving, or sharding, keeps each unit manageable.

When queries slow down as data grows. A common real-world path: a query that took 5 ms at 1 million rows takes 800 ms at 200 million rows. The cause is rarely "SQL doesn't scale". It is usually one of these:

  • a missing or unusable index, for example one on (status) when the query filters on status and sorts by created_at;
  • a working set that no longer fits in memory, so pages come from disk;
  • a query whose result grows with the data, such as an unbounded OFFSET pagination or a count over everything.

The fixes work in any database:

  • composite indexes that match the filter and sort;
  • keyset pagination (WHERE created_at < $last ORDER BY created_at DESC LIMIT 20);
  • partitioning by time, so recent queries touch only recent partitions;
  • archiving cold data;
  • precomputing aggregates.

Find the actual bottleneck first. In layered systems, adding capacity to the wrong layer does nothing. A workflow engine such as Temporal shows this clearly. Millions of long-running workflows can sit waiting with no compute assigned, so adding workers helps when the backlog is work ready to run. But if the bottleneck is the rate of state updates in the persistence layer, adding workers does not help at all, and you need more capacity in the database behind the service. The same is true of any architecture. Measure whether the database is limited by CPU, I/O, locks, connections or replication before deciding it needs replacing. See Temporal and Workflow Engines.

Worked thresholds. A rough guide for a single relational primary on modern cloud hardware. It is an order of magnitude, not a promise:

WorkloadComfortable on one primaryTime to plan the next step
Simple transactional writesUp to about 5,000-10,000 per secondSustained above about 20,000 per second
Indexed point reads (with replicas and cache)Hundreds of thousands per secondRarely the deciding factor
Data sizeA few TBAbove about 10 TB, or when a restore exceeds the RTO
Regions accepting writesOneSeveral, active-active

If your estimate sits well inside the first column, the scale criterion points to relational by default, and the other criteria decide.

Query flexibility#

SQL lets you ask new questions of old data: "revenue by country for users who signed up in March". NoSQL models are designed around specific queries; a new query often means a new table or index and a backfill. If the product is young and requirements change weekly, flexibility is worth a lot.

Query flexibility in depth#

OLTP versus OLAP is a bigger divide than SQL versus NoSQL. OLTP (online transaction processing) workloads run many small queries that touch a few rows each, by key or index: "load order 981", "insert this payment". OLAP (online analytical processing) workloads run few large queries that scan and aggregate millions or billions of rows: "revenue by country by week for the last two years". Row-oriented databases, whether PostgreSQL, MySQL, MongoDB or Cassandra, are built for OLTP. Columnar engines such as BigQuery, Snowflake, Redshift, ClickHouse and Apache Druid store each column separately and compressed, so a query that reads 3 of 40 columns reads about 3/40 of the data and runs vectorised over it. Running heavy analytics on the OLTP primary both performs badly and harms the transactional traffic. The ad-click example above is the classic interview version of that mistake.

How each family handles a new question.

  • Relational: write a new query, perhaps add an index (built online in minutes to hours), done.
  • Document (MongoDB): add a secondary index and query on it. Aggregation pipelines cover many reporting needs, with weaker joins.
  • DynamoDB: add a global secondary index, which is backfilled automatically, and pay its write cost forever. Queries outside any key or index need a full table scan, which is slow and expensive.
  • Cassandra: create a new table keyed for the query, write to it on every update, and backfill it. Secondary indexes exist but suit only narrow cases.
  • Any of them: stream changes into a warehouse or search index through CDC, and ask ad hoc questions there.

That last option is why many teams accept a rigid operational store. Flexibility comes from a second system built for questions, and the operational store only has to serve the product's known paths quickly. The price is a pipeline with minutes of lag and its own operations.

Uncertainty favours flexibility. For a young product, the most expensive mistake is a data model that makes next month's feature impossible. For a mature, well-understood, high-volume path, such as message storage or click logging, a rigid model optimised for that path is a good trade. Many companies follow exactly this arc: start fully relational, then carve out specific high-volume paths into specialised stores once their access patterns have stopped changing.

Team skill#

A database the team knows how to back up, monitor, tune and recover beats a theoretically better one they do not. Operational maturity, and the availability of a managed service, are legitimate deciding factors.

Team skill and operational cost in depth#

The total cost of a database is mostly people. Licences and servers are visible costs. The larger costs are:

  • learning to model data well for it;
  • tuning it under load;
  • upgrading it without downtime;
  • backing it up and proving restores work;
  • debugging it at 3 a.m.;
  • hiring people who know it.

A team of six that knows PostgreSQL deeply will usually run a better system on it than on a technically superior database they adopted last month. Every additional database multiplies these costs, which is why mature engineering organisations often keep an approved short list of datastores.

Managed services shift the equation. With Amazon RDS or Aurora, Cloud SQL, AlloyDB, DynamoDB, MongoDB Atlas, Astra or Keyspaces, the provider runs replication, failover, patching and backups. That makes specialised stores far cheaper to adopt than they were a decade ago. It does not remove the need for modelling skill: a badly keyed DynamoDB table throttles in production just as surely as a self-hosted one would. Managed services also create cost risks, such as on-demand pricing at high steady traffic, cross-region replication charges and per-index write costs, and they create lock-in.

Ecosystem matters. Look at more than the engine:

  • drivers in your languages and ORM support;
  • CDC connectors (Debezium supports PostgreSQL, MySQL, MongoDB, SQL Server, Oracle and others);
  • backup tooling, monitoring exporters and migration tools;
  • local development, for example running it in a container for tests.

PostgreSQL's ecosystem breadth is a large part of why it is the default recommendation.

Questions to ask before adopting a new datastore:

  1. Who will be on call for it, and have they run it in production before?
  2. How do we back it up, and how long does a full restore take?
  3. How do we upgrade it with no downtime?
  4. What happens when a node, a zone or a region fails?
  5. How do we get data in and out, for migration, analytics and deletion requests?
  6. What will it cost at 10x today's traffic?

If several answers are "we don't know yet", the new database's theoretical advantages have to be large to justify it.

Myths#

  • "NoSQL always scales better." NoSQL systems make horizontal scaling easier by restricting the data model. Relational databases scale a long way vertically and with replicas, and can be sharded: Instagram has described sharding PostgreSQL to store its data, and many large sites shard MySQL. What does not scale is unbounded joins across shards, in any database.
  • "NoSQL is faster." A key lookup in Postgres with an index takes about a millisecond, like a key-value store. Speed comes from the access pattern and data layout, not the label.
  • "NoSQL means no schema." The schema moves from the database into application code (schema-on-read). You still need to manage it, and old records in old shapes.
  • "SQL databases cannot handle JSON." PostgreSQL's JSONB supports indexing and querying of nested documents.
  • "NoSQL has no transactions." Many now do, within limits.

Myths in depth#

"NoSQL always scales better", examined. NoSQL databases make horizontal scaling easier by removing features that are hard to distribute: cross-partition joins, multi-row transactions on arbitrary rows, and secondary indexes that must stay consistent. They have not discovered a way to scale those features cheaply. They simply do not offer them, or offer them at a cost. A relational database that you use the same way, where every query includes the shard key, no cross-shard joins happen, and each transaction stays within one shard, scales horizontally too. That is exactly what Vitess, Citus and hand-built sharding layers do. Large-scale evidence:

  • YouTube built Vitess to shard MySQL.
  • Facebook serves its social graph from sharded MySQL behind the TAO cache.
  • Instagram sharded PostgreSQL by user.
  • Shopify splits merchants across many MySQL "pods".

The honest version of the claim is "NoSQL systems make the scalable subset of operations the only operations, so you cannot accidentally write a query that does not scale". That is a real benefit, but a different one.

"Joins are slow." An indexed join between an order and its 5 items costs a handful of index lookups, well under a millisecond with warm caches. Joins become slow when they are unbounded, touching millions of rows, or when they cross machines. Avoid those patterns, and joins are one of the most efficient operations a database performs.

"NoSQL databases lose data." This reputation came from early defaults. Some early MongoDB drivers returned before the server acknowledged a write, and early versions acknowledged writes before they were journaled or replicated. Modern versions default to majority write concern (MongoDB 5.0 and later). Any database can lose data if configured for speed over durability: asynchronous replication, relaxed fsync settings or w: 1. Durability is a configuration choice to examine in every system, relational ones included.

"Eventually consistent means unusable for important data." Cassandra at QUORUM, DynamoDB with strongly consistent reads and conditional writes, and MongoDB with majority concerns all provide strong per-key guarantees. What they lack is cheap multi-key transactions. Many important workloads, such as idempotency keys, user settings and device state, need only per-key correctness.

"We need NoSQL for flexible schemas." PostgreSQL's JSONB columns, with GIN indexes on their contents, give schema flexibility exactly where it is needed while the rest of the table stays typed and constrained. Conversely, document databases need schema management too: validation rules, versioned documents and migrations. Flexibility is a property of the design, not the product category.

NewSQL#

NewSQL (distributed SQL) databases keep SQL, relational schemas and serializable transactions, but shard and replicate automatically across nodes and regions, using consensus (Paxos or Raft) per data range.

SystemNotes
Google SpannerGlobal, externally consistent transactions using TrueTime clocks; managed on Google Cloud
CockroachDBPostgreSQL wire-compatible, serializable by default, Raft per range
TiDBMySQL-compatible, separate storage layer (TiKV)
YugabyteDBPostgreSQL-compatible query layer on a distributed store
Amazon Aurora DSQLManaged distributed SQL with PostgreSQL compatibility

The cost is latency: a write must reach a quorum of replicas, so a cross-region write pays one or more cross-region round trips (tens to hundreds of milliseconds). They also cost more to run than a single Postgres node. They fit when you need relational semantics and more write scale or geographic distribution than one primary can give.

NewSQL in depth#

Architecture in one picture. Most distributed SQL databases share a layered design. A stateless SQL layer parses and plans queries. Underneath, a transactional key-value layer splits the keyspace into ranges (CockroachDB) or tablets (Spanner, YugabyteDB, TiKV regions) of roughly 64-512 MB, and replicates each one with its own consensus group (Raft or Paxos), usually 3 or 5 replicas. Each range has a leader, or leaseholder, that serves consistent reads and coordinates writes. Ranges split when they grow or get hot, and they move between nodes automatically, which is the "automatic sharding" that hand-sharded MySQL lacks.

Transactions across ranges. A transaction touching rows in two ranges writes provisional values, called intents in CockroachDB, in both, then flips a single transaction record to committed. This is a form of two-phase commit, made fault-tolerant because each participant is itself a replicated consensus group, not a single machine that can vanish. Timestamps order transactions. Spanner uses TrueTime, GPS and atomic-clock-backed time with an explicit uncertainty bound of a few milliseconds, and waits out that uncertainty before making commits visible ("commit wait"), which yields external consistency. CockroachDB uses hybrid logical clocks on ordinary NTP-synchronised servers, and handles uncertainty by occasionally restarting reads that encounter values inside the uncertainty window.

The papers. Google's "Spanner: Google's Globally-Distributed Database" (Corbett and colleagues, OSDI 2012) described the system. "F1: A Distributed SQL Database That Scales" (Shute and colleagues, VLDB 2013) described the SQL database built on it to run Google's advertising business, which had previously used sharded MySQL. Its stated motivation was the pain of resharding MySQL and the need for consistent transactions at that scale.

Latency in practice. Within one region, a single-row write needs a consensus round across availability zones, typically a few milliseconds, compared with under a millisecond for a local commit on a single Postgres node. A multi-region transaction pays cross-region round trips: about 60-80 ms between US coasts, more across oceans. NewSQL products therefore offer data placement controls. CockroachDB, for example, can pin rows to regions ("regional by row") so that most transactions stay local, or replicate reference tables everywhere ("global tables") for fast reads with slower writes.

When NewSQL is the right answer:

  • you need relational semantics and write scale beyond one primary;
  • you need survival of a zone or region failure with zero data loss and automatic failover;
  • data residency rules require pinning users' rows to their region;
  • you want to avoid building and operating a sharding layer.

When it is not: the workload fits one Postgres primary, or latency per transaction must stay sub-millisecond. NewSQL also has pitfalls:

  • hot ranges from sequential primary keys: use UUIDs or hash-sharded indexes;
  • transaction retries under contention, because serializable is the default;
  • compatibility gaps with PostgreSQL or MySQL extensions and features;
  • higher cost per unit of throughput than a single node.

See Multi-Region Data and Distributed Transactions.

Polyglot persistence#

Polyglot persistence means using several databases, each for what it does best, inside one system:

Keep one source of truth per piece of data and feed the others from it (change data capture, events), so copies can be rebuilt. Each extra database adds operational cost, so add one only for a clear need.

In the diagram, only PostgreSQL, Redis's rate-limit counters, object storage and Cassandra hold original data. Elasticsearch and the warehouse are derived and can be rebuilt by replaying change data capture from a snapshot.

Polyglot persistence in depth#

The term was popularised by Martin Fowler and Pramod Sadalage around 2011, borrowing from "polyglot programming": use different storage technologies for different needs within one system. It is now the normal shape of production architectures, and its hard part is not choosing the stores but keeping them in agreement.

Never dual-write naively. The tempting approach is for the application to write to PostgreSQL and then to Elasticsearch, or to the database and then to a cache. If the process crashes between the two writes, or the second write fails, the stores silently diverge. Retrying does not fully help, because two concurrent requests can apply their second writes in the opposite order from their first. Robust patterns instead:

  • Change data capture: read the source database's log and apply every change, in order, to the derived stores. The database's commit order becomes the order everyone sees.
  • Transactional outbox: in the same transaction as the business write, insert an event row into an outbox table. A relay publishes outbox rows to Kafka, and consumers update their stores. Atomicity comes from the single local transaction.
  • Event-sourced pipelines: the event log is the source of truth, and every store, including the relational one, is a projection of it.

See Change Data Capture and the Outbox and Event Sourcing and CQRS.

Make every derived store rebuildable. If the search index or the cache can be rebuilt from the source of truth (replaying CDC from a snapshot, or rescanning the table), then bugs, schema changes and corruption in derived stores are recoverable inconveniences rather than data loss. Write down, for each store, "if this disappears, how do we rebuild it, and how long does it take?"

Expect and expose lag. Derived stores trail the source by milliseconds to seconds, sometimes minutes during incidents. Design the product for it. After a user edits a listing, show the edited version from the primary on their own page, even if search results lag for a few seconds.

The counter-movement: fewer databases. Partly in reaction to sprawl, many teams now push PostgreSQL further, using JSONB for documents, tsvector for search, PostGIS, pgvector, partitioned tables for time series, and even SKIP LOCKED queues. They add a specialised store only when a workload clearly outgrows it. Both philosophies are reasonable. The deciding factor is operational capacity. A five-person team gains a lot from running one database, while a large organisation with platform teams can afford purpose-built stores everywhere.

The interview default#

"I'll start with PostgreSQL" is a strong default because it covers transactions, joins, JSON, full-text search, geospatial queries and vectors, and scales to thousands of writes per second on one node. Move away from it when you can name the reason: "100k writes per second of append-only events", "global active-active writes", "full-text relevance ranking". Interviewers reward the reasoning, not the brand.

The interview default in depth#

Why Postgres is the safe opening move. It handles transactions, joins, constraints, JSON documents, full-text search, geospatial queries, vectors and time-partitioned tables, and every interviewer knows it. Starting there lets you spend the interview on the interesting parts of the design rather than defending an exotic choice. It also shows judgement: you do not add complexity without a reason.

A defensible script, with numbers:

  1. "Core entities are A, B, C with these relationships. Writes peak at about N per second, and the data reaches about X TB in three years."
  2. "That fits a single PostgreSQL primary with replicas, so that's my default. Here are the tables, keys and the two indexes that serve the main queries."
  3. "The one path that doesn't fit is P: 80,000 append-only events per second, read by user and time. That goes to Cassandra, or Kafka plus a warehouse if it's for analytics."
  4. "Search and analytics are derived stores fed by CDC, so the relational database stays the source of truth."

Reasons to open with something else. It is fine to start elsewhere when the problem's core is obviously a specialised workload:

  • a key-value cache design starts with in-memory hash tables;
  • a metrics system starts with a time-series store;
  • a chat system at WhatsApp scale starts with a partitioned message store;
  • a URL shortener with heavy reads may justify DynamoDB keyed by short code.

Even then, say why in one sentence. Some interviewers also prefer DynamoDB as a default because it is managed and scales without sharding work. That is a reasonable choice if you discuss its access-pattern constraints.

Signals interviewers listen for: you estimated before choosing; you named the deciding criterion; you knew the chosen database's limits (partition throughput, item size, replica lag); you separated the source of truth from derived stores; and you said what would make you change your mind.

Signals that your database no longer fits#

Database decisions should be revisited at each 10x of growth, but certain symptoms say "now" regardless of the calendar:

  • The primary's CPU or I/O stays above about 70% at normal peak after indexing, query fixes and a hardware upgrade, and write volume is still growing. Read scaling tricks will not help with writes. It is time to plan sharding, a write-optimised store for the heaviest stream, or a distributed SQL system.
  • Replication lag regularly exceeds what the product tolerates, for example several seconds during peaks, so read-your-writes workarounds keep spreading through the code.
  • Restores or replica rebuilds take longer than your recovery-time objective. A 15 TB database that takes 20 hours to restore is a business risk even if every query is fast.
  • Application code is rebuilding database features: hand-written joins across collections, distributed locks to keep records in step, or ad hoc consistency checks and repair jobs. That suggests the data model and the store have drifted apart, often towards needing a relational store.
  • One access path dominates cost. For example, 90% of writes are append-only events that nobody updates, which belong in a store built for them.
  • Schema changes have become feared, taking weeks of planning because of table size or tight coupling. This calls for better migration tooling or partitioning first, and a new database only if that fails.

None of these automatically means "switch databases". The first response is usually to fix the specific bottleneck: add a cache, a replica, a partition or a specialised store for one path. A full migration of the primary store is the last resort, because it is expensive and risky, as the deep dive on migration below describes.

When to Use It#

  • Every time a design needs a primary data store.
  • When adding a secondary store (search, cache, analytics), to justify it.
  • When reviewing whether an existing database still fits as the product grows.

When NOT to Use It#

  • Do not rerun this decision for every small feature; extend the existing database when it fits.
  • Do not pick a database before you know the access patterns and rough scale.

How to Implement It#

  1. List entities, relationships and access patterns, with read and write rates.
  2. Estimate scale: peak writes per second, total data size in 3 years, regions.
  3. Apply the criteria and write down the deciding factor in one sentence.
  4. Default to a managed relational database; add purpose-built stores for specific needs.
  5. Keep one source of truth and feed copies through CDC or events.
  6. Revisit at each 10x growth step.
TechnologyFits when
PostgreSQL / MySQLDefault primary store
DynamoDBKey-value at any scale, serverless, known patterns
Cassandra / ScyllaDBMassive write volume, multi-region
MongoDBDocument-shaped data with rich queries
CockroachDB / SpannerRelational plus horizontal or global scale

Common system types and their usual stores#

These pairings come up again and again in design work. Treat them as starting points to justify, not rules.

Social network. Users, profiles, follow relationships and posts start relational, sharded by user ID at scale. Timelines, precomputed feeds per user, are often lists in Redis or rows in a wide-column store keyed by user. Media goes in object storage, search in Elasticsearch, and the social graph's one- and two-hop queries in indexed adjacency tables plus a cache, rather than a graph database.

E-commerce. Orders, payments and inventory need transactions, so they go in a relational store. Product catalogue attributes go in documents or JSONB. Carts and sessions go in a key-value store with TTL. Search and facets go in a search engine, and recommendations use vectors or a separate service.

Messaging and chat. Messages are append-heavy and read by conversation and time, which suits a wide-column store with time buckets. Presence and typing indicators live in in-memory stores with short TTLs. Group membership and accounts are relational.

IoT and monitoring. Readings are time-stamped and append-only, with retention and downsampling, so they belong in a time-series database or a columnar analytics store. Device registry and ownership are relational.

Gaming. Player accounts and purchases are relational. Leaderboards are Redis sorted sets. Game state per match or session lives in memory or in a key-value store. Telemetry goes to an event stream and a warehouse.

Financial ledger. Append-only, double-entry, strongly consistent and auditable: a relational database, or a purpose-built ledger on top of one. Correctness beats every other criterion. NewSQL suits it when multi-region strong consistency is required.

Content management and publishing. Articles have varied structure and are read as whole units, which fits documents or relational tables with JSONB. The read-heavy delivery path is served from caches and a CDN.

Ride hailing and delivery. Trips, payments and accounts are relational. Live driver locations, updated every few seconds, live in an in-memory geospatial index. History goes to a stream and a warehouse.

URL shortener. Mapping a short code to a URL is a pure key lookup at very high read rates, which suits a key-value store or a relational table with a primary key, fronted by a cache. Either works at moderate scale. A managed key-value store removes sharding work at very large scale.

The recurring pattern: a relational core for entities and invariants, plus one or two specialised stores for the workload that defines the product.

Two criteria people forget: latency and compliance#

Latency targets. The six criteria cover most decisions, but a hard latency budget can override them. If a feature must answer in under 10 ms at p99, as an ad auction, a game server or a fraud check in the payment path must, then the store's tail latency matters more than its feature set. In practice:

  • An in-memory store answers in well under a millisecond plus network time.
  • A key-value or wide-column store on SSDs answers in low single-digit milliseconds.
  • An indexed relational query on a warm cache takes a millisecond or two.
  • Anything involving cross-region consensus pays tens of milliseconds.

Global user bases add physics. A user in Sydney reading from a database in Virginia waits roughly 200 ms per round trip, whatever the database. So the latency criterion often turns into a placement question: read replicas or caches near users, or a database that keeps each user's data in their home region.

Data residency, privacy and deletion. Regulations such as the EU's GDPR, and sector rules in finance and health, can require that personal data stays within a jurisdiction, can be exported on request, and can be fully deleted. These requirements shape database choice:

  • Residency: can the system pin rows or partitions to a region? Distributed SQL databases with row-level placement, or one database deployment per region, make this straightforward. A single global table replicated everywhere does not.
  • Deletion: in a polyglot architecture, "delete this user" must reach the primary, every cache, the search index, the warehouse, backups, logs and event streams. Designs that key all personal data by user ID, and that can replay a deletion through CDC, make this tractable. Some teams use crypto-shredding: encrypt each user's data with a per-user key and delete the key.
  • Audit and encryption: encryption at rest and in transit, access logging, and fine-grained permissions are standard in managed services, but they vary in granularity, for example row-level security in PostgreSQL versus table-level permissions elsewhere.

When either criterion is present, raise it early in the design. It often eliminates options before scale is even discussed.

Reading benchmarks and vendor claims#

Database marketing is full of numbers such as "1 million writes per second" or "10x faster than X". They are rarely false, but they are measured under conditions chosen to flatter the product. Questions to ask:

  • What workload? The Yahoo! Cloud Serving Benchmark (YCSB, Cooper and colleagues, 2010) defines standard mixes of reads, updates and scans over key-value data and is widely used to compare NoSQL systems. It does not exercise joins or multi-row transactions. TPC-C models an order-processing system with transactions and is the classic OLTP benchmark for relational and NewSQL systems. Results from one say little about the other.
  • What durability? A store that acknowledges writes before fsync, or with one replica, looks much faster than one configured for majority, durable commits. Compare with the settings you would actually run.
  • What latency percentile? Throughput at an unspecified latency is meaningless. Ask for p99 at the target throughput, because the tail is what users and dependent services feel.
  • What data size versus memory? Benchmarks whose data fits in RAM hide disk behaviour. Production datasets usually do not fit.
  • What happens under failure? Throughput during a node loss, during rebalancing and during compaction matters more than the steady state. Jepsen analyses have shown that correctness under partitions sometimes differs from documentation.

The only benchmark that decides is your workload: a prototype with your access patterns, data shapes, durability settings and failure drills, run for long enough to see compaction, vacuum and cache churn. An afternoon spent loading a realistic sample and replaying recorded traffic is worth more than a vendor's chart.

Writing the decision down#

Because database choices are expensive to reverse, mature teams record them as short architecture decision records:

decision: Primary store for orders and payments
status: accepted
context: 2k writes/s peak, 3 TB in 3 years, multi-row invariants (order + items + payment)
options: [PostgreSQL, DynamoDB, CockroachDB]
choice: PostgreSQL (managed), 1 primary + 2 replicas, partition orders by month
deciding_factor: transactions and ad hoc support queries; scale fits one primary
revisit_when: sustained writes > 15k/s, or a second region must accept writes
consequences: search and analytics via CDC; sharding plan sketched (by merchant_id)

The revisit_when line is the most valuable one. It turns "will this scale?" from a vague worry into a monitored threshold, and it tells the next engineer when the trade-off was expected to change.

Trade-offs#

ChoiceGainCost
RelationalTransactions, joins, flexible queriesWrite scale limited by one primary until sharded
NoSQLHorizontal scale, availability, fitted modelRestricted queries; consistency and joins in app code
NewSQLSQL plus automatic shardingHigher write latency, cost, newer operations
PolyglotBest tool per jobMore systems to run and keep in sync
Single Postgres plus extensionsOne system to run, transactions everywhereSpecialised workloads less optimised, one write ceiling
Managed NoSQL (DynamoDB)No servers, scales with loadAccess patterns fixed early, cost at high steady traffic, lock-in

Common Pitfalls#

  • Choosing NoSQL for scale the product will never reach.
  • Choosing a document store, then needing many-to-many joins everywhere.
  • Two sources of truth for the same data with no sync strategy.
  • Ignoring operational cost: backups, upgrades, on-call knowledge.
  • Dual-writing to two stores from application code without CDC or an outbox.
  • Running analytical GROUP BY queries on the transactional primary.
  • Trusting vendor benchmarks run with relaxed durability or data that fits in RAM.
  • Choosing a distributed SQL database for a workload that fits one node and paying latency for nothing.

Real-World Examples#

Instagram has described sharding PostgreSQL by user ID to scale its core data, rather than moving to a NoSQL store.

Google built Spanner to give its products relational schemas and globally consistent transactions; the Spanner paper (2012) describes it powering Google's advertising backend.

Google's F1 paper describes moving the AdWords backend from sharded MySQL to F1 on Spanner, motivated by the cost of resharding and the need for consistent transactions. YouTube's Vitess and Shopify's pod architecture show the opposite path working too: keeping MySQL and adding a sharding layer.

In the Interview#

Handling database-choice questions in an interview#

Typical prompts and strong responses:

  • "Why not MongoDB here?" "Orders, items and payments must change together and support staff run ad hoc queries. Postgres gives transactions and joins, and our 2,000 writes per second fit easily. If product attributes vary a lot, I'd put those in a JSONB column."
  • "This has to work across three regions. Does that change your answer?" "If each region only writes its own users' data, I'd keep Postgres per region with users pinned to a home region. If any region must write any row with strong consistency, I'd consider CockroachDB or Spanner and accept tens of milliseconds per cross-region write. If eventual consistency is acceptable, DynamoDB Global Tables or Cassandra multi-DC."
  • "You've got 1 million writes per second of sensor data." "That's append-only, keyed by device and time, read by recent windows. A time-series store or Cassandra with time-bucketed partitions handles it. Aggregates go to a columnar store. Device metadata stays relational."
  • "How would you migrate if you chose wrong?" "CDC into the new store, backfill, shadow reads comparing results, gradual read cutover, then writes. Every step reversible."

What separates levels. A mid-level answer picks a reasonable database with a reason. A senior answer quantifies, separates source of truth from derived stores, and names the chosen system's limits. A staff-level answer also discusses evolution: what breaks first at 10x, which decision is hardest to reverse, the operational cost of each additional store, and how the organisation's skills shape the choice.

Deep Dive: Migrating between databasesShow

Changing the primary store of a live system follows a standard path: dual writes or CDC to copy changes into the new store, a backfill of historical data, shadow reads that compare results from both stores, a gradual read cutover behind a feature flag, and finally switching writes and retiring the old store. Each step must be reversible. See Data Migration.

Because this is so costly, the real goal is not the perfect first database but a design that can evolve: clean data-access layers, one source of truth, and events that let you build new stores from existing data.

Deep Dive: What actually differs under the labelsShow

Strip away the marketing and every datastore is a set of answers to a few engineering questions. Comparing those answers predicts behaviour better than "SQL" or "NoSQL" does.

  1. Data model and query language: tables with SQL, documents with a query API, wide rows with CQL, graphs with Cypher, or plain keys. This decides which questions are cheap to ask.
  2. Partitioning: none (single node), hash (even load, no cross-key ranges) or range (ordered scans, possible hot ranges), and whether it is automatic or manual.
  3. Replication: single leader, multi-leader or leaderless, and synchronous, semi-synchronous or asynchronous. This decides failover behaviour, write availability and possible data loss.
  4. Consistency and transactions: per-key linearizable, snapshot isolation, serializable, or eventual, and whether transactions span keys, partitions or regions.
  5. Storage engine: B-tree (fast reads, in-place updates, write amplification on random writes) or LSM tree (fast writes, compaction, read amplification). See Storage Engines.
  6. Secondary indexing: local indexes, which need scatter-gather reads, or global ones, which need asynchronous or distributed updates.

For example, "PostgreSQL with Citus" and "MongoDB sharded" end up surprisingly similar on questions 2, 3 and 6, and very different on 1 and 4. "Cassandra" and "DynamoDB" share hash partitioning but differ on replication: leaderless versus leader per partition. "CockroachDB" is range-partitioned, consensus-replicated and serializable, in effect a Bigtable-style layout with SQL and Spanner-style transactions. When you meet a new database, place it on these six axes, and its strengths and failure modes usually follow.

Key Takeaways#

  • Decide with six criteria: data shape, relationships, consistency, scale, query flexibility and team skill.
  • Relational fits related data with transactions; NoSQL fits huge simple-key or write-heavy workloads and specialised queries.
  • "NoSQL scales better" is a myth; sharded SQL and NewSQL scale far.
  • NewSQL gives SQL and transactions with automatic sharding, at higher write latency.
  • Use polyglot persistence with one source of truth; in interviews, start with Postgres and justify any change with numbers.
  • Decide per data item: strong consistency for bookings, inventory and money, eventual consistency for feeds and counters.
  • Separate read scale, write scale and data volume. Relational handles read scale easily, and write scale is where sharding or NoSQL enters.
  • OLTP versus OLAP is often the real split. Run analytics on a columnar store fed by CDC.
  • Keep one source of truth, make derived stores rebuildable, and never dual-write without CDC or an outbox.
  • Record the decision with an explicit "revisit when" threshold.