Skip to content
Commitwise
Menu
Databases

NoSQL databases: document, key-value, wide-column and graph

How MongoDB, Redis, DynamoDB, Cassandra and Neo4j store data and what they're good at. Covers embedding vs referencing, the 16 MB document trap, partition and sort keys, one table per query, hot partitions, LSM trees and tombstones, graph traversals, and how to answer "do we need NoSQL for scale?"

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“NoSQL” isn’t one kind of database. It’s a label for everything that isn’t relational: document stores like MongoDB, key-value stores like Redis and DynamoDB, wide-column stores like Cassandra, and graph databases like Neo4j. Each one gives up something SQL databases offer (joins, ad hoc queries, transactions across many rows) to be very good at one way of reading and writing data.

Interviews test whether you know what each one gives up. “Why not just use MongoDB?” and “how would you model this in DynamoDB?” both have answers that start with the queries, not the data. The examples reuse the shop from How relational databases work; the system-level view of choosing a store is in Databases: SQL, NoSQL, indexes and sharding.

New to some of these? Open what you need, or skip ahead.

Basics:Tables, keys and joins

A relational database keeps data in tables of rows and columns. Each row has a primary key that identifies it; a foreign key in another table points to it, and a join brings the related rows together in a query. Each fact is stored once, so changing a customer’s name is one update. See How relational databases work.

Basics:Indexes

An index is a sorted copy of some columns with pointers to the rows, so the database can jump to matching rows instead of reading the whole table. It speeds up reads and makes every write a little more expensive. See Indexes and query plans.

Basics:Replication

Big databases keep copies of the data on several machines (replicas), so one failure doesn’t lose data and reads can be spread out. Copies take a moment to catch up, so a read from one of them can briefly return old data.

Part Not started

Document databases: embed or reference

A document databaseDocument databaseA database that stores each record as a JSON-like document with nested objects and arrays.Open in glossary → stores each record as a document: a JSON-like object that can contain nested objects and lists. MongoDB is the best known; Firestore and Couchbase are others. Documents with the same purpose live in a collection, the rough equivalent of a table, but nothing forces them to have the same fields.

An order in a relational database is spread over orders and order_items, joined when you need them. In MongoDB, the order page can be one document:

{
  _id: 1001,
  customerId: 42,
  status: "PAID",
  items: [
    { productId: 7, name: "Mug", quantity: 2, unitPrice: 9.50 },
    { productId: 3, name: "Coffee beans 1 kg", quantity: 1, unitPrice: 24.00 }
  ],
  total: 43.00
}

Reading the order is one lookup, with no join. That’s the main idea: store data the way the app reads it.

The big design question is embed or reference:

  • Embed (put it inside the document) when the data is read together with the parent, belongs only to it, and stays small. Order items are the classic example.
  • Reference (store just an id, like customerId: 42) when the data is shared by many documents, changes on its own, or keeps growing. A customer has many orders and can change their email; copying the whole customer into every order would mean updating hundreds of documents.

Queries are written as documents too. db.orders.find({ status: "PAID" }) finds paid orders, and a query on a field inside an array, like { "items.productId": 7 }, finds orders that contain product 7. When a field holds an array, a condition on that field matches if any element matches.

  • Embed vs reference: embed what’s read together, owned by the parent and bounded; reference what’s shared, large, unbounded or updated independently. A document is limited to 16 MB (BSON), and every read and write moves the whole document, so growth matters long before the limit.
  • Modeling patterns: subset (embed the latest 10 reviews, keep the rest in their own collection), extended reference (copy the fields you display, like { customerId, name }, and accept they may be stale), bucket (one document per sensor per hour instead of per reading), computed (maintain counters on write).
  • Indexes: B-tree like SQL. Compound index order follows ESR: equality fields first, then sort fields, then range fields. An index on an array field is multikey (one entry per element); in a compound multikey index, at most one of the indexed fields can be an array in any one document. Partial, TTL and wildcard indexes exist.
  • Joins: $lookup in the aggregation pipeline does a left outer join, but if most queries need several, the model is fighting the access patterns.
  • Atomicity: a write to one document is atomic, including its nested arrays, which is why embedding often replaces a transaction. Multi-document transactions exist (replica sets since 4.0, sharded clusters since 4.2), with a 60-second default lifetime and a real cost; design so they’re rare.
  • Durability and reads: write concern majority (the default since 5.0) waits until most replicas have the write; read concern and read preference decide whether a read can see data that a failover may still roll back, or stale data from a secondary.
  • “Schemaless” means the schema lives in application code. $jsonSchema validators enforce shape on the server; old documents with old shapes stay until you migrate them.

