- Chapter
- Chapter 1 — NoSQL Fundamentals
- Prerequisites
- Topic 1.1
- You will be able to
- Describe the four NoSQL data models precisely, explain how each stores and retrieves data, identify their natural access patterns and limitations, recognise multi-model products, and choose a category from a workload description
- Covers
- Key-value; Document; Wide-column; Graph
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Storage and Distribution by Category
- 4A. Deep Dive — Multi-Model Databases and Blurred Boundaries
- 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 databases are classified by their data model — the shape in which data is stored and accessed.

| Category | Data model | Primary access | Examples |
|---|---|---|---|
| Key-value | Key → opaque value | Get/put/delete by key | Redis, DynamoDB, Riak, etcd |
| Document | Key → structured, nested document (JSON/BSON) | By id + queries on fields | MongoDB, Couchbase, Firestore |
| Wide-column | Partition key → sorted rows with many columns | Partition + clustering-key ranges | Cassandra, HBase, Bigtable, ScyllaDB |
| Graph | Nodes + relationships with properties | Traversals, pattern matching | Neo4j, Neptune, Memgraph |
2Why It Exists
The relational model is general: any query over any combination of tables. Specialised models give up some generality to gain performance, scalability or expressiveness for particular patterns. Classifying stores by model helps architects reason about capabilities independent of product marketing.
| Data model spectrum | More structure visible to the database → |
|---|---|
| Key-value | Value opaque; database knows only keys |
| Wide-column | Database knows partition/clustering keys and columns |
| Document | Database understands nested fields and indexes them |
| Graph | Database understands entities and their relationships |
3Core Concepts
3.1 Key-value

| Property | Detail |
|---|---|
| Operations | GET, SET/PUT, DELETE, often atomic increments, TTL, conditional put |
| Complexity | O(1) lookups by hash; distribution by key hash |
| Value | Opaque bytes (Redis adds rich data structures: hashes, lists, sets, sorted sets, streams) |
| Strengths | Latency (sub-ms in memory), simplicity, linear scale |
| Limits | No queries on value content; secondary access needs extra keys/indexes |
// Spring Data Redis: session-like data with TTL
redis.opsForValue().set("session:" + sid, sessionJson, Duration.ofMinutes(30));
String s = redis.opsForValue().get("session:" + sid);
Long hits = redis.opsForValue().increment("rate:ip:" + ip); // atomic counter3.2 Document

| Property | Detail |
|---|---|
| Unit | Self-contained document (nested objects, arrays), typically ≤ 16 MB (MongoDB) |
| Operations | CRUD by id, queries on any field, secondary indexes, aggregation |
| Atomicity | Single-document writes atomic; multi-document transactions optional |
| Strengths | Matches application objects; flexible structure; rich queries |
| Limits | Cross-document joins costly; duplication to manage |
Query q = Query.query(Criteria.where("status").is("PAID").and("customer.id").is(17))
.with(Sort.by(Sort.Direction.DESC, "placedAt")).limit(20);
List<OrderDoc> orders = mongo.find(q, OrderDoc.class);3.3 Wide-column

| Property | Detail |
|---|---|
| Structure | Table → partitions (partition key) → rows sorted by clustering columns |
| Storage | Log-structured merge (LSM) trees: commit log, memtable, SSTables, compaction |
| Operations | Writes anywhere (fast), reads by partition key + clustering range |
| Strengths | Massive write throughput, linear scale, multi-datacenter replication |
| Limits | Queries must follow key design; no joins; limited ad-hoc filtering |
-- CQL (Cassandra): table designed for one query
CREATE TABLE readings_by_sensor_day (
sensor_id text, day date, ts timestamp, value double,
PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC);
SELECT ts, value FROM readings_by_sensor_day
WHERE sensor_id = 'S-42' AND day = '2026-09-25' AND ts >= '2026-09-25 08:00:00';3.4 Graph

