- Chapter
- Chapter 1 — NoSQL Fundamentals
- Prerequisites
- Volumes I–III
- You will be able to
- Explain the technical and organisational forces that led to NoSQL databases, distinguish scale-up from scale-out and why distribution changes database design, evaluate when flexible schemas help or hurt, match specialised workloads to specialised stores, and argue when a relational database remains the better choice
- Covers
- Scale; Flexible schemas; Specialised workloads
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — What Distribution Changes
- 4A. Deep Dive — Is NoSQL Still Necessary? Relational Answers Today
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
NoSQL ("not only SQL") is an umbrella term for database systems that do not use the relational table model as their primary data model. They typically favour horizontal scalability, flexible or schema-less data models, and optimisation for specific access patterns over the generality of SQL and multi-row ACID transactions.

| TOC driver | Problem it addresses |
|---|---|
| Scale | Data volume or write throughput beyond what one server can handle; global distribution |
| Flexible schemas | Rapidly evolving or heterogeneous records that fit rigid tables poorly |
| Specialised workloads | Access patterns (key lookups, time series, graph traversals, search) that general-purpose engines serve inefficiently |
2Why It Exists
In the mid-2000s, internet companies hit limits of single-server relational databases: billions of rows, tens of thousands of writes per second, users on several continents and schemas that changed weekly. Google's Bigtable paper (2006) described a distributed, sorted, wide-column store; Amazon's Dynamo paper (2007) described an always-writable, eventually consistent key-value store for shopping carts. Open-source systems followed — Cassandra (combining both ideas), MongoDB, Redis, CouchDB, Neo4j, HBase — and the 2009 "NoSQL" meetup gave the movement a name.
| Pressure (2005–2010) | Relational limitation at the time |
|---|---|
| Write volumes beyond one server | Sharding done manually in the application |
| Always-on across data centres | Synchronous replication across regions too slow |
| Agile schema change | Long ALTER TABLE on huge tables, locking |
| Commodity hardware clusters | Designs assumed large, reliable servers |
Since then relational databases have evolved (JSONB, native partitioning, logical replication, distributed SQL), and many "NoSQL-only" arguments have weakened. Today the question is not SQL vs NoSQL but which store fits each workload.
3Core Concepts
3.1 Scale


| Scale dimension | Relational single node | NoSQL cluster |
|---|---|---|
| Data volume | Limited by one server's storage and memory | Sum of nodes |
| Write throughput | One primary's CPU/IO/WAL | Writes spread across partitions |
| Read throughput | Replicas (asynchronous) | Replicas + partitions |
| Geography | One primary region | Multi-region replication (often multi-writer) |
| Failure | Failover of one primary | Replicas per partition; no single point of failure |
| Mechanism | Description |
|---|---|
| Partitioning (sharding) | Split data by key (hash or range) across nodes |
| Replication | Keep copies of each partition on several nodes |
| Rebalancing | Move partitions when nodes join/leave (consistent hashing, virtual nodes, chunks) |
| Request routing | Client, router or coordinator finds the owning node |
3.2 Flexible schemas

| Flexible-schema benefit | Example |
|---|---|
| Heterogeneous items | Product catalogue: phones have screenSize, shirts have sleeve |
| Evolving structure | New field added by one service release, old documents unchanged |
| Nested data | Order with embedded lines and shipping address in one record |
| Sparse attributes | Thousands of optional attributes, few used per item |
| Flexible-schema risk | Mitigation |
|---|---|
| Inconsistent field names/types across records | JSON Schema validators, typed Java classes |
| Silent data drift between versions | schemaVersion field, migration on read/write |
| Queries miss renamed fields | Contract tests, versioned migrations |
| No central integrity (FKs) | Application-level invariants, reconciliation jobs |
3.3 Specialised workloads