Predict the output

Three products: A has tags ['coffee', 'sale'], B has tags ['coffee'], C has tags ['tea']. How many documents does each query return?

db.products.find({ tags: "coffee" }).count();
db.products.find({ tags: ["coffee"] }).count();
db.orders.insertOne({
  _id: 1001,
  customerId: 42,                                        // reference: customers live on their own
  status: "PAID",
  createdAt: ISODate("2026-11-08T10:15:00Z"),
  shipping: { name: "Ana Petrović", city: "Novi Sad" },  // embedded snapshot, kept as it was
  items: [
    { productId: 7, name: "Mug", quantity: 2, unitPrice: NumberDecimal("9.50") },
    { productId: 3, name: "Coffee beans 1 kg", quantity: 1, unitPrice: NumberDecimal("24.00") }
  ],
  total: NumberDecimal("43.00")
});

// a customer's latest orders: equality on customerId, then the sort
db.orders.createIndex({ customerId: 1, createdAt: -1 });
db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).limit(20);

// orders that contain product 7: a multikey index on the array
db.orders.createIndex({ "items.productId": 1 });
db.orders.find({ "items.productId": 7 });

// revenue per product, like GROUP BY
db.orders.aggregate([
  { $match: { status: "PAID" } },
  { $unwind: "$items" },
  { $group: { _id: "$items.productId",
              revenue: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } } } },
  { $sort: { revenue: -1 } }
]);

The blog post that stopped saving

Spot the bugComments stored in the post

Tap the line with the bug.

// posts: { _id, title, body, authorId, comments: [ ... ] }
function addComment(postId, comment) {
  return db.posts.updateOne(
    { _id: postId },
    { $push: { comments: comment } }
  );
}

function showPost(postId) {
  return db.posts.findOne({ _id: postId });
}

Deep diveMongoDB or PostgreSQL with jsonb?Interview favorite

“Our data is JSON, so we should use MongoDB” is the claim to examine. PostgreSQL’s jsonb stores documents in a column, indexes them (GIN for containment, expression indexes for specific fields), and keeps joins, constraints and multi-row transactions around them. Many teams store the stable fields as columns and the variable ones (product attributes, integration payloads) as jsonb.

Where jsonb is weaker:

  • Updates replace the whole value: changing one field in a 200 KB document writes a new 200 KB version, plus WAL. MongoDB also rewrites the document on disk, but replication sends only the changed fields.
  • Planner estimates: PostgreSQL keeps no statistics inside jsonb by default, so a filter like attrs->>'color' = 'red' gets a fixed guess. Expression indexes and CREATE STATISTICS on expressions (PostgreSQL 14+) fix specific cases.
  • Horizontal scale: MongoDB has built-in sharding and automatic failover in every replica set. PostgreSQL needs extensions or a managed service (Citus, distributed SQL) to shard.

Where MongoDB is weaker: joins and reports across collections, constraints between documents, and transactions that are rare by design. A good answer picks per data shape: varied, self-contained documents read by id at large scale favour MongoDB; related entities with reporting needs favour PostgreSQL with some jsonb. Then name what you’d lose either way.

  • Embed what’s read together, owned and bounded; reference what’s shared, unbounded or independently updated. 16 MB document limit; unbounded arrays are the classic bug.
  • Patterns: subset, extended reference, bucket, computed. ESR order for compound indexes; at most one array field per document in a compound multikey index.
  • One-document writes are atomic; multi-document transactions exist but are costly. majority write concern by default since 5.0.
  • jsonb in PostgreSQL covers many document needs; weaker on large partial updates, statistics and built-in sharding.