| Property | Detail |
|---|---|
| Structure | Nodes (labels, properties), relationships (type, direction, properties) |
| Storage | Index-free adjacency — each node points to its relationships |
| Operations | Pattern matching and traversals (Cypher, Gremlin, GQL) |
| Strengths | Multi-hop queries in time proportional to the traversed subgraph |
| Limits | Horizontal write scaling harder; bulk scans/aggregations weaker than columnar/analytic stores |
// Cypher: accounts sharing a device with a known fraudster (2 hops)
MATCH (f:Customer {flagged: true})-[:USES]->(d:Device)<-[:USES]-(c:Customer)
WHERE c <> f
RETURN DISTINCT c.id, d.id4How It Works Internally — Storage and Distribution by Category
| Category | Typical storage engine | Distribution |
|---|---|---|
| Key-value (Redis) | In-memory hash tables + optional persistence (RDB/AOF) | Hash slots (16,384) across masters |
| Key-value (DynamoDB) | B-tree/LSM on SSD per partition | Hash of partition key |
| Document (MongoDB) | WiredTiger B-trees, compressed | Replica sets; sharding by shard key (range/hash) |
| Wide-column (Cassandra) | LSM: commit log, memtable, SSTables | Consistent hashing token ring, vnodes |
| Graph (Neo4j) | Native record stores with adjacency pointers | Leader + followers; sharding via composite databases |
4ADeep Dive — Multi-Model Databases and Blurred Boundaries
| Product | Primary model | Additional models |
|---|---|---|
| PostgreSQL | Relational | Document (JSONB), key-value (hstore), graph (Apache AGE extension), vector (pgvector) |
| MongoDB | Document | Time series collections, search, vector search |
| Redis | Key-value | JSON documents, search, time series, vectors |
| Azure Cosmos DB | Multi-API | Document, key-value, wide-column (Cassandra API), graph (Gremlin) |
| Couchbase | Document | Key-value first access, SQL++ queries |