| Workload | Access pattern | Why a general RDBMS struggles | Specialised store |
|---|---|---|---|
| Session/cache | Get/set by key, TTL, 100 k+ ops/s | Disk-oriented, MVCC overhead per update | Redis |
| Time series / IoT | Append-heavy, range reads by device + time | Index maintenance and vacuum at extreme write rates | Cassandra, time-series DBs |
| Relationship traversal | Friends-of-friends, fraud rings (multi-hop) | Recursive joins grow expensive with depth | Neo4j |
| Catalogue/content | Read whole varied objects | Many tables or EAV | MongoDB |
| Full-text search | Relevance ranking, fuzzy matching | Limited ranking features | Elasticsearch/OpenSearch |
4How It Works Internally — What Distribution Changes
| Relational single-node assumption | Distributed NoSQL reality |
|---|---|
| One copy of the truth | Several replicas — which one is current? |
| Transactions across any rows | Transactions usually limited to one partition/document |
| Joins anywhere | Joins across nodes expensive → denormalise |
| Planner chooses access paths | Data model must match queries (partition keys) |
| Failure = downtime or failover | Partial failure is normal; clients retry, replicas repair |
Distributed databases must decide how to behave when replicas cannot communicate (CAP) and how much latency to pay for consistency in normal operation (PACELC) — Topic 1.3.
4ADeep Dive — Is NoSQL Still Necessary? Relational Answers Today