db.orders.createIndex({ customerId: 1, createdAt: -1 });   // equality, then sort
db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).limit(20);
db.posts.updateOne({ _id: id }, { $push: { latest: { $each: [c], $position: 0, $slice: 3 } } });
db.products.find({ tags: { $all: ["coffee", "sale"] } });

Check this part

  1. Order items are shown with the order and belong only to it. Embed or reference?

  2. Why is pushing every comment into the post document a problem?

  3. Query: equality on status, sort by createdAt, range on total. Which compound index order fits MongoDB's ESR rule?

  4. What is atomic in MongoDB without a transaction?

A document database stores each record as a JSON-like document with nested objects and arrays. Embed what's read together, owned by the parent and bounded; reference what's shared, large, growing or updated on its own. Documents have a 16 MB limit, single-document writes are atomic, and compound indexes follow the equality, sort, range rule.

Part Not started

Key-value and wide-column: design around the key

A key-value store is a huge hash map: you give it a key, it gives you the value. It can’t answer “which values contain X?” without reading everything, but lookups by key stay fast no matter how much data there is.

  • Redis keeps everything in memory and offers data structures as values: strings, hashes, lists, sets, sorted sets. It’s the usual choice for caches, sessions, counters and leaderboards, often with an expiry time (TTL) on each key. See Caching with Redis.
  • DynamoDB (AWS) stores items that are found by a key with up to two parts. The partition key decides which machine holds the item. The optional sort key keeps items with the same partition key sorted, so you can ask for a range: “customer 42’s orders from November, newest first”.

Wide-column stores like Cassandra and ScyllaDB look like SQL tables, but the primary key works the same way as DynamoDB’s: a partition keyPartition keyThe part of a key that decides which partition, and so which machine, stores an item.Open in glossary → picks the machines, and clustering columns sort the rows inside a partition.

The rule for all of them: a fast query must tell the database which partition to read. Asking “all paid orders” when the table is keyed by customer means visiting every partition on every machine. So instead of one normalized table and many queries, you design one table per query, and write the same order into each table that needs it. That’s a lot of duplication, and it’s deliberate.