A multi-model product reduces the number of systems but each secondary model is usually less mature than a specialised store — evaluate the model you actually need.
5APIs / Features / Syntax
| Category | Spring Data module | Repository example |
|---|---|---|
| Key-value | Spring Data Redis | @RedisHash("carts") record Cart(...) + CrudRepository |
| Document | Spring Data MongoDB | MongoRepository<OrderDoc, String> |
| Wide-column | Spring Data Cassandra | CassandraRepository<Reading, ReadingKey> |
| Graph | Spring Data Neo4j | Neo4jRepository<Customer, Long> with @Query Cypher |
6Practical Examples
6.1 Key-value store used for queries
A team stored customer profiles in Redis as JSON strings and later needed "all customers in Pune with GOLD tier". Without secondary indexes they scanned all keys (SCAN + deserialise), blocking the instance at peak. Moving profiles to a document store (or adding a search index) matched the new access pattern.
6.2 Cassandra table designed like a relational table
A users table with PRIMARY KEY (user_id) was queried WHERE email = ? using ALLOW FILTERING — a full cluster scan. Creating a second table users_by_email (query-first design) fixed it.
6.3 Worked example — one domain in four models
| Model | Representation of "customer 17 placed order 5001 with 2 lines" |
|---|---|
| Key-value | order:5001 → serialised blob; customer:17:orders → list of ids |
| Document | orders document with embedded lines and customer snapshot |
| Wide-column | orders_by_customer partition 17, rows clustered by placed_at (one row per order) |
| Graph | (:Customer {id:17})-[:PLACED]->(:Order {id:5001})-[:CONTAINS {qty:2}]->(:Product) |
6.4 Worked example — matching access patterns to categories
| Access pattern | Category |
|---|---|
| "Get cart for session X" 50 k/s, expires in 2 h | Key-value |
| "Show product page with all attributes and top reviews" | Document |
| "Last 24 h of readings for device D" at 1 M writes/s | Wide-column |
| "Which accounts are within 3 hops of this flagged account?" | Graph |
| "Revenue by region and month with ad-hoc filters" | Relational / analytical |
6.5 Worked example — Redis data structures beyond plain values
| Structure | Command examples | Use |
|---|---|---|
| Hash | HSET cart:9 sku-1 2 | Object with fields |
| Sorted set | ZADD leaderboard 1820 user:17 | Rankings, time-ordered indexes |
| List/Stream | LPUSH, XADD events * … | Queues, event logs |
| Set | SADD online users:17 | Membership, deduplication |
| HyperLogLog | PFADD visitors:2026-09-25 u17 | Approximate unique counts |
6.6 Worked example — document store for a CMS
@Document("articles")
public record Article(@Id String id, String slug, String title,
List<Block> body, List<String> tags,
Map<String, String> seo, Instant publishedAt) { }
public interface ArticleRepository extends MongoRepository<Article, String> {
Optional<Article> findBySlug(String slug);
List<Article> findTop10ByTagsContainingOrderByPublishedAtDesc(String tag);
}Heterogeneous content blocks (text, image, video, quote) fit naturally into an array of polymorphic sub-documents.
6.7 Worked example — wide-column for messaging
| Query | Table | Primary key |
|---|---|---|
| Messages in a conversation, newest first | messages_by_conversation | ((conversation_id), sent_at DESC, message_id) |
| Conversations of a user by last activity | conversations_by_user | ((user_id), last_activity DESC, conversation_id) |
6.8 Worked example — graph for recommendations
MATCH (u:Customer {id: $id})-[:BOUGHT]->(:Product)<-[:BOUGHT]-(other:Customer)
-[:BOUGHT]->(rec:Product)
WHERE NOT (u)-[:BOUGHT]->(rec)
RETURN rec.sku, count(*) AS score
ORDER BY score DESC LIMIT 10"Customers who bought what you bought also bought…" is a two-hop pattern expressed directly.
6.9 Worked example — category limits discovered late
| Category | Limit discovered | Typical workaround |
|---|---|---|
| Key-value | Need to query by value attributes | Secondary key structures, search index |
| Document | Many-to-many reporting across collections | Analytics pipeline to warehouse |
| Wide-column | New query not supported by key design | New table + backfill |
| Graph | Bulk aggregations over all nodes | Export to analytics engine |
6.10 Worked example — scoring categories for a use case
| Criterion (IoT platform) | Key-value | Document | Wide-column | Graph |
|---|---|---|---|---|
| Write rate 500 k/s | ◆ | ◆ | ✔ | ✘ |
| Range reads by device/time | ✘ | ◆ | ✔ | ✘ |
| Multi-region | ✔ | ◆ | ✔ | ◆ |
| TTL expiry | ✔ | ✔ | ✔ | ◆ |
| Result | — | — | Choose | — |
6.11 Worked example — access from one Spring Boot service
spring:
data:
mongodb.uri: mongodb://catalog-db:27017/catalog
redis: { host: cache, port: 6379 }
cassandra:
contact-points: cass-1:9042,cass-2:9042
keyspace-name: telemetry
local-datacenter: dc1Several stores in one service are possible, but each adds connection management, health checks and failure modes — Chapter 7 discusses when this is justified.
6.12 Worked example — time series in a document store
| Design | Documents for 1 device, 1 day, 10 s interval |
|---|---|
| One document per reading | 8,640 documents |
| Bucket pattern: one document per hour with array of readings | 24 documents |
| MongoDB time series collection | Internally bucketed and compressed automatically |
7Common Problems & Mistakes
- Querying key-value stores by value.
- Relational thinking in wide-column stores (
ALLOW FILTERING). - Graph databases for bulk analytics.
- Document stores for highly relational, cross-entity reporting.
- Choosing by product popularity instead of model fit.
- Ignoring multi-model maturity differences.
8Performance & Production Considerations
| Category | Key production concern |
|---|---|
| Key-value | Memory sizing, eviction, persistence settings |
| Document | Index design, document size, shard key |
| Wide-column | Partition size, compaction, repairs, tombstones |
| Graph | Memory for graph cache, query depth limits |
9Architecture & Design Considerations
- List access patterns first, then choose the model.
- Expect different data shapes of the same domain in different stores.
- Prefer fewer stores unless a workload clearly needs a specialised model.
- Revisit when new access patterns emerge that the chosen model handles poorly.
10Interview Questions & Answers
What are the four main NoSQL categories?
The four main categories, classified by data model, are key-value, document, wide-column and graph. Key-value stores such as Redis and DynamoDB map a key to an opaque value and are accessed by key. Document databases such as MongoDB and Couchbase store nested JSON or BSON documents and can index and query fields inside them. Wide-column stores such as Cassandra, HBase, Bigtable and ScyllaDB organise data by partition key into sorted rows that are read by key and clustering-key range. Graph databases such as Neo4j and Neptune store nodes and relationships and answer traversal queries. Each category is optimised for a different access pattern, so classify by model, not product.
What is a key-value database best at?
A key-value database is best at very fast, simple operations by key: get, put, delete, atomic increments and conditional writes, often with a time-to-live. Because lookups are hash-based and data is distributed by key, latency is low, sub-millisecond for in-memory stores like Redis or Valkey, and throughput scales almost linearly by adding nodes. Typical uses are HTTP sessions, caches, rate-limit counters, feature flags, idempotency keys and shopping carts. Redis also offers hashes, sorted sets and streams, so it covers leaderboards and simple queues too. The limit is that the store cannot query by value content; any second access path needs extra keys or a different store.
How does a document database differ from a key-value store?
The difference is how much the database understands about the value. In a key-value store the value is opaque bytes: the database can fetch it by key, but it cannot filter, index or partially update fields inside it. A document database parses the document, JSON or BSON, and understands its nested fields and arrays. You can create secondary indexes on fields, query by them, project only some fields, update one field atomically and run aggregation pipelines. So finding all customers in Pune with GOLD tier is an indexed query in MongoDB but a full scan or a hand-built index in Redis. The cost is more storage and CPU per operation than a pure key lookup.
What is a wide-column database designed for?
A wide-column database is designed for very high write throughput and predictable reads at large scale, when queries follow a known partition key. Data is grouped into partitions by a partition key, distributed across the cluster by hash, and within a partition rows are sorted by clustering columns. Writes go to a commit log and memtable and are flushed to immutable SSTables in an LSM tree, so writes are cheap and sequential. Reads are efficient for one partition plus a clustering range, such as the readings for one sensor on one day, newest first. Typical uses are time series, IoT telemetry, messaging inboxes and activity feeds spread across many nodes and data centres.
When is a graph database the right choice?
A graph database is the right choice when the important questions are about connections, especially variable-length, multi-hop paths: friends of friends who bought this product, rings of accounts sharing devices in fraud detection, or which services are affected if this component fails. Graph stores keep relationships as first-class, directly linked records, so each traversal step follows a pointer instead of performing a join, and cost depends on the part of the graph visited, not total table size. In SQL the same questions need many self-joins or recursive CTEs that slow down quickly with depth. It is not the right choice for bulk aggregations or simple CRUD; there a relational store is simpler.
Why do Cassandra tables follow a query-first design?
Because Cassandra can only read efficiently by partition key and, within a partition, by clustering-column order. There are no joins, and filtering on other columns means scanning the cluster, which is what ALLOW FILTERING asks for. So you start from each query and design a table whose primary key makes that query a single-partition read, for example PRIMARY KEY ((sensor_id, day), ts) for readings by sensor and day. If you also need to find users by email, you create a users_by_email table and write to both tables. Denormalisation and duplicate writes are the accepted price; the benefit is predictable latency at any scale. Partition size must stay bounded too.
What are multi-model databases and what should you watch for?
Multi-model databases support more than one data model in one product: PostgreSQL with jsonb for documents, MongoDB with graph lookups and time-series collections, Azure Cosmos DB with several APIs, or ArangoDB combining documents and graphs. They can reduce the number of systems to operate, secure and keep consistent. The thing to watch is that the secondary models are usually less mature than a specialised store: a graph traversal over documents may lack index-free adjacency, query-language features or performance at depth. So evaluate the specific capability with your real access patterns and data volumes, not the vendor's feature checklist, and check the operational limits before committing to it.
How do you pick a NoSQL category for a new system?
I begin by enumerating the access patterns: each read and write, its volume, latency target, consistency requirement and growth. Then I map patterns to models: lookups by key with TTL suggest key-value, whole aggregates queried by fields suggest document, high write rates read by partition and time range suggest wide-column, and multi-hop relationship questions suggest graph. I check each candidate's limits against the full list, for example missing secondary indexes or weak cross-partition transactions, and include operational cost, managed-service options and team skills. Often the relational database still serves most patterns. I choose the smallest set of stores that serves them all and record the decision in an ADR.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.