-- PostgreSQL: flexible attributes with JSONB + GIN index
CREATE TABLE product (
id bigint PRIMARY KEY,
sku text UNIQUE NOT NULL,
category text NOT NULL,
attributes jsonb NOT NULL DEFAULT '{}'
);
CREATE INDEX idx_product_attrs ON product USING gin (attributes jsonb_path_ops);
SELECT sku FROM product
WHERE category = 'phone' AND attributes @> '{"screenSize": 6.1, "5g": true}';| Requirement | Often enough with PostgreSQL | Where NoSQL clearly wins |
|---|---|---|
| Semi-structured attributes | JSONB + relational core | Entirely document-shaped domain, huge scale |
| Moderate write scale (thousands/s) | Tuned single primary, partitioning | Hundreds of thousands/s, multi-region writes |
| Caching | Buffer cache + app cache | Shared, sub-ms, TTL-based data structures (Redis) |
| Graph questions of depth 2–3 | Recursive CTEs | Deep, frequent traversals over large graphs |
5APIs / Features / Syntax
| Store | Java access (Spring Boot 4) | Query language |
|---|---|---|
| MongoDB | Spring Data MongoDB / MongoDB Java Driver 5 | MQL, aggregation pipeline |
| Redis | Spring Data Redis (Lettuce) | Commands (GET, HSET, ZADD …) |
| Cassandra | Spring Data Cassandra / DataStax Java Driver 4 | CQL |
| Neo4j | Spring Data Neo4j / Neo4j Java Driver | Cypher |
| DynamoDB | AWS SDK v2 Enhanced Client | API (GetItem, Query), PartiQL |
6Practical Examples
6.1 MongoDB chosen "because JSON"
A team building an order system picked MongoDB because the API used JSON. The domain was highly relational (orders, customers, invoices, payments, refunds with cross-entity reports). They spent months emulating joins and transactions and building reconciliation jobs. The next major version moved the core to PostgreSQL with JSONB for flexible order metadata.
6.2 Relational database as a session store
A retailer stored HTTP sessions in PostgreSQL: 30 k updates/s at peak, each creating a dead tuple; autovacuum could not keep up, the table bloated to 400 GB and latency spiked. Moving sessions to Redis with TTL removed the load and simplified expiry.
6.3 Worked example — sizing the scale question
Scenario. An architecture review for a growing marketplace included a proposal to move "to NoSQL for scale". The chief architect asked for numbers first: what does each workload actually need, per second and in total?
| Workload metric | Value | Single PostgreSQL primary? |
|---|---|---|
| Orders per day | 400 k (≈ 5 writes/s average, 60/s peak) | Easily |
| Order lines stored | 2 B over 5 years | Yes, with partitioning |
| IoT readings | 200 k/s sustained | No — distributed write-optimised store |
| Session reads | 80 k/s, 5 ms SLO | Possible but wasteful — in-memory store |
What it shows. Putting real figures next to each workload changes the conversation. Orders average about 5 writes per second with peaks of 60, which a single PostgreSQL primary handles easily, and 2 billion order lines over five years fit with partitioning. Only two workloads exceed a single relational node's comfort zone: IoT readings at 200,000 writes per second sustained, which need a distributed write-optimised store, and session reads at 80,000 per second with a 5 ms target, which an in-memory store serves more cheaply.
Takeaway. Quantify each workload before choosing a technology. "Scale" is rarely a property of a whole system; it usually applies to one or two workloads, and those are the only ones that justify a specialised store.
6.4 Worked example — partitioning arithmetic
Scenario. The IoT team chose a distributed database for sensor data and needed to know how many nodes to buy now and next year, and what adding nodes would involve operationally.
| Parameter | Value |
|---|---|
| Data | 12 TB, growing 4 TB/year |
| Target per node | ≤ 1.5 TB (repair and rebuild times) |
| Replication factor | 3 |
| Nodes needed now | 12 × 3 / 1.5 = 24 |
| Nodes next year | 16 × 3 / 1.5 = 32 |
Adding 8 nodes moves roughly 25% of partitions — rebalancing must be planned (throughput, streaming time).
What it shows. With 12 TB of data, a replication factor of 3 and a target of at most 1.5 TB per node, the cluster needs 12 × 3 / 1.5 = 24 nodes today. Data grows by 4 TB a year, so next year needs 16 × 3 / 1.5 = 32 nodes. The per-node limit is not about disk size but about how long repairs and node rebuilds take; larger nodes take much longer to recover. Adding 8 nodes moves roughly a quarter of all partitions, which consumes network and disk throughput for hours or days.
Takeaway. Scale-out capacity planning is arithmetic on data size, replication and recovery time. Plan node additions ahead of need, schedule rebalancing in quiet periods, and test how long a node rebuild really takes before relying on the numbers.
6.5 Worked example — flexible schema in a product catalogue
Scenario. A retailer sells phones, shirts, furniture and groceries. Each category has different attributes: screen size and storage for phones, sizes and material for shirts. The relational catalogue had grown to hundreds of tables, and adding a category took weeks.
{ "_id": "SKU-1001", "category": "phone", "name": "Nimbus X",
"attributes": { "screenSize": 6.1, "storageGb": [128, 256], "5g": true } }
{ "_id": "SKU-2040", "category": "shirt", "name": "Linen Classic",
"attributes": { "sizes": ["S","M","L"], "sleeve": "long", "material": "linen" } }| Relational alternatives | Drawback |
|---|---|
| Table per category | Hundreds of tables, cross-category queries hard |
| EAV (entity-attribute-value) | Complex, slow queries, weak typing |
| Wide table with nullable columns | Hundreds of mostly-null columns |
| JSONB column | Good middle ground if the rest is relational |
What it shows. A document database stores each product as one document with a common core, such as ID, category and name, and an attributes object whose shape depends on the category. The two sample documents show how a phone and a shirt can coexist in one collection, each read and written as a whole. The table of relational alternatives shows why the team struggled: a table per category, entity-attribute-value tables and wide tables with many nullable columns each have serious drawbacks. A JSONB column in PostgreSQL is a good middle ground when the rest of the data is relational.
Takeaway. Choose a document model when data is genuinely varied and read as whole aggregates. Even then, validate documents with a schema per category, because flexible storage still needs consistent data.
6.6 Worked example — schema evolution without migration
Scenario. The customer service added a preferences field to customer documents in a collection of 30 million documents. Running a migration over every document at deployment time would have taken hours and blocked the release.
@Document("customers")
public record CustomerDoc(@Id String id, String email, String name,
Integer schemaVersion, Map<String, Object> preferences) { }
CustomerDoc upgrade(CustomerDoc c) {
if (c.schemaVersion() == null || c.schemaVersion() < 2) { // v1 had no preferences
return new CustomerDoc(c.id(), c.email(), c.name(), 2,
Map.of("newsletter", false));
}
return c;
}| Strategy | When |
|---|---|
| Lazy (upgrade on read/write) | Large collections; gradual |
| Background migration job | Must query new fields everywhere soon |
| Dual reading (old and new fields) | Transition period |
What it shows. Each document carries a schemaVersion field. When the service reads a document older than version 2, the upgrade method fills in default preferences and the next write saves it in the new format, so the collection migrates lazily as customers are active. The table compares strategies: lazy upgrade for large collections where gradual change is acceptable, a background job when every document must be queryable by the new field soon, and dual-reading during transitions. All strategies require code that can read both old and new formats for a while.
Takeaway. Schema-less storage moves schema evolution into the application rather than removing it. Version every document, keep upgrade code tested, and decide explicitly how long old versions may exist.
6.7 Worked example — mapping workloads of one company
Scenario. An architect joining a mid-sized e-commerce company found six different database technologies in production and was asked whether that was a mess or a strategy.
| System | Workload | Store |
|---|---|---|
| Checkout, payments | Transactions, integrity | PostgreSQL |
| Product catalogue | Varied documents, read-heavy | MongoDB |
| Sessions, rate limits, carts | Key-value, TTL, high ops | Redis |
| Clickstream | Append-heavy time series | Cassandra |
| Recommendations | Relationship traversal | Neo4j |
| Search | Full-text relevance | OpenSearch |
What it shows. Mapping each system to its workload showed a deliberate pattern. Transactions and payments use PostgreSQL for integrity; the varied, read-heavy catalogue uses MongoDB; sessions, carts and rate limits use Redis for fast key-value access with expiry; clickstream data uses Cassandra for append-heavy time series; recommendations use Neo4j for relationship traversal; and search uses OpenSearch for full-text relevance. Each choice matches a workload that the alternative stores handle poorly.
Takeaway. Polyglot persistence is justified when each store clearly serves a distinct workload. Document the mapping, give every store an owning team with operational skills, and challenge any new technology that does not have a clear workload of its own.
6.8 Worked example — time-series writes
Scenario. An industrial monitoring platform receives 200,000 sensor readings per second, around the clock, and deletes data older than 90 days. The first prototype on a single PostgreSQL node fell behind within an hour of production load.
| Rate: 200 k readings/s | PostgreSQL single node | Cassandra 12 nodes (RF 3) |
|---|---|---|
| Write path | WAL + heap + index per row | Commit log + memtable, sequential SSTable flushes |
| Per-node write rate needed | 200 k/s | ~50 k/s (with RF 3) |
| Deletion of old data | DELETE/vacuum or partition drop | TTL + time-window compaction |
What it shows. In PostgreSQL every reading writes to the WAL, the table heap and each index, with random I/O, all on one node. Cassandra's log-structured merge-tree design appends writes to a commit log and an in-memory table, then flushes them sequentially to immutable files. Spread across 12 nodes with a replication factor of 3, each node handles about 50,000 writes per second. Expiry is also cheaper: a time-to-live with time-window compaction drops whole files of old data instead of deleting rows one by one.
Takeaway. Append-heavy, time-ordered data suits write-optimised storage. Before adopting a new store, also consider PostgreSQL partitioning or time-series extensions, which may be enough at lower volumes with far less operational change.
6.9 Worked example — global availability requirement
Scenario. A global retailer requires that customers can always add items to their cart, even during a network partition between regions, but payments must never be taken twice. One database configuration cannot satisfy both.
| Requirement | Design implication |
|---|---|
| Cart must accept writes even if a region is cut off | Multi-writer (AP) store; conflict resolution |
| Payment must never double-charge | Strongly consistent store; single writer per account |
| Product reads in 3 continents < 50 ms | Local replicas; eventual consistency acceptable |
What it shows. The requirements are different consistency needs within one product. The cart can use a multi-region, multi-writer store that stays available during partitions and resolves conflicting updates later, for example by merging cart items. Payments need a strongly consistent store with a single writer per account, accepting that a partitioned region may reject payments rather than risk double charging. Product reads need low latency on three continents, so local replicas with eventual consistency are fine.
Takeaway. Decide consistency per operation, not per system. Write down which operations must stay available and which must stay correct during failures, then choose stores and configurations to match.
6.10 Worked example — graph workload threshold
Scenario. A bank's fraud team wanted to find accounts linked through chains of shared devices, phone numbers and transfers, up to five steps away. Their PostgreSQL recursive queries worked, but took minutes for some accounts.
| Query | PostgreSQL recursive CTE | Neo4j |
|---|---|---|
| Friends of a user (depth 1) | 1 ms | 1 ms |
| Friends-of-friends (depth 2) | 15 ms | 3 ms |
| Paths up to depth 5 between two accounts (fraud) | seconds–minutes | tens of ms |
What it shows. The measurements show where a graph database starts to pay off. For depth 1, direct relationships, both stores answer in about a millisecond, and for depth 2 PostgreSQL is still fine. Beyond that, relational joins multiply intermediate results, and queries of depth 5 take seconds to minutes, while a graph database follows stored relationships directly and answers in tens of milliseconds. The figures are illustrative; they depend heavily on data shape and indexing.
Takeaway. Traversal depth and query frequency decide whether a graph store is worth it. If deep, frequent relationship queries are central to the product, a graph database helps; occasional shallow ones are cheaper to keep in the relational database.
6.11 Worked example — cost of operating a new store
Scenario. A team proposed self-managing a Cassandra cluster for a new feature because the licence was free. The architecture review asked for the full cost, not just the licence.
| Cost item | Estimate for a self-managed Cassandra cluster |
|---|---|
| Engineers with expertise | 1–2 FTE equivalent for operations |
| Monitoring, backups, repairs | New tooling and runbooks |
| Training | Data modelling by query is a new skill |
| Managed alternative | Higher unit cost, lower operational burden |
What it shows. The estimate shows that people and operations dominate. Running Cassandra safely needs one to two full-time-equivalent engineers with specialist skills, new monitoring, backup and repair tooling, runbooks, and training in query-driven data modelling, which is very different from relational design. A managed service costs more per unit of capacity but removes most of the operational burden. For a single feature with moderate scale, the managed option or staying on PostgreSQL was cheaper overall.
Takeaway. Include operations, skills and on-call in every database business case. A technology that is free to license can be the most expensive option once people and incidents are counted.
6.12 Worked example — decision questions for "Do we need NoSQL?"
Scenario. Development teams repeatedly asked the architecture group whether they "need NoSQL". The group turned its reasoning into a short screening checklist that teams could apply themselves before a review.
| Question | If "yes" → consider |
|---|---|
| Will one well-tuned relational primary be exceeded within 3 years? | Scale-out store or distributed SQL |
| Is the data genuinely document-shaped and read as whole aggregates? | Document database |
| Is it key lookups with TTL at very high rates? | Key-value store |
| Are multi-hop relationship queries central? | Graph database |
| Do we need multi-region writes with availability over consistency? | Dynamo-style store |
| None of the above | Stay relational |
What it shows. Each question tests one of the real reasons for a specialised store: scale beyond a well-tuned relational primary within three years, data that is genuinely document-shaped and read as whole aggregates, very high-rate key lookups with expiry, multi-hop relationship queries at the core of the product, or multi-region writes where availability matters more than consistency. Each "yes" points to a specific kind of store; if every answer is "no", the recommendation is to stay relational.
Takeaway. A checklist makes technology decisions repeatable and explainable. Ask teams to bring their answers, with numbers, to the design review, and record the decision and its reasoning in an ADR.
7Common Problems & Mistakes
- Choosing NoSQL for fashion or to avoid schema design.
- Assuming NoSQL is always faster — it is faster for the patterns it was designed for.
- Ignoring integrity requirements that relational constraints provided.
- Underestimating operational cost of distributed stores.
- Treating "schema-less" as "no schema".
- Not re-checking modern relational capabilities (JSONB, partitioning).
8Performance & Production Considerations
| Aspect | Guideline |
|---|---|
| Evidence | Benchmark real access patterns at target scale |
| Capacity | Plan partitions, replication factor, rebalancing |
| Schema | Validators, versions, typed classes |
| Operations | Prefer managed services unless there is expertise |
| Exit strategy | Keep data export/migration paths |
9Architecture & Design Considerations
- Start from workloads and access patterns, then choose stores.
- Keep a relational system of record where integrity dominates.
- Use NoSQL stores for specific workloads they excel at.
- Record the decision with quantified drivers (volume, rate, latency, availability).
10Interview Questions & Answers
What does NoSQL mean?
NoSQL is usually read as "not only SQL". It is an umbrella term for databases that do not use the relational table model as their primary way of storing data. The main families are key-value stores such as Redis, document databases such as MongoDB, wide-column stores such as Cassandra, and graph databases such as Neo4j; search engines such as OpenSearch are often included. They differ widely in data model, consistency and query capabilities, so "NoSQL" says little about a specific product. Many now offer SQL-like query languages, and relational databases have added document and JSON features, so the line keeps blurring.
Why did NoSQL databases emerge?
NoSQL databases emerged in the late 2000s when web companies such as Google, Amazon and Facebook hit limits that relational databases of the time handled poorly. They needed to store far more data and absorb far more writes than one server could handle, so they needed to scale out across many cheap machines. They needed to change data structures frequently without long migrations. And they had specialised access patterns, such as key lookups at very high rates, append-heavy event data or relationship traversal. Systems like Bigtable and Dynamo inspired open-source databases that made different trade-offs, often relaxing joins and strict consistency to gain scale and availability.
What is the difference between scaling up and scaling out?
Scaling up, or vertical scaling, means making one server bigger: more CPU, memory and faster disks. It is simple, keeps transactions and joins local, but has a ceiling and a single point of failure, and the largest machines are expensive. Scaling out, or horizontal scaling, means adding more servers and partitioning the data across them, so capacity can keep growing and failures affect only part of the data. The cost is complexity: data must be partitioned by a key, cross-partition queries and transactions become expensive or impossible, and replicas raise consistency questions. Relational databases traditionally scale up; many NoSQL stores scale out by design.
What is the risk of a flexible schema?
A flexible schema lets each document or record have a different structure, which speeds up development, but the database no longer stops inconsistent data. Over time, fields are added with different names or types, old documents miss new fields, and different services write the same collection in slightly different ways. Bugs appear far from where the bad data was written. Validation and schema evolution move into application code, which must handle every historical shape. Mitigations include database-level schema validation where available, version fields on documents, shared schemas for each collection and tests that read real historical data.
Give examples of workloads that suit specialised stores.
Different stores are built for different access patterns. Key-value stores such as Redis suit sessions, caches, rate limits and shopping carts that need very fast lookups by key, often with automatic expiry. Wide-column stores such as Cassandra suit time-series and event data with very high write rates. Graph databases such as Neo4j suit fraud detection, recommendations and networks where queries follow many relationships. Document databases such as MongoDB suit catalogues and content with varied structure that is read as whole aggregates. Search engines such as OpenSearch suit full-text search and relevance ranking. Each performs poorly outside its sweet spot.
What can PostgreSQL offer before you move to NoSQL?
PostgreSQL covers more NoSQL-style needs than many teams expect. JSONB columns store flexible, document-shaped data with GIN indexes for fast queries inside the JSON, so a product catalogue can keep a relational core with flexible attributes. Declarative partitioning handles very large tables, such as years of orders or events, and makes dropping old data cheap. Read replicas spread read load, and extensions add capabilities such as time-series storage or vector search. Combined with good indexing and an external cache, a well-tuned PostgreSQL often meets requirements that might seem to call for NoSQL, with transactions and SQL intact.
What changes in design when data is distributed across nodes?
Once data is spread across nodes, the data model must follow the partition key: queries should find all their data in one partition, so data is often denormalised and duplicated per query pattern. Joins and multi-row transactions become local to a partition, or disappear entirely, so consistency across partitions needs application-level patterns such as idempotent writes or sagas. Replicas introduce a choice between consistency and availability, often configurable per operation through quorum levels. Partial failures become normal: some nodes may be slow or unreachable, so clients need timeouts and retries. Design starts from access patterns rather than from entities.
How do you decide whether a system needs a NoSQL store?
Start with measurable requirements for each workload: data volume and growth, read and write rates, latency targets, availability needs including multi-region, and the main access patterns. Compare them with what a well-tuned relational database can provide, including partitioning, replicas, JSONB and caching. Consider a specialised store only for workloads where its model clearly fits and the relational option clearly falls short. Then weigh operational cost, team skills, managed-service options and the cost of running yet another technology. Record the decision in an ADR, and keep the relational database as the default for everything else.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.