QueryTablePartition keySorted by
A customer’s orders, newest firstorders_by_customercustomer_idcreated_at DESC
An order by its idorders_by_idorder_id(none)
Today’s orders for a warehouseorders_by_warehouse_day(warehouse_id, day)created_at
  • Redis: in-memory; commands execute on one thread (I/O threads since 6.0), so one slow command (KEYS *, a huge SMEMBERS) blocks everyone. Persistence by RDB snapshots and/or AOF; with appendfsync everysec a crash can lose about a second of writes. A cache or a fast secondary store, rarely the source of truth for money. Licensing changed in 2024; Valkey is the BSD-licensed fork, and Redis 8 added an AGPL option.
  • DynamoDB: the partition key is hashed to a partition; each partition serves at most about 3,000 read units and 1,000 write units per second. Items up to 400 KB. Query needs the partition key (sort key conditions optional); Scan reads the whole table. Global secondary indexes are copies with another key, updated asynchronously (eventually consistent reads only); local secondary indexes share the partition key and must be defined at table creation. TransactWriteItems handles up to 100 items; condition expressions give optimistic concurrency.
  • Cassandra / ScyllaDB: masterless ring placed with consistent hashingConsistent hashingA way to assign keys to servers so that adding or removing a server moves only about 1/N of the keys.Open in glossary →, replication factor per keyspace, tunable consistency per query (ONE, QUORUM, LOCAL_QUORUM, ALL); with QUORUM writes and reads on RF 3, reads see the latest write. Conflicts resolve by last write wins on cell timestamps, so clock skew can drop writes. IF NOT EXISTS lightweight transactions use Paxos and cost several round trips. Keep partitions bounded (a common guideline is under about 100 MB); time series get a time bucket in the partition key.
  • Hot partitions: one key taking most of the traffic (a celebrity, a flash-sale product, “today”) overloads one node however big the cluster is. Spread it with a suffix (write sharding: product#7#3) and read all suffixes, or cache in front.
  • Pagination is by key: DynamoDB returns LastEvaluatedKey (pages of at most 1 MB), Cassandra a paging state. There is no cheap OFFSET or total count.

Predict the output

This Cassandra table is keyed by customer. What does the query on status do?

-- Cassandra CQL
CREATE TABLE orders_by_customer (
  customer_id bigint,
  created_at  timestamp,
  order_id    bigint,
  status      text,
  total       decimal,
  PRIMARY KEY ((customer_id), created_at, order_id)
) WITH CLUSTERING ORDER BY (created_at DESC, order_id ASC);

SELECT * FROM orders_by_customer WHERE status = 'PAID';
-- newest 20 orders of customer 42: one partition, already sorted
SELECT order_id, created_at, status, total
FROM orders_by_customer
WHERE customer_id = 42
LIMIT 20;

-- a range inside the partition, using the clustering column
SELECT order_id, total
FROM orders_by_customer
WHERE customer_id = 42
  AND created_at >= '2026-11-01' AND created_at < '2026-12-01';

-- the same order is also written to the table keyed by id
INSERT INTO orders_by_id (order_id, customer_id, created_at, status, total)
VALUES (1001, 42, '2026-11-08 10:15:00+0000', 'PAID', 43.00);

-- a time series: bucket by day so no partition grows forever
CREATE TABLE orders_by_warehouse_day (
  warehouse_id int,
  day          date,
  created_at   timestamp,
  order_id     bigint,
  PRIMARY KEY ((warehouse_id, day), created_at, order_id)
);

Practice: keys for a DynamoDB table

Exercisemedium

One table, three queries

Put customers, orders and order items in one DynamoDB table with a partition key PK and a sort key SK (both strings). It must answer, each with a single Query or GetItem:

  1. Get a customer’s profile.
  2. List a customer’s orders, newest first, 20 at a time.
  3. Get an order with all its items.

Write down which items exist (their PK and SK) and how each query is made.

›

Items of different kinds can share a partition key. Prefixes like CUSTOMER#42 and ORDER#1001 keep the kinds apart.

›

A sort key that starts with the date sorts by date. A Query can ask for sort keys that begin with a given prefix and read them in reverse.

SolutionTry it yourself first
PKSKOther attributes
CUSTOMER#42PROFILEname, email
CUSTOMER#42ORDER#2026-11-08T10:15:00Z#1001status, total
CUSTOMER#42ORDER#2026-11-02T08:01:00Z#987status, total
ORDER#1001INFOcustomerId, status, total, shipping
ORDER#1001ITEM#7name, quantity, unitPrice
ORDER#1001ITEM#3name, quantity, unitPrice
  1. GetItem with PK = CUSTOMER#42, SK = PROFILE.
  2. Query with PK = CUSTOMER#42 and begins_with(SK, 'ORDER#'), ScanIndexForward = false (newest first), Limit = 20. The next page starts from the returned LastEvaluatedKey.
  3. Query with PK = ORDER#1001: the info item and every item row, in one request.

The order summary is written twice (under the customer and under the order), in one TransactWriteItems so the copies can’t disagree. Dates in ISO format sort correctly as strings, which is why they go first in the sort key. A query nobody planned, like “all orders over 100”, isn’t possible without a scan or a new index: that’s the price of the design.

Deep diveLSM trees: why these stores write so fast, and what deletes costInterview favorite

Cassandra, ScyllaDB, RocksDB (and MyRocks), HBase and CockroachDB’s Pebble store data in a log-structured merge treeLSM treeA storage structure that buffers writes in memory and flushes them to immutable sorted files.Open in glossary → rather than a B-tree. A write appends to a commit log and goes into an in-memory sorted table (the memtable). When it fills up, it’s flushed to disk as an immutable sorted file (an SSTable). Nothing is updated in place, so writes are sequential and cheap.

Reads pay for it: a key may live in the memtable and in several SSTables, so a read checks them newest first, skipping most files with Bloom filters. Background compaction merges SSTables and drops overwritten values. The trade-off is often described as three amplifications: B-trees have higher write amplification (whole pages rewritten for small changes), LSM trees have higher read and space amplification until compaction catches up. Compaction strategy (size-tiered, leveled, time-window) is a real tuning decision.

A delete can’t remove data from immutable files, so it writes a tombstoneTombstoneA marker that records a deletion, so other devices or replicas learn that the item was deleted.Open in glossary →, a marker that hides older values. In Cassandra, tombstones stay at least gc_grace_seconds (10 days by default) so that replicas that missed the delete don’t bring the data back. The classic failure is using Cassandra as a queue: insert jobs, delete them when done, read “the oldest pending job”. Every read then scans thousands of tombstones; Cassandra warns at 1,000 per query and aborts at 100,000 by default. The answer is a design that doesn’t delete inside hot partitions: time-bucketed partitions that expire whole, TTLs with time-window compaction, or a real queue.

  • Redis: in memory, single-threaded commands, RDB/AOF (about 1 s loss with everysec); cache or derived store. Valkey is the BSD fork.
  • DynamoDB: partition key (about 3,000 RCU and 1,000 WCU per partition) plus sort key; Query vs Scan; GSIs eventually consistent; 400 KB items; 100-item transactions.
  • Cassandra: ((partition), clustering); one table per query; tunable consistency; last write wins; bounded partitions with time buckets; no ALLOW FILTERING in production.
  • Hot keys: write sharding or a cache. LSM trees: fast writes, compaction, tombstones (don’t build queues on them).
-- CQL
CREATE TABLE events_by_device_day (
  device_id uuid, day date, ts timestamp, payload text,
  PRIMARY KEY ((device_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
  AND default_time_to_live = 2592000;   -- 30 days
SELECT * FROM events_by_device_day WHERE device_id = ? AND day = ? LIMIT 100;

Check this part

  1. What does the partition key decide in DynamoDB or Cassandra?

  2. The orders table is keyed by customer. You also need orders by warehouse. What is the usual Cassandra answer?

  3. A flash-sale product gets 90% of the writes in a DynamoDB table. What happens?

  4. Why is a Cassandra table used as a job queue a known anti-pattern?

Key-value and wide-column stores find data by key: a partition key picks the machine and a sort or clustering key orders items inside it. You design one table or key layout per query, because filtering on anything else means a full scan. A key that gets most of the traffic becomes a hot partition. LSM-tree storage makes writes fast and deletes leave tombstones.

Part Not started

Graph databases, other specialists, and choosing

A graph databaseGraph databaseA database that stores nodes and the relationships between them, and follows relationships directly.Open in glossary → stores nodes (people, products, accounts) and relationships between them (FOLLOWS, BOUGHT, USES_DEVICE), and both can have properties. Neo4j is the best known; its query language, Cypher, draws the pattern you’re looking for with brackets and arrows:

MATCH (ana:Person {name: 'Ana'})-[:FOLLOWS]->(friend:Person)
RETURN friend.name

(…) is a node, -[:FOLLOWS]-> is a relationship in one direction. The database finds every path that fits the pattern and returns one row per path.

Graphs shine when the question is about connections several steps away:

  • “People you may know”: friends of friends who aren’t your friends yet.
  • Fraud: accounts that share a phone number, a device or a card with an account already banned, up to four steps away.
  • Recommendations: “people who bought this also bought”.
  • Permissions: a user is in a group, which is inside another group, which can read a folder.

In SQL each step is another join (or a recursive CTE, from Subqueries and CTEs), and the query gets harder to write and slower with each step. In a graph database, each node points directly at its neighbours, so a step costs about the same however big the whole graph is.

Graphs aren’t the only specialists. A real system often has several stores, each fed from one source of truth:

NeedStoreExamples
Full-text search with typos and rankingSearch engine (inverted index)Elasticsearch, OpenSearch
Reports over billions of rowsColumnar analyticsClickHouse, BigQuery, Snowflake, DuckDB
Metrics and sensor readings over timeTime seriesTimescaleDB, InfluxDB, Prometheus
“Find similar” for AI embeddingsVector searchpgvector, Qdrant, Pinecone
Many-hop relationshipsGraphNeo4j, Amazon Neptune, Memgraph
  • Graph model: property graphs (Neo4j, Memgraph, Neptune) with Cypher or Gremlin. ISO GQL (2024) standardizes a language close to Cypher, and SQL:2023 added SQL/PGQ for graph pattern queries over tables. In PostgreSQL, recursive CTEs or the Apache AGE extension.
  • Strengths: traversal cost depends on the part of the graph touched, not its size (index-free adjacency); variable-length paths (-[:FOLLOWS*1..3]->), shortest paths, and patterns that would be many self-joins.
  • Weaknesses: whole-dataset aggregates, very high-degree supernodes (a celebrity with 50 million followers turns every traversal through them into a scan), sharding a graph without cutting most traversals across machines.
  • Cypher semantics: within one MATCH, a relationship is used at most once per path but nodes can repeat, and every path is a row. Use DISTINCT, and exclude the start node and existing neighbours explicitly.
  • Derived stores: search, analytics and vector indexes are fed by change data capture or the transactional outboxTransactional outboxSaving an outgoing message in the same database transaction as the data change, and publishing it afterwards.Open in glossary →, lag behind the source, and must be rebuildable from it.
  • Columnar engines store each column separately and compress it, so an aggregate over three columns of a billion rows reads only those columns; single-row updates are expensive. They answer OLAP questions; the transactional database (OLTP) runs the app.

Predict the output

Ana follows Bo and Cara. Bo follows Ana and Dan. Cara follows Dan. What names does this return?

MATCH (ana:Person {name: 'Ana'})-[:FOLLOWS]->(:Person)-[:FOLLOWS]->(fof:Person)
RETURN fof.name
// accounts up to two links away from a banned one (account, shared phone/device/card, account)
MATCH path = (bad:Account {banned: true})-[:USES*1..4]-(other:Account)
WHERE other.banned = false
RETURN other.id, min(length(path)) / 2 AS distance
ORDER BY distance;
-- account_links(account_id, thing_id): one row per account using a phone, device or card
WITH RECURSIVE reach(account_id, distance, seen) AS (
    SELECT id, 0, ARRAY[id] FROM accounts WHERE banned
  UNION ALL
    SELECT b.account_id, r.distance + 1, r.seen || b.account_id
    FROM reach r
    JOIN account_links a ON a.account_id = r.account_id
    JOIN account_links b ON b.thing_id = a.thing_id
    WHERE r.distance < 2
      AND b.account_id <> ALL (r.seen)
)
SELECT account_id, min(distance) AS distance
FROM reach
WHERE distance > 0
GROUP BY account_id
ORDER BY distance;

Both find the same accounts. In the graph, one account-to-account step is two relationships (account uses a phone, the phone is used by another account), so *1..4 in Cypher covers the same two account-to-account steps as distance < 2 in SQL, and dividing the path length by 2 gives the same distance. The SQL needs a recursive CTE and an array to avoid going in circles; the Cypher reads like the question.

Practice: follow suggestions in SQL

Exercisemedium

People you may know

A relational table stores who follows whom: follows(follower_id, followee_id), primary key on both columns. Write a query that suggests people for user 1 to follow:

  • people followed by the people user 1 follows,
  • but not user 1 themself, and not anyone user 1 already follows,
  • ranked by how many of user 1’s followees follow them (mutual connections), at most 10.
›

Join follows to itself: the first copy is user 1’s followees, the second copy is who those people follow.

›

“Not anyone user 1 already follows” is an anti-join: NOT EXISTS with a subquery on follows. The ranking is count(*) per suggested person.

SolutionTry it yourself first
SELECT f2.followee_id AS suggested, count(*) AS mutual
FROM follows f1
JOIN follows f2 ON f2.follower_id = f1.followee_id
WHERE f1.follower_id = 1
  AND f2.followee_id <> 1
  AND NOT EXISTS (
      SELECT 1 FROM follows mine
      WHERE mine.follower_id = 1
        AND mine.followee_id = f2.followee_id)
GROUP BY f2.followee_id
ORDER BY mutual DESC, suggested
LIMIT 10;

Each path through a followee is one row before grouping, the same as in Cypher, which is why count(*) counts mutual connections. Two steps are fine in SQL with an index on (follower_id, followee_id); at four or five steps, or when the steps vary, a graph database becomes the simpler tool.

Deep dive"Do we need NoSQL for scale?"Interview favorite

The question usually hides an assumption that relational databases don’t scale. Start with numbers: a single well-tuned PostgreSQL or MySQL primary on current hardware handles tens of thousands of simple writes per second and several terabytes, read replicas multiply read capacity, and partitioning keeps big tables manageable. Most products never outgrow that, and they keep joins, constraints and transactions.

Good reasons to choose a NoSQL store, each tied to a requirement:

  • Write volume or data size beyond one primary, with simple key-based access: event logs, IoT readings, messages. Cassandra, ScyllaDB, DynamoDB.
  • Operations: DynamoDB has no servers, versions or failover to manage and stays fast at any size, if the access patterns are known up front.
  • Multi-region writes with low latency in every region: Cassandra, DynamoDB global tables, accepting last-write-wins conflicts.
  • Data shape: graph traversals, full-text search, time series, vectors.

What you pay: queries you didn’t plan for are expensive or impossible, duplicated data must be kept in sync by your code, consistency is often eventual, and schema changes become backfill jobs. If you need both SQL and horizontal scale, distributed SQL (CockroachDB, Spanner, YugabyteDB) is a third option, with higher latency per transaction. A strong answer: “PostgreSQL for orders and payments, because they need transactions and reporting; this one high-volume, key-accessed dataset goes to Cassandra; search is derived into OpenSearch through the outbox.”

  • Graphs (Neo4j, Neptune; Cypher, ISO GQL, SQL/PGQ): many-hop traversals cost what they touch; supernodes and global aggregates hurt. In Cypher, paths are rows and nodes can repeat: DISTINCT and explicit exclusions.
  • Specialists: search, columnar OLAP, time series, vector; all derived from a source of truth via CDC or outbox.
  • “NoSQL for scale”: one PostgreSQL primary goes far; choose NoSQL for key-access write volume, serverless operations, multi-region writes, or data shape. Distributed SQL is the third option.
MATCH (me:Person {id: $id})-[:FOLLOWS]->(:Person)-[:FOLLOWS]->(s:Person)
WHERE s <> me AND NOT (me)-[:FOLLOWS]->(s)
RETURN s.id, count(*) AS mutual
ORDER BY mutual DESC LIMIT 10;

Check this part

  1. Which question is a graph database best at?

  2. Product search with typo tolerance and ranking: where does it usually run?

  3. A Cypher friends-of-friends query returns the user themself. Why?

  4. Which is a strong reason to pick Cassandra over PostgreSQL?

Graph databases store nodes and relationships and follow them directly, which makes many-hop questions (friends of friends, fraud rings, recommendations) fast and simple to write. Search engines, columnar analytics, time-series and vector stores are other specialists, usually fed from the main database. Choose by access pattern and transaction scope; a relational database is the default.

Key takeaways

  • NoSQL stores give up joins and ad hoc queries to be very good at one access pattern. Design starts from the queries.
  • Documents: embed what’s read together and stays small; reference what’s shared or keeps growing. Unbounded arrays break at 16 MB.
  • Key-value and wide-column: the partition key picks the machine; design one table per query and duplicate on purpose.
  • Graphs make many-hop relationship questions simple; search, analytics, time series and vectors have their own specialists.
  • A relational database is the default; pick another store for a specific need.
  • MongoDB: ESR indexes, one-document atomicity, rare transactions; jsonb covers many document cases.
  • DynamoDB/Cassandra: per-partition limits, hot keys, eventually consistent indexes, last write wins, bounded partitions.
  • LSM trees: fast sequential writes, compaction, tombstones that punish delete-heavy designs.
  • Cypher paths are rows and nodes repeat; supernodes are the graph’s hot keys.
  • Justify NoSQL with an access pattern and a number, and name the cost; distributed SQL is the alternative.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.