NoSQL Data Models
NoSQL and Non-Relational Data Models
IntermediateLesson 8 of 8 in Database Design and Advanced SQL Course
What you will learn
- Describe what the relational model offers, why NoSQL databases appeared, how the four main non-relational families organize data, and how access patterns drive the choice of model.
- Compare the relational model with the four NoSQL familiesDefine NoSQL, name the document, key-value, wide-column and graph families, and contrast them with tables, joins and a schema declared in advance.
- Describe data by its shape, relationships and access patternsClassify data as structured, semi-structured or unstructured, read JSON, recognize one-to-many and many-to-many relationships, and list the access patterns a data model must serve.
- Compare the relational model with the four NoSQL families
- Design documents and collections, decide what to embed and what to reference, and use keys, values and expiry times in a key-value store.
- Structure and query data as documentsBuild documents with nested objects and arrays, group them in collections, query and update them by field, and know what a single-document write guarantees.
- Decide when to embed and when to referenceChoose between nesting related data inside a document and linking documents by identifier, using the relationship's type, its growth and how the data is read and updated.
- Store and retrieve data in a key-value storeDesign keys, choose value types, set expiry times and recognize workloads such as caching, sessions and counters that suit lookups by key.
- Structure and query data as documents
- Design partitioned, query-first tables in a wide-column store, represent connected data as a property graph, and query graphs with patterns.
- Design wide-column tables around queriesUse partition keys and clustering columns to group and sort rows, keep partitions bounded, and write one table per query in a store such as Apache Cassandra.
- Represent connected data as a property graphModel entities as nodes and connections as typed, directed relationships with properties, and explain when a graph fits better than tables.
- Query a graph with pattern matchingRead and write Cypher patterns that match nodes, follow relationships and limit traversal depth, and compare them with the SQL needed for the same question.
- Design wide-column tables around queries
- Explain how databases keep copies of data on several nodes and split data across nodes, and predict the effects on availability, performance and correctness.
- Replicate data across nodesExplain why databases keep copies on several nodes, compare single-leader, multi-leader and leaderless replication, and predict what replication lag does to reads.
- Shard data across nodesSplit a dataset into shards with a shard key, compare range and hash partitioning, avoid hotspots and work out how much data moves when nodes are added.
- Replicate data across nodes
- Distinguish consistency models, apply the CAP theorem and its latency extension correctly, and tune quorum reads and writes for a workload.
- Distinguish consistency modelsDefine strong and eventual consistency and the session guarantees between them, and separate the consistency in ACID from the consistency that distributed systems trade away.
- Apply the CAP theoremState the CAP theorem precisely, explain why the real choice during a network partition is between consistency and availability, and extend it with the latency trade-off of PACELC.
- Tune consistency with quorum reads and writesUse the replication factor N, the write count W and the read count R to predict whether reads see the latest write, how many failures a setting tolerates and how conflicting writes are resolved.
- Distinguish consistency models
- Match a workload to a suitable data model step by step, and design an application that uses several databases while keeping them in sync.
- Match a workload to a data modelCompare access patterns, relationships, scale and consistency needs to choose relational, document, key-value, wide-column or graph storage for a workload, and justify the choice.
- Design a polyglot persistence architectureAssign each part of an application to a suitable store, decide which store is the system of record, keep the stores in sync and weigh the gains against the extra operating cost.
- Match a workload to a data model
NoSQL Data Models study guide
1Explain how non-relational data models differ from the relational model
A data model shapes the reads and writes an application can perform easily. You already know how tables, keys, constraints, and joins organize relational data. Here you will compare that approach with four non-relational families, then describe a workload precisely enough to choose among them. Start with the application's questions: the same records can lead to different designs when the required reads, growth, or update rules change.
1.1 Compare the relational model with the four NoSQL families
A database's model determines the shape of its records and how queries connect them. NoSQL, usually expanded as "not only SQL," groups databases whose main model is non-relational. It names several approaches, not one language or performance guarantee.
Compare the units of data
In a relational database, a declared schema defines tables, typed columns, keys, and constraints. Foreign keys connect rows; joins assemble related facts. Normalization stores each fact once, which helps prevent conflicting copies.
| Model | Main unit | Typical way to retrieve related data |
|---|---|---|
| Relational | Row | Join tables through keys |
| Document | Nested document | Read an aggregate or filter by a field |
| Key-value | Value under a unique key | Supply the key |
| Wide-column | Keyed rows with varying columns | Read rows by shared or neighboring keys |
| Graph | Nodes and typed relationships | Follow a relationship pattern |
MongoDB and CouchDB are document examples; Redis is a key-value example. Cassandra and HBase are wide-column stores, with different key structures. Neo4j stores property graphs. Cassandra's CQL resembles SQL, so SQL-like syntax does not make a store relational.
Match an object to a storage boundary
An aggregate is related data treated as one unit, such as an order with its items and delivery address. Document, key-value, and wide-column designs often organize around aggregates. Keeping a whole aggregate together makes it easier to retrieve and place on one server. A graph emphasizes individually connected nodes and relationships instead.
Consider a user profile with three past jobs and two phone numbers. A normalized schema might use users, jobs, and phones. The program assembles the rows into a nested profile object. A document can hold that nested shape directly. The gap between application objects and relational tables is the object-relational impedance mismatch; mapping between the two requires code even when a relational design is a good choice.
Locate the schema
Schema-on-write checks a record's structure when it is saved. Schema-on-read lets reading code interpret records whose shapes can differ. A flexible collection still has expectations: code that reads address.city must handle an absent address. Many document databases also offer validation rules. "Schemaless" hides this responsibility.
Explain why alternatives appeared
NoSQL systems spread in the late 2000s as applications needed more write capacity across ordinary servers, changing record structures, closer matches to application objects, and low-latency key lookups. Google's Bigtable design appeared in 2006; Amazon's Dynamo appeared in 2007 and influenced leaderless key-value systems.
These needs do not establish a speed ranking. A store optimized for known keys may struggle with an unplanned report. NoSQL systems can have transactions: single-record atomic writes are common, and MongoDB and Neo4j support multi-record ACID transactions. Relational systems remain useful for business transactions and can support flexible fields too, such as indexed PostgreSQL jsonb.
Key Takeaways
- NoSQL describes non-relational models, not a ban on SQL-like languages.
- The model determines the normal units of storage and the available query paths.
- An aggregate groups data that the application treats as one unit.
- A flexible record still has a schema expected by its readers.
- Performance and transaction support depend on the workload and database design.
1.2 Describe data by its shape, relationships and access patterns
A useful database design starts with the reads and writes the application must perform. Data shape matters, but a list of fields alone cannot tell you how to store them.
Read the shape
Structured data uses a fixed set of typed fields, as in table rows. Semi-structured data carries field names or tags while allowing records to differ. JSON and XML are examples. Unstructured data, such as audio, images, and free text, lacks an internal record structure that the database can query field by field.
In JSON, braces contain an object of field-value pairs, and square brackets contain an array. Values can be strings, numbers, booleans, null, objects, or arrays:
{"name": "Lena", "skills": ["SQL", "Python"], "address": {"city": "Lyon", "postalCode": "69002"}}
Here skills is an array of two strings and address is a nested object. Postal codes are strings: they are identifiers, and arithmetic on them has no useful meaning.
Follow the relationship in both directions
A post can own many comments. Nesting those children in the parent copies no shared parent record. But embedding a city's full details in every resident's document duplicates the city many times. One-to-many and many-to-one describe opposite views of the same relationship; the chosen nesting direction decides what gets copied.
Many-to-many links, such as students taking courses, create duplication when complete records from either side are embedded repeatedly. Shared data is usually referenced by ID. Ownership, update needs, and growth decide a boundary more reliably than the relationship's name alone.
Write an access pattern precisely
An access pattern describes a specific operation: what the request already knows, the needed filters and sort order, how often it runs, and its response-time target. For a delivery app, these are different patterns:
- Fetch a menu by restaurant ID, very frequently, in under 50 ms.
- List a customer's 20 newest orders, newest first.
- Save a courier's position every 5 seconds.
- Produce monthly sales totals for every restaurant.
Also record data volume, growth, read/write ratio, freshness needs, and whether future queries are predictable. A workload with 95% reads of a few popular records differs from one adding 4,000 sensor readings per second.
Shape records around the important reads
Relational design usually starts with entities and normalized relationships. Queries and indexes can support many later questions. Query-first NoSQL design starts with access patterns, then aims to answer a frequent request through one document, key, or partition. An unforeseen query may need a new structure.
For a blog page, normalized posts, comments, and users can be joined. A document can instead embed the latest 20 comments and copied display names so one read returns the page. That duplication is denormalization. It saves reads, but a name change now affects every copied name. The design must update those copies or accept a delay. Choosing a product before listing these reads and update costs leaves the main design evidence missing.
Key Takeaways
- Classify the data shape and describe its relationships separately.
- An access pattern includes known keys, filters, ordering, frequency, and latency.
- Nesting direction determines which facts are duplicated.
- Query-first design trades general query flexibility for direct frequent reads.
- Denormalization creates a responsibility to maintain changing copies.
- Estimate growth and read/write rates before choosing storage.
2Model data in document databases and key-value stores
A document can bring an application object and its related data into one read. A key-value store makes a different promise: give it a known key, and it retrieves the value. In this chapter you will build and query documents, decide where their boundaries belong, and design keys and expiration rules. The central question is what should travel and change together, especially when some related data is shared or keeps growing.
2.1 Structure and query data as documents
A document database stores a record with its field names and nested structure. Documents belong to collections and have unique identifiers. MongoDB uses BSON, a binary format that also supports types such as dates, 64-bit integers, and decimals; its identifier field is _id.
Build an order aggregate
{"_id": "order-1001", "customerId": "c-17", "status": "shipped", "items": [{"sku": "MUG-01", "qty": 2, "unitPrice": 8.50}, {"sku": "TEA-03", "qty": 1, "unitPrice": 12.00}]}
The order owns an array of item objects. Two mugs contribute 17.00 and one tea contributes 12.00, so the total is 29.00. A single read returns all of these items. In normalized tables, orders and order_items would be separate.
A collection can hold different shapes. Book documents might have isbn and pages; clothing documents might have size and color. Reading code must handle missing fields and distinguish record types where that affects interpretation.
Query fields and update only what changes
MongoDB filters can reach nested fields with dot notation:
db.orders.find({"status": "shipped", "items.sku": "MUG-01"})
This finds shipped orders containing at least one item with that SKU. It does not return only the matching line item; it selects matching order documents. A secondary index on a search field such as customerId can avoid a collection scan, just as a relational index can avoid a table scan.
db.orders.updateOne(
{"_id": "order-1001"},
{"$set": {"status": "delivered"}}
)
The filter selects the order, and $set changes its status while preserving the items. Update operators can also increment values and add array elements. Reading and rewriting the whole object is unnecessary for a one-field change.
Decide what the database must enforce
MongoDB does not require a collection validator by default. An optional $jsonSchema validator can require fields and types; with its default enforcement settings, an invalid insert or update is rejected. This is useful for fields that every reader relies on.
A single-document write is atomic: all its changes to fields and embedded arrays happen together, or none do. Updating two documents is a different boundary and needs a multi-document transaction when both must change together. Embedding data that changes as a unit often avoids that extra coordination.
Keep the document workable
MongoDB's document limit is 16 MiB, or 16,777,216 bytes, with at most 100 nesting levels. An ever-growing array can become expensive to load and update before reaching either limit. Store open-ended histories separately.
Stable field names also help queries. Instead of making each date a field name, store uniform entries such as {"date": "2026-10-01", "count": 5}. MongoDB can join collections with $lookup; its cost depends on indexes, matching counts, and document sizes. If most page reads need several lookups, compare that design with relational and graph alternatives before accepting it.
Key Takeaways
- A collection groups documents;
_iduniquely identifies each MongoDB document. - Dot notation filters nested fields, including fields inside array elements.
- Partial update operators preserve fields that the update does not change.
- Atomicity applies to one document; coordinated changes across documents need a transaction.
- Validation can enforce required fields without making all documents identical.
- Bound document growth and use stable field names.
2.2 Decide when to embed and when to reference
A document boundary decides which information arrives in one read and changes in one atomic write. Embedding places related data inside that boundary. Referencing keeps an identifier pointing to a separate document.
Ask what belongs together
Embed children that belong to one parent, are usually read and updated with it, and stay bounded. Two or three delivery addresses fit naturally inside a customer profile. One profile read gets the addresses, and an address edit changes one document.
Reference related records when they are shared, independently meaningful, frequently updated on their own, or able to grow without a useful bound. A product used in thousands of orders should have a central identity. A plain document reference resembles a foreign key, but MongoDB does not enforce the referenced record's existence; the application must manage missing or deleted targets.
| Decision factor | Favors embedding | Favors referencing |
|---|---|---|
| Ownership | Child belongs to one parent | Record is shared |
| Reads | Data is usually read together | Records are queried independently |
| Updates | Changes belong in one atomic unit | Related data changes independently |
| Growth | A small bounded group | A large or open-ended history |
Check the growth, not just today's size
If each comment contributes about 1 KiB, dividing 16 MiB by 1 KiB gives 16,384 comment-sized chunks. That uses the entire byte budget before the post's own fields and document overhead, so an actual document reaches the limit earlier. A busy post can outgrow an embedded comment array, and loading it can become slow well before the hard limit.
Store the full comment history in a comments collection, indexed by postId and createdAt. Keep only the latest 10 comments in the post if the first page needs them immediately. This subset pattern combines a bounded embedded preview with a referenced full history. New comments must update the history and the preview consistently enough for the page's needs.
Separate a snapshot from a live copy
An order should preserve the product name and price at purchase. If the catalog price rises from 12.00 to 14.00, the old order keeps 12.00. This is a historical snapshot, so changing it to today's price would corrupt the purchase record.
A copied author display name usually has a different meaning. If it is meant to show the current name, a rename copied into 5,000 comments creates 5,000 updates or a period of stale names. Reference frequently changing shared data, or explicitly accept and manage those delayed updates.
Model shared links with a size in mind
For students and courses, an ID array can sit on either side, or a separate link collection can hold each enrollment. If students take about 6 courses while courses have 400 students, courseIds in each student keeps the array short; an index can support finding students by course.
Work from access patterns, record cardinality and expected growth, choose the boundary, then check the resulting reads. Embedding every order in a customer creates unbounded growth. Referencing every small child creates extra lookups even when the page always needs the whole group.
Key Takeaways
- Embed owned data that is read together, changes together, and stays bounded.
- Reference shared, independent, frequently changing, or unbounded related data.
- A purchase snapshot must preserve the values at purchase time.
- The subset pattern embeds a limited preview while storing the full history separately.
- Choose the side of an ID array that keeps growth manageable.
2.3 Store and retrieve data in a key-value store
A key-value store retrieves a value through a unique key. The basic operations are set, get, and delete. For a plain value, the store does not search its contents; another lookup route needs another designed key or data structure.
Design the key from the request
Use information the application already has. Keys such as user:42:profile, session:9f3a7c, and cart:42 combine a purpose with an identifier. They should be unique and predictable. Hashing keys can spread them across servers, and in-memory stores such as Redis often serve a request within a millisecond.
A session token supports direct lookup. Finding every session for a user is a different access pattern; placing a user ID inside an opaque value does not create a searchable index.
Give temporary values an expiration
SET session:9f3a7c "user=42" EX 1800
GET session:9f3a7c
TTL session:9f3a7c
EX 1800 gives the key a time to live (TTL) of 1,800 seconds, or 30 minutes. GET retrieves the value until it expires; TTL reports its remaining lifetime in seconds. Once expired, the key is absent and GET returns nil. Sessions, one-time codes, and cached results often need this automatic removal.
Choose a value structure
Redis offers strings, hashes, lists, sets, and sorted sets. A hash holds named fields within one key; a list preserves insertion order; a set keeps unique members; a sorted set orders members by numeric score.
HSET cart:42 MUG-01 2 TEA-03 3
HINCRBY cart:42 MUG-01 1
The hash maps product codes to quantities. The increment changes the mug quantity from 2 to 3 without rewriting a large JSON string.
ZADD scores 1520 ana 1710 ben 1385 cleo
ZRANGE scores 0 1 REV WITHSCORES
Ranks 0 through 1 select two entries, in descending order: ben with 1710, then ana with 1520. Use an atomic command such as INCR page:home:views for concurrent counters. Two separate reads followed by two writes can lose an increment; two atomic increments both count. A rate limit can pair a counter with a 60-second expiry.
Keep a cache tied to its source
With cache-aside, the application checks product:501. On a hit, it returns the cached value. On a miss, it reads the authoritative database, caches the result with a TTL such as 300 seconds, and returns it. A product update changes the database and invalidates the cache key. A missed invalidation can leave the old entry visible until that entry expires.
A cache is a rebuildable copy. Durability in an in-memory store depends on persistence settings, such as Redis snapshots or its append-only file. Important permanent data needs a durable system of record.
Key-value storage suits sessions, carts, feature flags, and counters. Content searches and cross-record reports need more structure. Avoid listing every key with KEYS * on a busy server; SCAN works in batches. Expiry and sensible value sizes also keep the memory footprint under control.
Key Takeaways
- A key must be predictable from information available in the request.
- An opaque value cannot support a field search without another designed lookup structure.
- A TTL automatically removes temporary data.
- Choose a Redis structure that supports the required update directly.
- Atomic increments prevent lost updates in counters.
- Cache-aside loads misses from the system of record and needs invalidation.
- Persistence settings determine what survives a crash.
3Model data in wide-column stores and graph databases
Some workloads revolve around large streams of keyed events; others revolve around paths between connected entities. Wide-column stores and graph databases serve these two needs in different ways. You will design a Cassandra table from a required time-range query, then build a property graph and read Cypher patterns. In each case, the model makes certain operations direct while putting limits on queries that ignore its structure.
3.1 Design wide-column tables around queries
A wide-column store keeps keyed rows whose populated columns can vary. Cassandra and HBase both belong to this family, but their keys work differently. In Cassandra, a partition key groups rows on the same replica nodes, and clustering columns sort the rows inside that partition. HBase sorts rows by a row key, splits tables into key-range regions, and groups columns into declared column families.
Distinguish wide-column from columnar
A columnar analytical database stores columns separately to scan and aggregate selected fields over many rows. A wide-column store is organized for keyed reads and writes. Its name does not mean that it is a data warehouse optimized for arbitrary column scans.
The following design uses Cassandra and CQL. Start with the query: "Get the 10 newest readings for one sensor on one day."
CREATE TABLE readings_by_sensor_day (
sensor_id text,
day date,
reading_time timestamp,
temperature_c decimal,
PRIMARY KEY ((sensor_id, day), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);
Read the primary key in two parts
The inner parentheses group sensor_id and day into the composite partition key. Cassandra hashes that pair to select the replica nodes. reading_time is the clustering column: it sorts rows newest first and distinguishes rows inside the partition.
SELECT reading_time, temperature_c
FROM readings_by_sensor_day
WHERE sensor_id = 'S-12' AND day = '2026-10-29'
LIMIT 10;
Both partition components are supplied, so the request can go straight to one partition and read its first 10 rows. A time restriction can narrow the ordered rows within that partition. Key restrictions must follow the declared clustering order.
Bound the partition
At one reading every 10 seconds, one sensor adds 8,640 rows per day. At an illustrative 50 bytes per row, that is about 432,000 bytes, or 0.43 MB. A year gives 3,153,600 rows and about 158 MB. Using only sensor_id would put all those rows in one continually growing partition. Adding day creates time buckets with a predictable size.
A bounded bucket can still be busy, so check both rows per bucket and traffic per key. A low-cardinality key such as country creates a few large partitions and concentrates work.
Build another table for another query
A building-wide daily view needs a different partition key, (building_id, day), and clustering columns such as (reading_time, sensor_id). Write readings to both query tables. This deliberate duplication avoids joins, which CQL does not provide, but the application must maintain both representations.
A non-key filter such as temperature_c > 30 is not served by this primary key. Without a suitable index, allowing filtering can require an expensive scan; it does not fix the data layout. Design a query table or index for that access pattern.
Cassandra writes are upserts. Inserting an existing full primary key updates its stored values. If two events can share a timestamp, add an event identifier to the clustering key so both events survive. A SQL-like table declaration does not give CQL the query flexibility or duplicate-key behavior of a relational table.
Key Takeaways
- In Cassandra, the partition key selects placement and clustering columns order rows within it.
- Use a time bucket to bound a growing event partition.
- A required query should match its table key or an appropriate index.
- Different access patterns often need different denormalized tables.
- An upsert with the same full primary key updates the existing row.
- HBase uses row keys, regions, and column families; its key model differs from Cassandra's.
3.2 Represent connected data as a property graph
A property graph represents entities as nodes and their connections as relationships. Nodes have labels, such as Person or Product. Each relationship has a type and direction. Both nodes and relationships can carry named properties.
Model the meaning of a connection
(:Person {name: "Ana"})-[:FOLLOWS {since: 2024}]->(:Person {name: "Ben"})
This says Ana follows Ben, beginning in 2024. It does not say Ben follows Ana. A query can traverse an edge in either direction, but the stored direction still carries meaning.
A practical starting point is to turn nouns into nodes, verbs into relationship types, and descriptive values into properties. Then check whether the resulting graph answers the required questions. A city can be a city property when the app only displays a name. A City node with LIVE_IN relationships is more useful when the app finds residents through their shared city.
A purchase with its own date, payment method, and several products is an Order node linked to a customer and products. Putting all that meaning on one BOUGHT edge would make the multi-product structure awkward. Use a node when a connection becomes an entity that other records need to connect to.
Follow edges from a starting node
For "friends of friends," a relational query joins a link table to itself. The planner may use indexes, a hash join, or a merge join. A native graph database such as Neo4j finds a starting node, then follows its stored relationships directly to neighboring nodes. This index-free adjacency makes local traversal depend mainly on the relationships visited.
The starting node still needs to be found. An index on a person's identifier avoids scanning every person before the traversal begins. Traversal speed depends on the actual paths, filters, and data; the existence of relationships alone does not make a graph faster than SQL.
Control the expansion
With 100 connections from each visited person, two steps can generate up to 10,000 path expansions, and three up to 1,000,000. Repeated people may reduce the count of distinct results, but the engine still has work to do to explore paths. Bound the depth and apply useful filters early.
A supernode has an unusually large number of edges, such as a celebrity with millions of followers. A path through it can expand sharply even at shallow depth. Specific relationship types and property filters can reduce the relevant work. Keeping connections as an ID list hidden in a property prevents the graph engine from treating them as traversable edges.
Choose the model for the question
Graphs fit fraud-ring searches, recommendations, social connections, routes, and system dependencies, especially when paths have several or variable numbers of steps. Isolated key lookups and whole-dataset totals often fit simpler models.
RDF is another graph model: it stores subject–predicate–object triples, such as Ana–follows–Ben, and uses SPARQL. Property graphs put properties directly on nodes and edges. Choose the graph model and query language together; they are related approaches with different data representations.
Key Takeaways
- Nodes represent entities; typed, directed relationships represent their connections.
- Properties can belong to nodes or relationships.
- The required questions decide whether a value should become a property or a separate node.
- Index-free adjacency speeds local traversal after the start node is found.
- Bound traversal depth and account for supernodes.
3.3 Query a graph with pattern matching
Cypher expresses a graph question as a pattern to match. Parentheses describe nodes; brackets describe relationships. Labels and properties narrow the match. Cypher helped shape GQL, the ISO graph query language published in April 2024 as ISO/IEC 39075.
Read one directed step
MATCH (a:Person {name: "Ana"})-[:FOLLOWS]->(b:Person)
RETURN b.name
The query finds Ana, follows outgoing FOLLOWS relationships, and returns the names at their ends. Removing the arrowhead makes the pattern match either direction, which changes the question. An index on :Person(name) can help find Ana before the traversal begins.
Work through a two-step recommendation
Use these directed edges: Ana→Ben, Ana→Cleo, Ben→Dev, Ben→Cleo, Cleo→Dev, and Cleo→Ana. Every edge has type FOLLOWS.
MATCH (a:Person {name: "Ana"})-[:FOLLOWS]->(:Person)
-[:FOLLOWS]->(c:Person)
WHERE c <> a AND NOT EXISTS { (a)-[:FOLLOWS]->(c) }
RETURN DISTINCT c.name
First expand Ana's two outgoing edges to Ben and Cleo. From Ben, the second step reaches Dev and Cleo. From Cleo, it reaches Dev and Ana. The candidate results are therefore Dev, Cleo, Dev, and Ana.
The self-exclusion removes Ana. The direct-follow exclusion removes Cleo because Ana already follows her. DISTINCT combines the two remaining occurrences of Dev, giving one recommendation. Filtering and deduplication solve different problems: removing duplicates alone would still leave unsuitable candidates.
Specify a path length
The quantified relationship -[:FOLLOWS]->{1,3} follows one to three outgoing steps. The older form -[:FOLLOWS*1..3]-> is also supported. An upper bound limits exploration in a large graph.
MATCH p = shortestPath(
(a:Person {name: "Ana"})-[:FOLLOWS*]->
(d:Person {name: "Dev"})
)
RETURN length(p)
For this small graph, the shortest directed path has length 2, through Ben or Cleo. The function returns a shortest path, so it need not return every path with that length.
Compare a fixed path with SQL
With a table follows(follower, followee), two steps can be expressed as:
SELECT DISTINCT f2.followee
FROM follows f1
JOIN follows f2 ON f1.followee = f2.follower
WHERE f1.follower = 'Ana';
This SQL query returns the raw two-step destinations; it does not yet exclude Ana or existing direct follows. More fixed steps add self-joins. A variable depth needs recursion, typically a recursive common table expression. Cypher makes the path structure visible in the query.
Write patterns as well as read them
CREATE (:Person {name: "Eva"}) adds a node. Match two existing nodes before creating a relationship between them. MERGE matches a complete pattern when it exists and creates it when absent, making repeated sequential loads easier to repeat safely. To enforce unique node identities during concurrent loads, add an appropriate uniqueness constraint; MERGE alone does not enforce node uniqueness.
Key Takeaways
- An arrow in a Cypher pattern controls relationship direction.
- Trace intermediate nodes before applying endpoint filters.
DISTINCTremoves repeated results caused by multiple paths.- A bounded variable-length pattern supports several depths without a separate query per depth.
- Indexes help find starting nodes; traversal then follows relationships.
MERGEreuses an existing matching pattern; concurrent uniqueness needs a constraint.
4Distribute data with replication and sharding
Adding servers changes where data lives and how failures affect an application. Replication keeps copies; sharding divides the dataset. You will follow a write through replicas, examine stale reads and failover, and then choose how records are assigned to shards. These decisions interact: a database can split its records into many shards and keep several replicas of every shard, with different consequences for reads and writes.
4.1 Replicate data across nodes
Replication keeps copies of the same records on several servers. Copies can serve reads near users, spread read traffic, and keep data available after a machine fails. The write path and acknowledgment rule determine what those copies guarantee.
Follow a single-leader write
In single-leader replication, clients write to the leader, also called the primary. It records changes and sends them to followers or secondaries. Reads may go to the leader or followers. MongoDB replica sets and the built-in replication of PostgreSQL and MySQL use this approach.
| Replication mode | When the client hears success | Main consequence |
|---|---|---|
| Synchronous | After the required follower confirms | Extra waiting; an acknowledged copy survives leader loss |
| Asynchronous | Before followers need to confirm | Faster acknowledgment; uncopied writes can be lost on failover |
A deployment can combine the modes, with one synchronous follower and others receiving changes asynchronously. Waiting for a follower adds network delay and can stall writes if that follower cannot be reached.
Predict a stale read
Suppose a follower is 500 ms behind. At time 0 a user changes a profile photo and receives confirmation from the leader. At 200 ms a reload reaches the follower, which still holds the old photo. That is replication lag, the delay between a confirmed write and its appearance on a follower.
The user needs read-your-writes behavior. Route their read to the leader, or to a follower known to have applied that write. A fixed waiting interval is only safe if it actually covers the lag; checking catch-up gives a stronger basis. Other users can keep using followers when a briefly old photo is acceptable.
Replace a failed leader safely
Failover promotes a follower when the leader fails. An asynchronous follower may be missing recent acknowledged changes. There is also a split-brain risk if the old leader continues accepting writes while another is promoted.
A majority election helps prevent two active primaries. In a three-voting-member MongoDB replica set, two votes are needed to elect a primary. One isolated member cannot form that majority and steps down if it was primary. The connected pair can elect a primary and continue serving writes, subject to the required acknowledgments.
Compare other write paths
In multi-leader replication, several leaders accept local writes and exchange them. That reduces distance to a writer but allows concurrent edits to the same record. A merge rule, last-write-wins rule, or application decision must resolve conflicts.
In leaderless replication, a coordinator sends a write to multiple replicas and asks several for reads. Quorum settings determine the number of replies needed. Repair mechanisms bring stale copies up to date; there is no permanent single write leader.
Keep the purpose of a copy clear
Read replicas do not remove a single leader's write bottleneck: each write still passes through it. Replication also copies mistakes. An accidental deletion can promptly reach every replica, so recovery still needs backups that preserve earlier states. Evaluate the required write rate, read freshness, failover behavior, and backup plan separately.
Key Takeaways
- Replication adds copies and can spread reads; it does not split the dataset.
- Synchronous acknowledgment waits for a required replica; asynchronous acknowledgment can precede copying.
- Follower reads can be stale because of replication lag.
- Majority elections help prevent split brain during failover.
- Multi-leader and leaderless designs require explicit conflict and consistency rules.
- Replicas do not replace historical backups.
4.2 Shard data across nodes
Vertical scaling gives a database a larger machine. Horizontal scaling adds machines. Sharding scales out the dataset by assigning each record to one logical shard using a shard key. Each shard can also have replicas, so division and copying can happen together.
Choose range or hash placement
Range partitioning assigns continuous key intervals to shards, such as customer names A–F and G–M. Nearby keys stay together, helping range queries. But an increasing timestamp sends all new writes to the newest range. That shard becomes a hotspot while older shards stay quiet.
Hash partitioning hashes a key to choose its shard. It spreads distinct keys without preserving their original order. A query for one known key can be routed directly; a range across different keys usually needs multiple shards.
| Placement | Helps | Main risk or cost |
|---|---|---|
| Range | Neighboring-key range reads | Concentrated writes to a growing end range |
| Hash | Spreading many distinct keys | Range reads lose locality |
Understand what moves when capacity grows
With shard = hash(key) mod N, changing the shard count changes the divisor for every key. Growing from 4 to 5 shards leaves the same numbered assignment for about 20% of uniformly distributed hashes; about 80% move. The extra server requires redistribution far beyond its own eventual share.
Consistent hashing places keys and node positions on a ring. A key belongs to the next node clockwise. Adding a node takes over part of the existing ring; with balanced shares, growth from four to five nodes moves about one fifth of keys. Multiple virtual-node positions per physical server help balance ownership and traffic. The exact movement depends on the actual positions and data distribution.
Check the query and the traffic
A good shard key has many distinct values, distributes both records and load, and appears in the main query filter. Sharding orders by customer_id makes one customer's history local. A report on all orders from yesterday needs requests to all relevant shards and a combined result: scatter-gather.
Even a good hash cannot divide one hot key. Every request for a celebrity's post still reaches the shard owning that key. A cache can absorb reads. Splitting a write counter into keys such as post:77:0 through post:77:9 spreads updates, but reads must combine the parts. The extra read work is part of the trade-off.
Include the coordination costs
A cross-shard join needs data from several servers. A transaction spanning shards needs a coordination protocol, such as two-phase commit, or may be unsupported. Rebalancing moves records while the database serves requests. Changing a shard key later can require rewriting data placement.
A low-cardinality key such as country limits how many independent groups can be spread and may produce very uneven shards. A well-indexed server with read replicas can be enough when reads are the bottleneck. Shard when measured data or write needs justify the new routing and coordination costs.
Key Takeaways
- Sharding divides records; replication can keep copies of every shard.
- Range placement preserves key locality but can concentrate sequential writes.
- Hash placement spreads distinct keys and makes cross-key ranges less local.
- Consistent hashing limits movement when balanced capacity is added.
- A hot individual key remains hot even with a well-distributed hash.
- Choose a shard key using query routing, data distribution, and traffic distribution.
- Cross-shard work and rebalancing add operating and coordination costs.
5Reason about consistency trade-offs in distributed databases
Copies of data need a contract for what readers can see while writes spread across servers. You will compare consistency guarantees, reason through a network partition, and calculate quorum settings. Keep the business rule in view: a delayed view count and a second sale of the last seat have very different costs. The arithmetic explains replica overlap and failure tolerance; transaction rules explain whether competing updates can safely succeed.
5.1 Distinguish consistency models
A consistency model specifies what a replicated database may return while writes spread between copies. The useful question is whether a particular read is allowed after the writes that have already happened.
Place the read on a timeline
Strong consistency, or linearizability, makes operations behave as if they act on one copy in real-time order. After a write completes, a later read returns its value or a newer one. A read overlapping a write may return the old or new value, depending on where the operations take effect.
Eventual consistency promises convergence if new writes stop. Replicas may disagree before convergence, and the definition gives no fixed time limit.
Suppose replicas A, B, and C hold x = 5. A write sets x = 7 and is confirmed after A stores it. B and C receive it 300 ms later. Reading B at 100 ms returns 5. Eventual consistency allows that result. Linearizability does not, because the write completed before the read began.
Name the guarantee actually needed
| Guarantee | What it protects |
|---|---|
| Read-your-writes | A client sees its own earlier changes |
| Monotonic reads | A client's reads do not move backward after seeing newer data |
| Causal consistency | Readers see dependent operations in their cause-before-effect order |
| Consistent prefix | A reader sees an initial part of one agreed write order |
The first two are session guarantees. A profile editor may need read-your-writes without requiring that every other user immediately see the new photo. Monotonic reads prevents a user from seeing version 8 and then version 6 after switching replicas.
Causal consistency prevents a reply from appearing before the question it answers. Unrelated concurrent changes may appear in different orders. Consistent prefix is a separate ordering guarantee: seeing an earlier segment of an agreed sequence is allowed; seeing a later event with earlier events missing is not.
Separate the two meanings of consistency
The C in ACID concerns valid database states: a transaction respects constraints and application invariants. The other ACID properties are atomicity, isolation, and durability. Replica consistency concerns which version a read can see. A constraint-preserving transaction and a fresh distributed read answer different questions.
BASE means "basically available, soft state, eventually consistent." It is an informal design description, not a precise substitute for a database's documented operation guarantees.
Protect the whole business operation
Stock, balances, and bookings need current authoritative state for decisions. Strong reads alone do not make a separate check followed by a write safe. Two clients can each read "1 seat left" before either changes it, then both create bookings.
Use an atomic conditional update, a uniqueness constraint, or a sufficiently isolated transaction so the check and change are protected together. A delayed like count may be acceptable; a second sale of the last seat is a different business outcome.
Convergence also says nothing about preserving every concurrent edit. Last-write-wins can make replicas agree by discarding one version. The conflict policy must retain or merge the information the application needs.
Key Takeaways
- Linearizability respects the real-time order of completed operations.
- Eventual consistency promises convergence, with no fixed convergence deadline.
- Session guarantees can protect one user without making every read globally current.
- Causal consistency orders dependent operations; consistent prefix preserves an agreed prefix.
- ACID consistency concerns valid states; replica consistency concerns observable versions.
- An atomic check-and-update protects competing decisions; fresh reads alone do not.
5.2 Apply the CAP theorem
A network partition prevents groups of database nodes from exchanging messages. Each group may still receive client requests. CAP explains the guarantees that cannot all be maintained in that situation.
Use CAP's precise meanings
Consistency means linearizability: operations behave like one current copy in real-time order. Availability means every request received by a non-failing node eventually gets a non-error response. Partition tolerance means handling lost communication between nodes.
When a partition occurs, a distributed system cannot guarantee both consistency and availability. Eric Brewer proposed the conjecture in 2000; Seth Gilbert and Nancy Lynch proved it in 2002. Partitions can arise from failed links, switches, or network configuration, so a distributed design must decide how to respond.
Follow a decision on both sides
A ticket shop has East and West data centers and one seat left. Their link fails. If both sides independently accept a sale, both clients get success but the application can sell the same seat twice.
A CP response preserves consistency by refusing or delaying operations that cannot be safely coordinated. Some clients cannot complete a sale during the partition. An AP response keeps answering locally, allowing stale state or conflicting accepted changes that must later be reconciled. For a cart, merging additions after communication resumes may be an acceptable trade-off. For the final seat, a rejected second sale is usually preferable to two confirmed owners.
"Pick any two" hides the timing of this choice. A distributed system cannot prevent all partitions simply by choosing the letters C and A. When communication works, it can provide both; during a partition, it must give up at least one guarantee for affected operations.
Read a configuration, not a permanent label
In Cassandra, ONE waits for one replica and can succeed with just one reachable replica. QUORUM needs a majority of the item's replicas. In a split, the minority cannot complete a quorum operation. Ordinary quorum settings alone are not linearizable; conditional operations needing that guarantee use lightweight transactions.
MongoDB writes require a majority-elected primary. A minority side cannot accept writes by lowering its write concern. Secondary reads may continue there if configured, and can return stale data. Read and write behavior can therefore differ within the same partition.
CAP availability is stricter than everyday uptime. A system can serve nearly all users most of the year and still give up CAP availability because some non-failing nodes must reject requests during a split. CAP itself does not specify normal-operation latency or disk durability.
Consider the healthy network too
Daniel Abadi's PACELC formulation, published in 2012, adds: if there is a partition, choose availability or consistency; else, consider latency versus consistency. Waiting for a distant replica adds a network round trip even when nothing has failed. Between continents that can be around 100 ms or more.
For a workload, identify the cost of inconsistent success, decide whether refusal or stale data is worse during a partition, and then assess the normal latency budget. Apply the database's actual settings to those requirements.
Key Takeaways
- During a partition, a distributed system cannot guarantee both linearizability and CAP availability.
- CP behavior may reject or delay requests; AP behavior permits results needing reconciliation.
- CAP availability means every non-failing node answers, not a high annual uptime percentage.
- Product behavior depends on the operation, configuration, and database architecture.
- PACELC also considers latency versus consistency when the network is healthy.
5.3 Tune consistency with quorum reads and writes
A leaderless database sends writes to several replicas and gathers replies. The replication factor, N, is the number of replicas for one item. W counts required write acknowledgments; R counts replicas needed for a read. Reads compare versions among the replies they receive.
Calculate overlap
For strict replica sets, read and successful-write sets must intersect when:
With three replicas A, B, and C, a write confirmed by A and B overlaps any two-replica read. Reading B and C reaches B, which has the write. Equality is insufficient: with four replicas, a two-replica write and two-replica read can use disjoint pairs.
A majority quorum is:
For N of 3 it is 2; for N of 5 it is 3. Majority reads and writes satisfy the strict overlap rule.
Work out failure tolerance
Writes need W reachable replicas and can tolerate N minus W being unreachable. Reads can tolerate N minus R. For N = 5 and R = W = 3, both still work with two unavailable replicas: three remain, and the read/write sum is 6, greater than 5.
With N = 3, R = W = 1 is responsive but may read a replica missing a completed write. W = 3 and R = 1 gives overlapping reads after successful writes, but every write needs all three replicas. One unavailable replica blocks writes while reads can still succeed.
In Cassandra, levels such as ONE, QUORUM, LOCAL_QUORUM, and ALL choose acknowledgment requirements per operation. LOCAL_QUORUM uses a majority in the local data center. A low write level does not send the update to fewer replicas: the coordinator sends it to all responsible replicas and waits for fewer confirmations.
Keep the copies repaired
Read repair updates stale versions discovered by a read. Hinted handoff stores a missed write for an unavailable replica and replays it when the replica returns. Anti-entropy repair compares replica data, using Merkle trees in Cassandra, and copies missing changes. These mechanisms address different paths by which replicas fall behind.
Concurrent values still need conflict resolution. Cassandra uses last-write-wins per column, choosing the latest timestamp. Clock differences can distort that choice, and one genuine concurrent change can be discarded. Version vectors can detect concurrency so an application can merge values, for example by taking a union of cart items.
Recognize the limit of the arithmetic
Overlap alone does not guarantee linearizability. With N = 3 and R = 2, an unfinished or failed write can reach only A. A read of A and B may return it; a later read of B and C may return the old value. Readers see time move backward even though their sets overlap.
Coordinated repair before a read returns can close this gap in suitable protocols. Sloppy quorums that count stand-in nodes can lose the strict-set overlap itself. For operations such as claiming a unique username, use a stronger mechanism such as a consensus-based lightweight transaction. A read overlapping a write may legally return the old or new value.
Key Takeaways
- R and W count required replies among N replicas for an item.
- Strict read/write sets overlap when the sum is greater than N; equality is insufficient.
- Writes tolerate N minus W unreachable replicas; reads tolerate N minus R.
- A consistency level changes the wait for acknowledgments, not the intended replication factor.
- Repair brings stale copies forward; conflict resolution chooses or merges competing versions.
- Last-write-wins can discard concurrent changes and depends on timestamps.
- Quorum overlap alone does not provide linearizability.
6Choose data models for workloads and combine them
Choosing a database means matching measured needs to a model the team can operate. You will turn access patterns, data growth, relationships, and correctness rules into a reasoned choice. Then you will combine stores where a specialized model earns its cost. The final design must say which copy is authoritative, how derived copies receive changes, and what happens when an update is delayed, retried, or delivered out of order.
6.1 Match a workload to a data model
A model earns its place by making the important operations simple while meeting correctness and operating requirements. Start with a workload description that another developer could use to check your choice.
Build the decision from evidence
- List the main reads and writes, known keys, filters, ordering, frequency, and latency targets.
- Describe record shape, ownership, and relationships.
- Estimate volume, growth, and request rates.
- State freshness, atomicity, transaction, and constraint needs.
- Identify predictable queries and ad hoc questions.
- Compare the simplest workable designs, including the team's skills and operating cost.
A database family is a useful starting point, not a performance measurement.
Match the dominant work
| Model | Particularly useful when the workload needs |
|---|---|
| Relational | Multi-row transactions, constraints, joins, and changing reports |
| Document | Whole records with nested or varying attributes |
| Key-value | Low-latency retrieval and updates by known keys |
| Wide-column | Heavy writes and keyed time-range reads across nodes |
| Graph | Multi-step or variable-depth connection queries |
Relational systems suit payments, bookings, inventory, and business records. They also scale through indexes, read replicas, and, where needed, sharding or distributed SQL. Variable attributes alone do not force a new database: a relational JSON column such as PostgreSQL jsonb may be enough.
Work through a high-volume location feed
Twenty thousand delivery vans report every 5 seconds. Each van sends 17,280 updates per day. Across the fleet that is 345,600,000 daily writes, or 4,000 writes per second. The main read asks for one van's track on one day.
A Cassandra-style table can partition by (van_id, day) and cluster by time. Distinct vans distribute writes, each daily bucket bounds growth, and the required track read targets one partition. A model choice based only on the daily total would miss these key reasons. Also check whether the observed load fits a simpler existing database before adding infrastructure.
Compare workloads that look similar on the surface
Sessions for 200,000 concurrent users, retrieved by token on every request and expiring after 30 minutes, fit key-value storage with TTLs. A museum's 3,000 exhibits have different attributes for paintings and fossils, so documents fit their varied record shapes. A transfer that must debit one account and credit another together fits relational transactions and constraints.
Finding accounts connected through shared devices or phone numbers within three steps fits a graph. Merely storing a customer ID on an order does not justify graph storage: an ordinary join may already answer every required question.
Count the cost of another engine
A multi-model engine offers several data representations in one system. A relational engine with JSON or a recursive SQL query may avoid a second service for a modest need. A specialist can still win when its measured benefit matters, but the comparison must include backups, security, monitoring, upgrades, and team knowledge. A key-value design that cannot answer a required monthly report is incomplete even if its individual lookups are fast.
Key Takeaways
- Write the access patterns and correctness rules before selecting a family.
- Calculate rates and partition growth, not just a total dataset size.
- Match graph storage to path questions and wide-column storage to keyed write-heavy workloads.
- Relational JSON and multi-model features may satisfy a need without another engine.
- Include team skills and operating cost in the comparison.
6.2 Design a polyglot persistence architecture
Polyglot persistence uses several kinds of databases in one application. Martin Fowler popularized the term in 2011. It can improve a difficult workload, but every extra store creates another copy or ownership boundary to manage.
Assign each job and its authority
An online store might use relational tables for orders, payments, and stock; documents for varied product attributes; key-value storage for carts and sessions; a graph for recommendations; and a search index for full-text product search.
For each fact, name one system of record, the authoritative store. The order database owns the accepted purchase. A recommendation graph built from purchases is derived data and can be rebuilt. A cache or search index can be useful without becoming a second authority.
This distinction answers a practical recovery question: if the stores disagree, which value should win? Two stores both treated as authoritative leave that question unresolved.
Trace the failure in a dual write
Suppose the application commits an order, then adds it to the graph. The order succeeds and the graph request fails. Retrying the whole business operation could duplicate the order, while doing nothing leaves the graph missing the purchase. Even when both writes succeed, concurrent updates can reach the stores in different orders.
These dual writes do not become atomic simply because one application issues both. A database transaction in the first store does not include a later request to another engine.
Publish changes from a committed record
Change data capture (CDC) reads changes from the system of record's log and sends them to derived stores. The transactional outbox writes the business change and an event row in the same local transaction. A separate process publishes the committed event. If that transaction fails, neither the order nor its event is committed; if publishing fails, the committed event remains available for retry.
Delivery still needs two safeguards. First, retries can deliver an event twice. An idempotent consumer makes applying the same event again have the same effect as applying it once. It can record event IDs to skip repeats. Setting a value to its recorded state can be idempotent; incrementing a count on every delivery is not.
Second, changes to the same record must be applied in their original order. Deduplicating events does not stop an older status from overwriting a newer one. Preserve per-record ordering or reject obsolete versions so a replay cannot move derived state backward. With reliable retries, duplicate handling, and ordering, the stores can converge after delays.
Keep ownership and operating cost visible
In microservices, a service usually owns its database and exposes data through APIs or events. Several services may all use the same database technology. The architecture becomes polyglot when they choose different kinds of stores; service ownership alone does not establish that.
Every engine needs monitoring, backups, security, upgrades, and expertise. Queries spanning stores need application-level combination, and failures can leave derived views temporarily behind. Start with a general-purpose database and add a specialist when a measured query, scale, or latency problem justifies those costs. A rebuildable cache should never be the only durable copy of an important business fact.
Key Takeaways
- Polyglot persistence combines database types within an application.
- Give each fact one system of record and treat other copies as derived.
- Sequential writes to two stores can leave them inconsistent.
- CDC and a transactional outbox publish changes tied to committed business data.
- Retries require idempotent consumers, and record updates require preserved ordering.
- A specialized store must justify its operating and synchronization costs.
NoSQL Data Models examples
1Choose a useful shape for application data
10 steps
- 1IntroductionStart with the page the app needs
A learning platform must display a member profile, recent activity, and connections to other members. Those features use related data, but they do not necessarily need the same storage shape.
You will compare the units each model retrieves, then describe the reads before deciding how records should fit together into one aggregate. The aim is a design whose common requests have clear lookup paths and whose changing copies can be maintained.
- 2ExplanationCompare how a request reaches its data
Relational queries combine rows through keys and joins. A document can hold a nested profile as one record. A key-value lookup supplies a known key. A wide-column query targets keyed rows, while a graph query follows typed relationships.
These are different access routes, not a speed ranking. A direct token lookup and a search for several levels of member connections ask different things of the database.
- 3ExampleKeep a profile together
A member profile contains a name, two phone numbers, and three past jobs. Normalized tables can hold the member, phones, and jobs separately; the application assembles the profile.
A document can store the nested profile directly. Treating that group as one read/write unit makes it an aggregate. This reduces object-to-table mapping for the page, while shared records may still belong outside the aggregate.
- 4ChallengeRead the model behind the syntax
A database uses a SQL-like language, but its rows are grouped by hashed partition keys and ordered by clustering columns. Does the language make this a relational database?
---reveal---
No. The data model and storage organization determine the family. Cassandra uses CQL with SQL-like statements while remaining a wide-column store. Familiar syntax does not guarantee joins or arbitrary relational query flexibility.
- 5Key InsightFind the schema in the reader
Suppose one profile has an address and another has none. A reader that blindly accesses
address.citycan still fail even though the database accepted both records.Flexible storage moves some structure checking into application code. An optional validator can enforce fields the application always needs. The choice is where and when to check structure, not whether the application has any expectations.
- 6ExplanationDescribe one operation precisely
"Show recent activity" leaves several design questions open. A useful access pattern says: "Given a member ID, return that member's 15 newest activities, newest first, on each profile visit."
Add frequency and latency targets, then estimate growth and freshness needs. The known ID supports routing; the sort requirement affects record order; the growing history affects whether one embedded array will remain practical.
- 7ExampleRead a nested record
Consider
{"name": "Mina", "skills": ["SQL", "Java"], "address": {"city": "Dakar"}}.The outer braces contain an object.
skillscontains an array of strings, andaddresscontains another object. This is semi-structured data: field names carry the structure, and other profiles can omit or add fields. The photo itself is unstructured data even if the profile stores its URL in a named field. - 8ChallengeChoose where a shared place belongs
Every member document embeds the current name and contact details of a shared training center. The center changes its phone number. What maintenance work follows?
---reveal---
Every copied phone number must be updated, or some profiles will show the old number. The nesting direction duplicated the shared center. Referencing a central center record can avoid that repeated change when current details are required.
- 9ChallengeRecheck a growing page aggregate
The platform proposes embedding every activity and every connected member's full profile in one member document. The page shows only recent activities, while connections and profiles change independently. How should the boundary change?
---reveal---
Keep the owned profile bounded, store the full activity history separately, and reference independently changing members. A limited recent-activity preview can serve the page. An aggregate should follow the read pattern without absorbing unbounded history or shared live records.
- 10RecapUse the operation to judge the model
Check a proposed shape by naming the request it serves, the record or key it reaches, and the facts it duplicates.
You should be able to explain where structure is checked, which group is handled as one aggregate, and what must happen when a copied fact changes. Those answers give concrete reasons to compare models.
2Build a bounded document and a session lookup
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDesign a record that stays useful
- 2ExampleRepresent an order as nested items
- 3ExampleChange the status without replacing the items
- 4ChallengeFind the boundary of the guarantee
- 5ExplanationKeep bounded owned data inside
- 6ExampleSeparate history from the first-page preview
- 7ChallengeKeep the meaning of a copied price
- 8TipLeave room inside the size limit
- 9ExampleConstruct a key the request knows
- 10ExplanationUpdate a cart field directly
- 11ExampleFollow a cache miss
- 12ChallengePredict a lookup after expiry
- 13ChallengeSeparate durable facts from temporary copies
- 14RecapCheck one read and one change
3Lay out an event table and trace a graph query
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse the structure the query needs
- 2ExplanationName the lookup before the key
- 3ExampleRead the CQL key layout
- 4ExampleEstimate a bucket’s growth
- 5ChallengePreserve two simultaneous events
- 6ExplanationTurn connections into graph structure
- 7ExampleGive a rich purchase its own identity
- 8ChallengeRespect the stored direction
- 9TipWatch the node with many connections
- 10ExampleStart a two-step pattern
- 11ExampleList the endpoints before filtering
- 12ChallengeReturn one suitable recommendation
- 13ExplanationBound a variable path
- 14ConnectionFind where an index still helps
- 15ChallengeMatch a model to the changed query
- 16RecapTrace keys and paths separately
4Follow copies and choose shard placement
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate copies from ownership
- 2ExplanationFollow the acknowledgment
- 3ExamplePlace a read inside the lag
- 4ChallengeDecide what one isolated voter can do
- 5Key InsightKeep a recovery copy from before the mistake
- 6ExampleRoute one customer’s orders
- 7ExplanationCompare two timestamp placements
- 8ExampleMove only the added share
- 9ChallengeFind the remaining hotspot
- 10ChallengeCombine the two kinds of distribution
- 11RecapCheck routing, load, and recovery
5Test consistency against a read timeline
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what the client can observe
- 2ExampleMark when the write finishes
- 3ExplanationProtect one client’s session
- 4ConnectionKeep cause before effect
- 5ChallengeFind the race after a current read
- 6ExampleSplit the communication link
- 7ChallengeDecide what the business can reconcile
- 8Key InsightCount the normal coordination delay
- 9ExplanationDefine the three counts
- 10ExampleShow a guaranteed intersection
- 11ExampleSubtract the replicas still needed
- 12ChallengeCombine overlap with a failure target
- 13ExplanationRepair a copy and resolve a conflict
- 14ExampleTest an unfinished write
- 15TipDistinguish a legal overlap in time
- 16ChallengeChoose the mechanism for a unique claim
- 17RecapAudit a guarantee in three passes
6Choose stores and deliver changes safely
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the choice explainable
- 2ExampleMeasure the dominant operation
- 3ExplanationMatch the correctness requirement too
- 4ChallengeReconsider a proposed graph
- 5ExplanationName the original and the view
- 6ExampleCommit the event with the purchase
- 7ChallengeRetry without counting twice
- 8TipKeep older changes from winning
- 9ChallengeRecover a failed search update
- 10RecapWrite the operational decision
NoSQL Data Models practice questions
Set 1: Recognize models and follow basic operations10 Practice Questions
Question 1 of 10
EX 240. There are no later changes. What is its configured lifetime?Show answerHide answer
EX option measures a key’s lifetime in seconds, so this key expires after 240 seconds. Milliseconds use a different expiration option. Confusing those units changes the intended retention time by a factor of one thousand and can make temporary data disappear too early.Question 2 of 10
PRIMARY KEY ((machine_id, month), event_time). What forms the partition key?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
$set to change only its status. What happens to its embedded line items?Show answerHide answer
$set changes the named field and preserves the document’s other fields, including its embedded items. This single-document update is atomic within that document. Treating it as a full replacement would incorrectly remove data the update never asked to replace.Question 6 of 10
Rui-[:SUPERVISES]->Sara and no reverse relationship. What fact does that edge record?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Apply boundaries, routing, and consistency rules10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
FOLLOWS edges Uma→Vik, Uma→Wen, Vik→Xia, and Wen→Xia. What does a two-step query from Uma return after DISTINCT is applied to endpoint names?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(probe_id, day) as its partition key and time as its clustering column. A new requirement lists all probes’ readings for one greenhouse on one day. The table has no secondary indexes. How should its query design change?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Diagnose a design before it causes data loss10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
capacity, but the database currently accepts any field shape. What change can enforce that expectation at write time?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
FOLLOWS. A recommendation needs distinct two-step endpoints excluding Eli and people Eli already follows. What result remains?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Resolve competing modeling and failure requirements10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
A-[:DEPENDS_ON]->B when A depends on B. What Cypher relationship pattern follows one to four downstream dependencies while preserving that meaning?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Transfer the rules to new workloads10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
quantity to be numeric. With default validation enforcement, an update attempts to replace it with "several". What should happen?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
deviceIds as text arrays. Investigators need to traverse from an account through a shared device to other accounts, but a few devices have millions of users. What redesign supports that query while addressing its main expansion risk?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Access pattern
ACID consistency
Aggregate
Anti-entropy repair
AP behavior
Asynchronous replication
Atomic counter
Atomicity
B
BSON
Bucketing
C
Cache invalidation
Cache-aside
CAP availability
CAP theorem
Cardinality
Causal consistency
Change data capture
Clustering column
Collection
Columnar database
Consistency model
Consistent hashing
Consistent prefix
CP behavior
Cypher
D
Denormalization
Document
Dual write
E
Embedding
Eventual consistency
F
Failover
H
Hash
Hash partitioning
Hinted handoff
Historical snapshot
Hotspot
I
Idempotent consumer
Index-free adjacency
J
JSON
K
Key-value store
L
Last-write-wins
Latency
Leaderless replication
Linearizability
M
Monotonic reads
Multi-model database
N
Network partition
Node
NoSQL
O
Object-relational impedance mismatch
P
PACELC
Partition key
Pattern matching
Polyglot persistence
Property graph
Q
Quorum
R
Range partitioning
RDF
Read repair
Read-your-writes
Referencing
Region
Relational model
Relationship
Replication
Replication factor
Replication lag
S
Scatter-gather
Schema validation
Schema-on-read
Schema-on-write
Secondary index
Semi-structured data
Shard key
Sharding
Shortest path
Single-leader replication
Sorted set
Split brain
Structured data
Subset pattern
Supernode
Synchronous replication
System of record
T
Time to live
Transactional outbox
Traversal
U
Unstructured data
Upsert
V
Variable-length path
W
Wide-column store
Workload
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.