SQL vs NoSQL: Choose a Database by Access Pattern, Not by Buzzword
System Design series · Part 3 Storage basics (1 of 8)
- SQL vs NoSQL: Choose a Database by Access Pattern, Not by Buzzword
- Indexes and B+Trees: From Disk Pages to Composite Indexes, Index-Defeating Queries, and Keyset Pagination
- B-Tree vs LSM-Tree: In-Place Updates vs Append-Only, and the Write, Read, and Space Amplification Trade-offs
- Transactions and Isolation Levels: MVCC, Lost Updates, Write Skew, and Spring Transaction Boundaries
- File and Object Storage: Block vs File vs Object, Direct Multipart Uploads, Metadata Consistency, and Upload Security
- Bloom Filters and HyperLogLog: Trading a Little Error for a Lot of Memory, and What to Do When Someone Games the Estimate
- Full-Text Search and Inverted Indexes: Chinese Tokenization, BM25 Ranking, Index Sync, and the Authorization Boundary of Search
- Geohash and Geospatial Indexes: Cell Boundaries in Nearby Search, Redis GEO, and How Distance Leaks Location
System Design series Part 3-1 | Previous: CDNs and HTTP Caching | Next: Indexes and B+Trees | Series map
Read first: Part 1-3 Napkin Math for Capacity Estimates, Part 2-1 Vertical Scaling, Horizontal Scaling, and Stateless Services.
Scenario and problem
Your e-commerce platform is launching three new features at once, and the team is arguing over which database to use:
- Orders and payments: one order has to decrement stock, create a payment record, and apply a coupon at the same time; if any step fails, everything has to roll back
- Product view history: about 100 million rows a day, insert-only; the most common query is “the 50 products a member viewed most recently”, and rows are kept for 90 days
- Product attributes: phones have a screen size and storage capacity, clothes have a size and material; every category has different fields, and the operations team keeps adding more
- Orders and paymentsOne order has to decrement stock, create a payment record, and apply a coupon at the same time; if any step fails, everything has to roll back. This is exactly what relational database transactions do best.
- View historyAbout 100 million rows a day: 1,157 a second on average and about 5,800 at peak, which one MySQL server can handle with batched writes. The real trouble is deleting 100 million expired rows every day: DELETE produces a lot of undo log, locks, and fragmentation.
- Product attributesPhones have a screen size and storage capacity, clothes have a size and material, and the operations team keeps adding fields. A traditional EAV table stores one row per attribute, so finding "phones of 6 inches or more with 256 GB" means joining the table to itself several times.
- The team starts arguingSome say NoSQL is faster and everything should move to MongoDB; others say MySQL can do it all. The three features get stuck in different places. The question is not SQL or NoSQL; it is the shape and lifecycle of the data.
Someone says “NoSQL is faster, move everything to MongoDB”; someone else says “MySQL can do it all”. Each side is only half right. The question to ask when choosing a database is not “SQL or NoSQL” but: what the data looks like, how it is read and written, how much consistency it needs, and how much of it there is.
The simplest approach and its limits
The simplest approach is to put all three features into the existing MySQL. First, estimate where it would break:
- Orders: this is exactly what relational databases do best: multiple rows in one transaction, all or nothing
- View history: 100 million rows ÷ 86,400 seconds ≈ 1,157 rows a second on average; take 5x for the peak, about 5,800. With the row header and transaction information, each InnoDB row is about 50–70 bytes, so about 5–7 GB a day and about 0.5 TB for 90 days. One MySQL server can handle this volume with batched writes (an order-of-magnitude estimate; load test it for real). The real trouble is deletion: 100 million expired rows have to be deleted every day, and
DELETEproduces a lot of undo log, locks, and fragmentation - Product attributes: the traditional approach is an EAV (entity–attribute–value) table with one row per attribute. Finding “phones with a screen of 6 inches or more and 256 GB of storage” means joining the table to itself several times, which is slow and hard to write
So the limit is not “MySQL is slow”; it is the shape and lifecycle of the data. As you will see later, all three problems have solutions in MySQL, and they are much cheaper than bringing in a new database. But first you need to understand what NoSQL actually solves.
Core mechanism
Five data models
| Type | What the data looks like | Good at | Bad at | Examples |
|---|---|---|---|---|
| Relational | Normalized tables linked by foreign keys | Arbitrary queries, joins, multi-row transactions, constraints | Automatic horizontal scaling, data whose structure varies a lot | MySQL, PostgreSQL |
| Key-Value | A key maps to one value | Access by key, with very low latency | Queries by value, range queries (depends on the product) | Redis, DynamoDB (when used as KV) |
| Document | Nested JSON documents | Reading a whole aggregate at once (an order and its line items) | Relationships and transactions across documents | MongoDB |
| Wide-column | The partition key decides where data lives, the clustering key decides its order | Very high write volume, range queries within a partition | Any query that does not specify the partition key | Cassandra, HBase |
| Graph | Nodes and edges | Traversing multi-level relationships (friends of friends) | Heavy aggregate calculations | Neo4j |
A full-text search engine (Elasticsearch and the like) is usually not the primary database but a second copy of the data synced from the primary; see the full-text search post.
Where “NoSQL is faster” gets its speed
NoSQL has no magic. Where it is faster, it is because of the four things below, and each one has a cost:
- It gives up some features: no joins, limited multi-row transactions, limited secondary indexes. Work you do not do takes no time
- The data model fits the access pattern: one document holds a whole order and its line items, fetched in one read with no join across five tables. The cost is that another access pattern (say, “find every order that bought a given product”) becomes hard
- A different write path: databases like Cassandra use an LSM-Tree, where writes are sequential appends, which suits heavy writes. The cost is that a read may have to check several layers of files (see the B-Tree vs LSM-Tree post)
- Built-in sharding: data is spread across machines automatically by partition key. The cost is that queries and transactions across partitions are expensive, or not possible at all
Conversely, a relational database looking up one row by primary key also usually takes under 1 ms. If your query is “get one row by ID” to begin with, switching databases will not make it faster.
Queries first, or data first
This is the most fundamental difference between the two camps:
flowchart LR
subgraph rel["Relational: model the data first"]
A1[Find entities and relationships] --> A2[Normalize into tables] --> A3[Add whatever index<br/>each query needs]
end
subgraph nosql["Wide-column / KV: list the queries first"]
B1[List every query] --> B2[Design one table per query<br/>and choose its partition key] --> B3[Write to several tables on every write]
end
Take view history as an example, with two queries to support:
| Query | Relational (one table) | Wide-column (one table per query) |
|---|---|---|
| Products a member viewed recently | Primary key (member_id, viewed_at) |
Table A: partition key member_id, sorted by viewed_at |
| How many people viewed a product today | Secondary index (product_id, viewed_at) |
Table B: partition key (product_id, date) |
| A third query added next month | Add an index | Add table C and backfill all historical data |
In a wide-column database, every new query means another copy of the data, and every write has to write several copies. If requirements are still changing, that cost is high. That is why when requirements are uncertain, the query flexibility of a relational database is valuable in itself.
The schema does not disappear, it moves
“NoSQL needs no schema” is a common misconception. Data always has a structure; the only difference is who checks it:
- Schema-on-write (relational): the database checks on write and rejects anything that does not fit. Changing the structure takes a migration
- Schema-on-read (document databases): anything is accepted on write, and the code interprets it on read. Changing the structure needs no downtime, but the code must understand both the old and the new format until every old document has been converted
The latter moves the migration burden from the database to the application, and that burden is usually invisible: five years later, the code has a block of if (doc.version == 1) ... else if (doc.version == 2) ... that nobody dares to delete.
The scope of transactions and consistency
| Atomicity of a single record | Multi-record transactions | Reading the latest data | |
|---|---|---|---|
| MySQL, PostgreSQL | Yes | Yes, any number of rows | Yes on the primary by default; reads from a replica lag behind |
| MongoDB | Single document | Multi-document transactions within a replica set since 4.0, on sharded clusters since 4.2 | Depends on the read concern setting |
| DynamoDB | Single item | TransactWriteItems, up to 100 operations at a time |
Eventually consistent by default; strongly consistent reads on request (at twice the cost) |
| Cassandra | Within a single partition | No general transactions; lightweight transactions (Paxos) only do compare-and-set within a single partition | Depends on the consistency level set on each request |
Note that NoSQL transaction support has improved a lot in recent years, so “NoSQL has no transactions” is no longer true. But a transaction across shards is always more expensive than one on a single machine. That is a physical limit, not a product problem. Distributed SQL (Spanner, CockroachDB, TiDB) offers cross-shard transactions, at the cost of an extra round of cross-node coordination latency on every write. For the consistency trade-offs, see the CAP and PACELC post.
Decision flow
flowchart TD
S[New data requirement] --> Q1{"Need transactions across many rows,<br/>or query patterns still unclear?"}
Q1 -- Yes --> R[Relational database]
Q1 -- No --> Q2{"Can one relational<br/>database server handle the load?"}
Q2 -- Yes --> R
Q2 -- No --> Q3{What is the access pattern?}
Q3 -- Key access with very low latency --> KV[Key-Value]
Q3 -- Heavy writes and range reads per partition --> WC[Wide-column]
Q3 -- Read and write a whole aggregate --> DOC[Document]
Q3 -- Multi-hop relationship traversal --> G[Graph]
R --> N["Try first: JSON columns, partitioned tables,<br/>read/write splitting, caching"]
The step most often skipped is the one in the middle: whether one relational database server can handle the load has to be worked out with Napkin Math, not judged by feel.
Comparing options
Back to the three features from the scenario:
| Feature | Choice | Reason | When to re-evaluate |
|---|---|---|---|
| Orders and payments | MySQL | Needs multi-table transactions and constraints, and is queried in many ways (customer service, reports, reconciliation) | When a single primary can no longer handle the writes, first consider sharding by member (see the Sharding post) |
| View history | MySQL partitioned table | A few thousand rows a second is within one machine’s capacity; once partitioned by date, expired data is deleted instantly with DROP PARTITION |
When volume grows 10x (about 60,000 rows a second at peak), or writes across data centers are needed, switch to a wide-column database |
| Product attributes | MySQL JSON column | The structure varies a lot, but the query patterns are fixed; frequently queried attributes get a functional index | When you need full-text search or fuzzy filtering on many conditions, sync a copy to a search engine |
Running several kinds of database side by side (polyglot persistence) is not wrong, but every extra database brings one more set of: backup and restore, monitoring and alerts, version upgrades, on-call expertise, and syncing and reconciliation with the other databases. For a small team, these operating costs often matter more than any difference in performance.
In Java
1. Product attributes: a JSON column with a functional index
CREATE TABLE product (
id BIGINT NOT NULL PRIMARY KEY,
category VARCHAR(16) NOT NULL,
name VARCHAR(200) NOT NULL,
attributes JSON NOT NULL,
-- functional index (MySQL 8.0.13+): can be combined with regular columns in a composite index
INDEX idx_phone_screen (category, (CAST(attributes->>'$.screenInch' AS DECIMAL(3,1))))
);SELECT id, name
FROM product
WHERE category = 'PHONE'
AND CAST(attributes->>'$.screenInch' AS DECIMAL(3,1)) >= 6.5;Inside MySQL, a functional index is a hidden generated column with an index built on it. The expression in the query must be exactly the same as the one in the index: leave out a CAST or write it another way and the index goes unused, so check with EXPLAIN. For JSON arrays (tags, for example) you can use a multi-valued index (MySQL 8.0.17+, written as CAST(... AS CHAR(32) ARRAY)).
On the JPA side, use Hibernate 6’s JSON mapping:
@Entity
public class Product {
@Id
private Long id;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private ProductCategory category;
@Column(nullable = false)
private String name;
@JdbcTypeCode(SqlTypes.JSON)
@Column(nullable = false)
private Map<String, String> attributes = new HashMap<>(); // values are always stored as strings; the type is CAST in the index
protected Product() {
}
public Product(Long id, ProductCategory category, String name) {
this.id = id;
this.category = category;
this.name = name;
}
public void replaceAttributes(Map<String, String> requested) {
Set<String> unknown = new HashSet<>(requested.keySet());
unknown.removeAll(category.allowedAttributes());
if (!unknown.isEmpty()) {
throw new IllegalArgumentException("Attributes not allowed for this category: " + unknown); // allowlist: blocks writes to arbitrary fields
}
this.attributes = new HashMap<>(requested);
}
}public enum ProductCategory {
PHONE(Set.of("screenInch", "storageGb", "color")),
APPAREL(Set.of("size", "color", "material"));
private final Set<String> allowedAttributes;
ProductCategory(Set<String> allowedAttributes) {
this.allowedAttributes = allowedAttributes;
}
public Set<String> allowedAttributes() {
return allowedAttributes;
}
}@JdbcTypeCode(SqlTypes.JSON) goes on the field. The attribute values are deliberately a Map<String, String>, for the same reason as the problem in the Session post: after a round trip through JSON, a Map<String, Object> gets the types of numbers wrong. The attributes allowed for each category live in the enum (for how to map enums, see the JPA enum post). This is what moving the “schema” from the database back into the application looks like in practice: the structure still exists, only now the code checks it.
2. View history: partitioning by date
CREATE TABLE product_view_event (
member_id BIGINT NOT NULL,
viewed_at DATETIME(3) NOT NULL,
product_id BIGINT NOT NULL,
PRIMARY KEY (member_id, viewed_at, product_id) -- the partitioning column must be part of every unique key
)
PARTITION BY RANGE COLUMNS (viewed_at) (
PARTITION p20261122 VALUES LESS THAN ('2026-11-23'),
PARTITION p20261123 VALUES LESS THAN ('2026-11-24')
);-- deleting a whole day of data only drops one partition file, and finishes almost instantly
ALTER TABLE product_view_event DROP PARTITION p20260824;With a primary key that starts with (member_id, viewed_at), “products a member viewed recently” is a single index range scan. But note: when the query does not include viewed_at, MySQL cannot tell which partition holds the data and has to check all 90 partitions one by one. So add a time range to the query, letting MySQL look only at the latest few partitions (partition pruning):
SELECT product_id, viewed_at
FROM product_view_event
WHERE member_id = ?
AND viewed_at >= NOW() - INTERVAL 7 DAY
ORDER BY viewed_at DESC
LIMIT 50;Partitions have to be created ahead of time every day and dropped once they expire, which is a job for the scheduler (for how to use ShedLock, see the stateless services post):
@Component
public class ViewEventPartitionJob {
private static final ZoneId TAIPEI = ZoneId.of("Asia/Taipei");
private static final DateTimeFormatter DAY = DateTimeFormatter.BASIC_ISO_DATE; // 20261122
private static final int DAYS_AHEAD = 7;
private static final int RETENTION_DAYS = 90;
private final JdbcTemplate jdbc;
public ViewEventPartitionJob(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Scheduled(cron = "0 30 2 * * *", zone = "Asia/Taipei")
@SchedulerLock(name = "view-event-partitions", lockAtMostFor = "10m")
public void maintain() {
LocalDate today = LocalDate.now(TAIPEI);
Set<String> existing = new HashSet<>(jdbc.queryForList("""
SELECT partition_name FROM information_schema.partitions
WHERE table_schema = DATABASE() AND table_name = 'product_view_event'
""", String.class));
for (int i = 0; i <= DAYS_AHEAD; i++) { // create the next 7 days ahead of time
LocalDate day = today.plusDays(i);
String name = "p" + day.format(DAY);
if (!existing.contains(name)) {
jdbc.execute("ALTER TABLE product_view_event ADD PARTITION (PARTITION %s VALUES LESS THAN ('%s'))"
.formatted(name, day.plusDays(1)));
}
}
LocalDate cutoff = today.minusDays(RETENTION_DAYS);
for (String name : existing) { // drop whole partitions past the retention period
if (LocalDate.parse(name.substring(1), DAY).isBefore(cutoff)) {
jdbc.execute("ALTER TABLE product_view_event DROP PARTITION " + name);
}
}
}
}Why create 7 days ahead? Because a row with no matching partition cannot be written: if the job keeps failing until the partitions run out, every write gets a Table has no partition for value ... error. Keep a buffer of a few days, and set an alert on “the date of the newest partition”. The partition names and dates in the DDL are all generated by the code, with no external input, so building the SQL from strings is fine here; as soon as any user input is involved, never do this.
On the write side, use JDBC batches. MySQL Connector/J needs rewriteBatchedStatements=true for the driver to rewrite a batch of INSERTs into one multi-row INSERT; otherwise the batch is still sent one row at a time.
Pitfalls and gotchas
- “NoSQL is faster”: it is fast because it gives up features and fits a specific access pattern. Once the query pattern changes, the advantage disappears
- Treating MongoDB as schemaless: the schema has moved into the code, and nobody keeps it documented
- Running a query without the partition key on a wide-column database: Cassandra’s
ALLOW FILTERINGscans the whole cluster. With little data in development you will not notice; in production it times out - A poorly chosen partition key: with “date” as the partition key, all of the day’s writes hit the same partition and create a hot spot. DynamoDB caps the throughput of a single partition, so a hot key gets throttled
- Documents that grow without limit: keep stuffing comments and records into the same document and it eventually hits the size limit (16 MB for a single MongoDB document), and every update rewrites the whole document
- EAV tables: they look flexible, but queries have to join the table to itself several times, and constraints cannot guarantee the data is correct. Since MySQL 5.7, the usual replacement is a JSON column
- Queries on a partitioned table without the partitioning column: every partition gets queried, which is slower than not partitioning at all
- No alert when partitions run out: suddenly every write fails
- Adding a new database for one feature: performance barely changes, but operating costs double
Security
- NoSQL has injection too: if you use a JSON object sent by the client directly as a query condition, an attacker can send an operator such as
{"password": {"$ne": null}}, and the condition becomes “the password is not null”, which is the same as needing no password at all. Always bind query parameters as explicit types (strings, numbers); never pass an object from the request into a query unchanged - Flexible fields mean a flexible attack surface: if a JSON column or a document database accepts whatever fields the client sends, an attacker can write attributes such as
verified: truethat users should not get to decide. This is API3 (Broken Object Property Level Authorization) in the OWASP API Security Top 10 2023, and the allowlist inreplaceAttributesabove exists for exactly this - Deployments that are open by default: starting in 2017, tens of thousands of MongoDB instances with no authentication, exposed directly on the internet, were wiped and held for ransom. Elasticsearch and Redis have had the same kind of incident. Every database belongs on an internal network with authentication turned on
- One more database, one more copy of personal data: the same personal data may live in the primary database, the search engine, the cache, and the analytics database at the same time. When a user asks for deletion, every copy has to be deleted; in a security audit, every copy needs encryption and access control
When to use it, and when not to
- Default to a relational database: requirements are still changing, you need transactions, queries are varied, or the team knows it best. MySQL and PostgreSQL, with JSON columns, partitioned tables, read/write splitting, and caching, can handle far more scale than most people expect
- Signals to switch to NoSQL: access patterns are fixed and simple (almost all by key), write volume clearly exceeds what one machine can do, you need writes in several regions at once, or the data is naturally an independent tree or a graph
- When to re-evaluate: single-machine writes to the partitioned table approach the load test limit; queries on the JSON column keep getting more complex and the functional indexes keep piling up; the same data starts needing several completely different ways to query it (what you may need then is CQRS plus a dedicated read database; see the CQRS post)
References
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017: Chapter 2, Data Models and Query Languages
- Giuseppe DeCandia et al., “Dynamo: Amazon’s Highly Available Key-value Store”, SOSP 2007
- Fay Chang et al., “Bigtable: A Distributed Storage System for Structured Data”, OSDI 2006
- Avinash Lakshman, Prashant Malik, “Cassandra: A Decentralized Structured Storage System”, ACM SIGOPS Operating Systems Review, 2010
- MySQL Reference Manual — The JSON Data Type, Functional Key Parts, Multi-Valued Indexes: https://dev.mysql.com/doc/refman/8.0/en/json.html
- MySQL Reference Manual — Partitioning Keys, Primary Keys, and Unique Keys: https://dev.mysql.com/doc/refman/8.0/en/partitioning-limitations-partitioning-keys-unique-keys.html
- Hibernate ORM User Guide — JSON mapping: https://docs.jboss.org/hibernate/orm/6.6/userguide/html_single/Hibernate_User_Guide.html
- Amazon DynamoDB Developer Guide — Transactions: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transactions.html
- MongoDB Manual — Transactions: https://www.mongodb.com/docs/manual/core/transactions/
- OWASP API Security Top 10 2023 — API3 Broken Object Property Level Authorization: https://owasp.org/API-Security/editions/2023/en/0xa3-broken-object-property-level-authorization/
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments