NoSQL Data Models

NoSQL and Non-Relational Data Models

Compare document, key-value, wide-column and graph databases with the relational model you already know, and learn to choose a data model for a given workload. Design documents and decide what to embed, use keys and expiry times, build query-first tables with partition keys, and query connected data with graph patterns. Then see how replication and sharding spread data across servers, what the CAP theorem and quorum settings mean for consistency, and how one application can combine several databases.

IntermediateLesson 8 of 8 in Database Design and Advanced SQL Course

What you will learn

  1. 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 families
      Define 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 patterns
      Classify 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.
  2. 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 documents
      Build 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 reference
      Choose 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 store
      Design keys, choose value types, set expiry times and recognize workloads such as caching, sessions and counters that suit lookups by key.
  3. 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 queries
      Use 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 graph
      Model 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 matching
      Read and write Cypher patterns that match nodes, follow relationships and limit traversal depth, and compare them with the SQL needed for the same question.
  4. 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 nodes
      Explain 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 nodes
      Split 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.
  5. Distinguish consistency models, apply the CAP theorem and its latency extension correctly, and tune quorum reads and writes for a workload.
    • Distinguish consistency models
      Define 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 theorem
      State 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 writes
      Use 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.
  6. 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 model
      Compare 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 architecture
      Assign 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.

NoSQL Data Models study guide

6 chapters

1

Explain 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.

ModelMain unitTypical way to retrieve related data
RelationalRowJoin tables through keys
DocumentNested documentRead an aggregate or filter by a field
Key-valueValue under a unique keySupply the key
Wide-columnKeyed rows with varying columnsRead rows by shared or neighboring keys
GraphNodes and typed relationshipsFollow 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.
2

Model 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; _id uniquely 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 factorFavors embeddingFavors referencing
OwnershipChild belongs to one parentRecord is shared
ReadsData is usually read togetherRecords are queried independently
UpdatesChanges belong in one atomic unitRelated data changes independently
GrowthA small bounded groupA 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.
3

Model 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.
  • DISTINCT removes 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.
  • MERGE reuses an existing matching pattern; concurrent uniqueness needs a constraint.
4

Distribute 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 modeWhen the client hears successMain consequence
SynchronousAfter the required follower confirmsExtra waiting; an acknowledged copy survives leader loss
AsynchronousBefore followers need to confirmFaster 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.

PlacementHelpsMain risk or cost
RangeNeighboring-key range readsConcentrated writes to a growing end range
HashSpreading many distinct keysRange 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.
5

Reason 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
GuaranteeWhat it protects
Read-your-writesA client sees its own earlier changes
Monotonic readsA client's reads do not move backward after seeing newer data
Causal consistencyReaders see dependent operations in their cause-before-effect order
Consistent prefixA 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:

R+W>N

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:

⌊N/2⌋+1

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.
6

Choose 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
  1. List the main reads and writes, known keys, filters, ordering, frequency, and latency targets.
  2. Describe record shape, ownership, and relationships.
  3. Estimate volume, growth, and request rates.
  4. State freshness, atomicity, transaction, and constraint needs.
  5. Identify predictable queries and ad hoc questions.
  6. 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
ModelParticularly useful when the workload needs
RelationalMulti-row transactions, constraints, joins, and changing reports
DocumentWhole records with nested or varying attributes
Key-valueLow-latency retrieval and updates by known keys
Wide-columnHeavy writes and keyed time-range reads across nodes
GraphMulti-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

6 Walkthroughs

1

Choose a useful shape for application data

10 steps
Compare storage models, then turn a page requirement into access patterns.
  1. 1
    IntroductionStart 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.

  2. 2
    ExplanationCompare 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.

  3. 3
    ExampleKeep 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.

  4. 4
    ChallengeRead 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.

  5. 5
    Key InsightFind the schema in the reader

    Suppose one profile has an address and another has none. A reader that blindly accesses address.city can 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.

  6. 6
    ExplanationDescribe 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.

  7. 7
    ExampleRead a nested record

    Consider {"name": "Mina", "skills": ["SQL", "Java"], "address": {"city": "Dakar"}}.

    The outer braces contain an object. skills contains an array of strings, and address contains 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.

  8. 8
    ChallengeChoose 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.

  9. 9
    ChallengeRecheck 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.

  10. 10
    RecapUse 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.

2

Build a bounded document and a session lookup

14 steps
Design an order document, separate growing related data, and use keys with expiration.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDesign a record that stays useful
  2. 2
    ExampleRepresent an order as nested items
  3. 3
    ExampleChange the status without replacing the items
  4. 4
    ChallengeFind the boundary of the guarantee
  5. 5
    ExplanationKeep bounded owned data inside
  6. 6
    ExampleSeparate history from the first-page preview
  7. 7
    ChallengeKeep the meaning of a copied price
  8. 8
    TipLeave room inside the size limit
  9. 9
    ExampleConstruct a key the request knows
  10. 10
    ExplanationUpdate a cart field directly
  11. 11
    ExampleFollow a cache miss
  12. 12
    ChallengePredict a lookup after expiry
  13. 13
    ChallengeSeparate durable facts from temporary copies
  14. 14
    RecapCheck one read and one change
3

Lay out an event table and trace a graph query

16 steps
Build a query-first key, then model and traverse connected entities.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionUse the structure the query needs
  2. 2
    ExplanationName the lookup before the key
  3. 3
    ExampleRead the CQL key layout
  4. 4
    ExampleEstimate a bucket’s growth
  5. 5
    ChallengePreserve two simultaneous events
  6. 6
    ExplanationTurn connections into graph structure
  7. 7
    ExampleGive a rich purchase its own identity
  8. 8
    ChallengeRespect the stored direction
  9. 9
    TipWatch the node with many connections
  10. 10
    ExampleStart a two-step pattern
  11. 11
    ExampleList the endpoints before filtering
  12. 12
    ChallengeReturn one suitable recommendation
  13. 13
    ExplanationBound a variable path
  14. 14
    ConnectionFind where an index still helps
  15. 15
    ChallengeMatch a model to the changed query
  16. 16
    RecapTrace keys and paths separately
4

Follow copies and choose shard placement

11 steps
Predict stale reads and failover, then route records across shards.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate copies from ownership
  2. 2
    ExplanationFollow the acknowledgment
  3. 3
    ExamplePlace a read inside the lag
  4. 4
    ChallengeDecide what one isolated voter can do
  5. 5
    Key InsightKeep a recovery copy from before the mistake
  6. 6
    ExampleRoute one customer’s orders
  7. 7
    ExplanationCompare two timestamp placements
  8. 8
    ExampleMove only the added share
  9. 9
    ChallengeFind the remaining hotspot
  10. 10
    ChallengeCombine the two kinds of distribution
  11. 11
    RecapCheck routing, load, and recovery
5

Test consistency against a read timeline

17 steps
Distinguish guarantees, reason through a partition, and calculate quorum behavior.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what the client can observe
  2. 2
    ExampleMark when the write finishes
  3. 3
    ExplanationProtect one client’s session
  4. 4
    ConnectionKeep cause before effect
  5. 5
    ChallengeFind the race after a current read
  6. 6
    ExampleSplit the communication link
  7. 7
    ChallengeDecide what the business can reconcile
  8. 8
    Key InsightCount the normal coordination delay
  9. 9
    ExplanationDefine the three counts
  10. 10
    ExampleShow a guaranteed intersection
  11. 11
    ExampleSubtract the replicas still needed
  12. 12
    ChallengeCombine overlap with a failure target
  13. 13
    ExplanationRepair a copy and resolve a conflict
  14. 14
    ExampleTest an unfinished write
  15. 15
    TipDistinguish a legal overlap in time
  16. 16
    ChallengeChoose the mechanism for a unique claim
  17. 17
    RecapAudit a guarantee in three passes
6

Choose stores and deliver changes safely

10 steps
Use workload evidence, then follow an order event into a derived view.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the choice explainable
  2. 2
    ExampleMeasure the dominant operation
  3. 3
    ExplanationMatch the correctness requirement too
  4. 4
    ChallengeReconsider a proposed graph
  5. 5
    ExplanationName the original and the view
  6. 6
    ExampleCommit the event with the purchase
  7. 7
    ChallengeRetry without counting twice
  8. 8
    TipKeep older changes from winning
  9. 9
    ChallengeRecover a failed search update
  10. 10
    RecapWrite the operational decision

NoSQL Data Models practice questions

50 Practice Questions in 5 sets

Set 1: Recognize models and follow basic operations10 Practice Questions

Question 1 of 10

A Redis key is saved with EX 240. There are no later changes. What is its configured lifetime?
  1. 240 milliseconds.
  2. 240 minutes.
  3. 240 seconds.
  4. 240 hours.
Show answerHide answer
Answer: C
The Redis 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

A Cassandra table declares PRIMARY KEY ((machine_id, month), event_time). What forms the partition key?
  1. machine_id by itself.
  2. machine_id and month together.
  3. event_time by itself.
  4. month and event_time together.
Show answerHide answer
Answer: B
The inner parentheses group machine ID and month as the composite partition key. The event time is a clustering column that orders and distinguishes rows inside the selected partition. Using the first column alone ignores the explicit grouping and would describe a different table layout.

Question 3 of 10

A database retrieves opaque records only when given their unique lookup keys. What data model does this describe?
  1. A relational model.
  2. A key-value model.
  3. A document model.
  4. A property-graph model.
Show answerHide answer
Answer: B
The request supplies a key and retrieves its value, which is the defining access route of a key-value store. The value may contain serialized fields, but that does not create field queries. A document model normally lets queries inspect named fields inside records.

Question 4 of 10

A JSON collection allows each equipment record to contain different named attributes. How is that data classified?
  1. Unstructured data.
  2. Fixed-schema structured data.
  3. A relational schema.
  4. Semi-structured data.
Show answerHide answer
Answer: D
The field names give the records an identifiable structure, while their fields can vary, so the data is semi-structured. Unstructured data does not expose this kind of field-by-field record layout. Variable fields do not erase the structure already present in JSON objects.

Question 5 of 10

An update selects one MongoDB invoice by its identifier and uses $set to change only its status. What happens to its embedded line items?
  1. They remain intact within the same document.
  2. They are removed unless included in the update.
  3. They are copied into a separate collection.
  4. They change only after a second document write.
Show answerHide answer
Answer: A
$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

A graph contains Rui-[:SUPERVISES]->Sara and no reverse relationship. What fact does that edge record?
  1. Sara supervises Rui, with no reciprocal fact recorded.
  2. Rui supervises Sara, with no reciprocal fact recorded.
  3. Rui and Sara each supervise the other person.
  4. Rui and Sara share a supervisor represented by the edge.
Show answerHide answer
Answer: B
The arrow records the direction of the supervision relationship from Rui to Sara. Traversing that stored edge backward in a query would still leave its meaning unchanged. A reciprocal relationship would require its own recorded connection; it cannot be inferred from this one edge.

Question 7 of 10

A primary confirms a profile update at 0 ms. A follower receives it at 600 ms. A read at 250 ms reaches that follower. Why can it return the old profile?
  1. The confirmed write necessarily failed at the primary.
  2. A follower can never read a value written by a primary.
  3. The update must change every shard before any read runs.
  4. The follower is still behind because of replication lag.
Show answerHide answer
Answer: D
The read occurs before the follower receives the update, so replication lag explains the old value. Confirmation at the primary does not make every asynchronous copy immediately current. The old response alone therefore does not show that the original write failed.

Question 8 of 10

A user reads version 12 of another user’s record, then reads version 10 after switching replicas. What session guarantee would forbid this sequence?
  1. Monotonic reads.
  2. Read-your-writes.
  3. Eventual consistency.
  4. ACID durability.
Show answerHide answer
Answer: A
Monotonic reads prevents a session from moving backward after it has observed a newer version. Read-your-writes protects the client’s own earlier changes, but this client has only read someone else’s record. Eventual convergence alone does not stop temporary backward reads while replicas differ.

Question 9 of 10

A non-failing replica refuses a request during a network partition because it cannot safely coordinate the operation. What CAP guarantee is being given up for that request?
  1. Consistency with completed operations.
  2. Tolerance of lost network communication.
  3. Availability at every non-failing node.
  4. Durability of already stored records.
Show answerHide answer
Answer: C
CAP availability requires a non-error response to every request at a non-failing node. Refusing the unsafe operation sacrifices that guarantee to preserve consistency. This does not mean the database has lost its stored data or that all other clients must also be unable to work.

Question 10 of 10

A fleet has 1,800 trackers reporting every 6 seconds. Its dominant read is one tracker’s history for one day; events are time ordered and the history grows continually. What initial storage layout best fits these requirements?
  1. Deduplicate event IDs and apply distinct events in arrival order.
  2. Publish each event once without retry after uncertain sends.
  3. Retry each event and repeat its increment on every delivery.
  4. Wide-column; 300 writes/s; partition by tracker and day.
Show answerHide answer
Answer: D
The fleet produces 1,800 divided by 6, or 300 writes per second. A tracker-day partition bounds growth and matches the daily keyed history, with time ordering inside it. A tracker-only partition misses the growth boundary, while one shared daily value concentrates unrelated trackers’ writes.
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

A graph has only outgoing 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?
  1. Xia twice.
  2. Vik and Wen once each.
  3. Uma and Xia once each.
  4. Xia once.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A support page fetches one case by ID, the newest 12 notes, and the current owner’s name. The owner’s name is copied into every case. What extra work follows a rename?
  1. Update only the central owner and expect copies to change.
  2. Reassign case identifiers so the old names become current.
  3. Update affected copies or accept temporarily stale names.
  4. Normalize the note timestamps to preserve the copied names.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A team record owns four emergency contacts that are always read with the team and remain limited to four. What document boundary fits this access pattern?
  1. Embed the four contacts inside the team document.
  2. Reference each contact solely to avoid any nested fields.
  3. Embed every team’s contacts in one shared root document.
  4. Store each contact only inside an expiring cache entry.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A ranking must keep participants unique and order them by numeric points as scores change. What Redis structure fits?
  1. A Redis list.
  2. An ordinary set.
  3. A plain string.
  4. A sorted set.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A table uses (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?
  1. Add a timestamp index within each probe-day partition.
  2. Add a greenhouse-day table and maintain both layouts.
  3. Change only the clustering order of the probe-day table.
  4. Replace the probe-day table with a greenhouse-day table.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Orders are hash-sharded by customer ID. A report totals yesterday’s orders for every customer. Why can the report need several shards?
  1. Hashing puts every order from a date on the same shard.
  2. Replication removes all customer-based query routing.
  3. Its date filter does not identify one customer shard.
  4. A customer key guarantees locality for every order report.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

After writes stop, replicas eventually agree, but readers can temporarily see different versions. What consistency model is described?
  1. Eventual consistency.
  2. Linearizability.
  3. Read-your-writes.
  4. Monotonic reads.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An item has six responsible replicas. A write waits for four acknowledgments. What is the smallest read response count that guarantees strict read/write overlap?
  1. 2 replicas.
  2. 3 replicas.
  3. 4 replicas.
  4. 5 replicas.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A team already meets its query targets with relational tables. New catalog records need optional type-specific attributes, but no new path queries. What should it evaluate before adding another engine?
  1. A JSON column in the existing relational database.
  2. A graph engine solely because products have categories.
  3. A key-value cache as the only permanent catalog copy.
  4. A separate wide-column engine for every product type.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An order and its outbox event commit together. Publication succeeds, but the publisher crashes before recording that success. It sends the event again after restart. How should the derived-store consumer preserve the intended result?
  1. Apply every delivery as a new increment and keep its arrival order.
  2. Delete the authoritative order whenever a retry is detected.
  3. Deduplicate the event ID and preserve each record’s order.
  4. Disable retries and assume the first send always reached the consumer.
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

An application expects every document to contain a numeric capacity, but the database currently accepts any field shape. What change can enforce that expectation at write time?
  1. Keep accepting records and call the collection schemaless.
  2. Change the JSON field name for every capacity value.
  3. Copy each invalid record into another unvalidated collection.
  4. Add a validator requiring a numeric capacity field.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two invoice documents must change together, or neither change may take effect. What MongoDB mechanism covers that requirement?
  1. A multi-document transaction.
  2. Two separate document writes.
  3. An index on invoice status.
  4. A collection with no validator.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A service embeds an ever-growing repair history and the current shared supplier details in each asset document. Its page needs only the newest five repairs and always-current supplier data. What redesign addresses both problems?
  1. Separate repairs but embed current supplier details in every asset.
  2. Separate repairs, keep a bounded preview, and reference suppliers.
  3. Reference suppliers but retain every repair in the asset document.
  4. Keep only five repairs and discard the complete older repair history.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A graph must connect customers to purchases, each purchase to several products, and a refund to the purchase. What is a useful representation of a purchase?
  1. A customer’s text property containing every purchased product.
  2. A single customer-product edge with no purchase identity.
  3. An Order node linked to its customer, products, and refund.
  4. An isolated product label repeated for every purchase date.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A graph has edges Eli→Fay, Eli→Gus, Fay→Hao, Fay→Gus, Gus→Hao, and Gus→Eli, all FOLLOWS. A recommendation needs distinct two-step endpoints excluding Eli and people Eli already follows. What result remains?
  1. Hao once.
  2. Hao and Gus once each.
  3. Hao twice.
  4. Eli and Hao once each.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A database’s bottleneck is writes handled by one leader. The team adds asynchronous read replicas without changing the write path. What direct benefit should it expect?
  1. More independent write capacity, with each replica accepting writes.
  2. Immediate removal of lag, with every follower always current.
  3. More read capacity, with the leader still handling every write.
  4. Historical recovery, with replicas preserving deleted records.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A table is range-sharded by an ever-increasing event timestamp. Where do newly arriving events concentrate?
  1. Evenly across all existing timestamp ranges.
  2. Only on shards containing the oldest events.
  3. On a random shard independent of the timestamp.
  4. On the shard holding the newest timestamp range.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two disconnected regions sell access to one remaining berth. A plan keeps both regions writable using their local count, then resolves conflicts by timestamp. What guarantee fails, and what response protects the unique allocation?
  1. Consistent allocation fails; accept local claims and keep the latest write.
  2. Consistent allocation fails; refuse claims lacking safe coordination.
  3. No guarantee fails; replicate both claims after the link recovers.
  4. Availability fails; let both regions allocate from local counts.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An item has eight responsible replicas, waits for six write acknowledgments, and needs three read responses. With three replicas unreachable, what can complete?
  1. Both reads and writes can complete.
  2. Reads can complete, but writes cannot.
  3. Writes can complete, but reads cannot.
  4. Neither reads nor writes can complete.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Three services each own a separate database, and all three use the same relational database technology. Does service ownership alone make this polyglot persistence?
  1. Yes; separate ownership alone defines polyglot persistence.
  2. No; separate services can never choose their own storage models.
  3. Yes; any database replica counts as a different model.
  4. No; polyglot persistence combines different database kinds.
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

A teammate claims that a database cannot be NoSQL if it supports multi-record ACID transactions. What is the correction?
  1. NoSQL requires every write to bypass database constraints.
  2. NoSQL describes the main model, not a ban on transactions.
  3. Supporting transactions always changes documents into tables.
  4. A database family is determined only by its query syntax.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Each training attendee joins about four workshops; a workshop can have thousands of attendees. Workshop titles change centrally. The app opens an attendee’s workshop list and searches attendees by workshop. What document design best limits duplication and array growth?
  1. Embed current workshop records inside each attendee document.
  2. Keep attendee-ID arrays inside each workshop as the sole link store.
  3. Keep workshop records and indexed workshop-ID arrays on attendees.
  4. Embed attendee records and current titles in every workshop document.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two clients read a shared counter as 18 and each writes back 19. What operation would preserve both intended increments?
  1. Two atomic increments, producing 20.
  2. Two replacement writes of 19, producing 20.
  3. One expiry change, producing 19.
  4. Two fresh reads without updates, producing 20.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Each station records two channels every 30 seconds. The channels can share a timestamp, and each row is estimated at 80 bytes. Reads ask for one station-day. What design and daily payload estimate preserve all readings?
  1. Partition station/day; cluster time only; 230,400 bytes.
  2. Partition station only; cluster day/time; 460,800 bytes.
  3. Partition day/channel; cluster time only; 230,400 bytes.
  4. Partition station/day; cluster time/channel; 460,800 bytes.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A dependency graph stores A-[:DEPENDS_ON]->B when A depends on B. What Cypher relationship pattern follows one to four downstream dependencies while preserving that meaning?
  1. <-[:DEPENDS_ON*1..4]-
  2. -[:DEPENDS_ON*1..4]-
  3. -[:DEPENDS_ON*4..4]->
  4. -[:DEPENDS_ON*1..4]->
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A three-voter single-leader system confirms writes asynchronously. The primary acknowledges an update that neither follower receives, then becomes isolated. The connected followers elect a primary. What must the application account for?
  1. Both sides retain authority; the acknowledged update exists on both.
  2. The old primary loses authority; the new primary can lack the update.
  3. The old primary keeps authority; the pair cannot hold a majority.
  4. The pair gains authority; client acknowledgment proves it has the update.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A system provides linearizable individual reads and writes. Two clients each read the same available license count of 1, then each writes a separate accepted allocation. Why can this history still overallocate, and what change protects the count?
  1. The check/write can race; use an atomic conditional allocation.
  2. The reads must overlap; add a second read before each allocation.
  3. The write order is missing; serialize only the final writes.
  4. The values need copies; wait for all replicas on each read and write.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

With N=3 and W=R=2, a write reaches only A before failing. No repair or further write occurs. One read asks A and B; after it finishes, a second asks B and C. What result sequence can occur, and is it linearizable?
  1. Old then old; a failed write cannot be observed by any read.
  2. New then new; the first quorum read necessarily updates C.
  3. New then old; overlap alone does not ensure linearizability.
  4. New then old; a failed write makes backward reads linearizable.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A service repeatedly explores shared-device connections between accounts at several depths. Simple account lookups already work well in its relational database. What requirement could justify a graph store?
  1. The unique identifiers in account records.
  2. The repeated multi-step connection searches.
  3. The ability of relational tables to model links.
  4. The numeric login count on each account.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An outbox consumer skips repeated event IDs. For one order, status version 6 is applied before delayed version 5, and the consumer then replaces the status with version 5. What safeguard is missing?
  1. Preserve record order or reject obsolete versions.
  2. Deduplicate event IDs again before every status write.
  3. Replace the outbox with two sequential application writes.
  4. Choose the last event to arrive regardless of record version.
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

A system copied current reviewer names into case previews to speed frequent reads. Reads now rarely open previews, names change often, and new ad hoc reports join cases to reviewers. What design direction best matches the changed workload?
  1. Favor normalized reviewer references and indexed report joins.
  2. Keep name copies and build another copied layout for every new report.
  3. Embed reviewers and their complete case lists to avoid report joins.
  4. Use keyed case previews and implement cross-reviewer reports as key scans.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A collection validator requires quantity to be numeric. With default validation enforcement, an update attempts to replace it with "several". What should happen?
  1. The text is converted to an arbitrary numeric estimate.
  2. The validator is removed for that document automatically.
  3. The document is accepted because all JSON values are legal.
  4. The update is rejected for violating the validator.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A ticket document keeps the seat and price paid, plus a copy of the venue’s current support number. The page must display today’s support number and the original purchase price. The venue edits both its support number and current prices. How should these fields be handled?
  1. Refresh the paid price and support number to today’s values.
  2. Preserve the paid price; reference or refresh the support number.
  3. Preserve both copied fields permanently as purchase history.
  4. Reference today’s price while preserving the old support number.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Message IDs are unique only within a channel, and a channel can receive messages indefinitely. Reads request a channel’s messages for one day, newest first; timestamps can repeat. What Cassandra key best serves the read and preserves each message?
  1. Partition (channel_id, day); cluster by time alone.
  2. Partition day; cluster by channel and message ID alone.
  3. Partition (channel_id, day); cluster by time and message ID.
  4. Partition channel_id; cluster by message ID and time.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A fraud graph stores accounts with 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?
  1. Create device nodes and typed links; filter and bound traversal.
  2. Create device nodes and typed links; rely on shallow depth alone for cost.
  3. Create account-to-account links, omitting device identity from the model.
  4. Create device nodes; keep connections only in account ID-list properties.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A timestamp-range shard receives nearly all new telemetry writes. The common read is one unit’s events during a selected hour. There are many units with similar traffic. What placement change addresses the hotspot while keeping that read local?
  1. Hash each event independently and gather each hourly read.
  2. Keep timestamp ranges and split the newest range more finely.
  3. Hash a unit-hour key so each bounded group stays together.
  4. Hash the hour only so all units for that hour share one group.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What does PACELC compare with consistency when no network partition is occurring?
  1. Replication factor.
  2. Schema validation.
  3. Backup retention.
  4. Latency.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An item has nine strict replicas. Reads must still work with six replicas unreachable; writes must still work with two unreachable. What R and W satisfy those limits and guarantee read/write overlap?
  1. R=2,W=7
  2. R=3,W=7
  3. R=4,W=6
  4. R=3,W=6
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two clients concurrently replace the same cart field on different replicas with different additions. The system uses last-write-wins per field and later all replicas agree. Why can an addition still be missing, and what change can retain both concurrent versions for merging?
  1. Replication delay hides one version; wait for convergence without changing the rule.
  2. Timestamp selection discards one version; add read repair without changing that rule.
  3. Timestamp selection discards one version; detect concurrency and merge.
  4. Timestamp selection discards one version; keep the greatest timestamp again.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A relational store owns accepted subscriptions. A search index may lag by a minute and must be rebuildable. Notifications can be delivered repeatedly or out of order. What design gives the index a safe recovery path?
  1. Publish committed changes; deduplicate IDs and apply distinct events in arrival order.
  2. Publish each change once; keep record order but omit retries after uncertain sends.
  3. Replay committed changes in record order; repeat every delivery’s increment.
  4. Publish committed changes; deduplicate and apply record versions in order.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

92 Key Terms, each with its definition

A

Access pattern
An access pattern is a specific application read or write, described by its lookup, filters, ordering, frequency, and latency.
The access pattern requests one member’s latest 15 messages, newest first, on every page load.
ACID consistency
ACID consistency means a transaction preserves database validity rules, including declared constraints and business invariants.
ACID consistency requires a committed transfer to preserve the database’s balance rules.
Aggregate
An aggregate is related data that an application treats as one unit for reading and writing, such as an order and its items.
The checkout page retrieves the order aggregate with its line items and delivery address in one read.
Anti-entropy repair
Anti-entropy repair compares replica datasets and transfers missing or outdated data to restore agreement between copies.
Anti-entropy repair uses comparisons of replica data to find differences missed by ordinary traffic.
AP behavior
AP behavior maintains availability during a partition by answering locally, permitting stale or conflicting results to be reconciled.
AP behavior can accept cart additions in both disconnected regions and merge them later.
Asynchronous replication
Asynchronous replication allows a write acknowledgment before followers confirm it, leaving a possible gap during failure.
Asynchronous replication can lose a recent acknowledged change if the promoted follower never received it.
Atomic counter
An atomic counter changes a numeric count as one indivisible operation so concurrent increments are not lost.
An atomic counter records both page views even when two requests arrive at the same moment.
Atomicity
Atomicity is the guarantee that an operation’s changes within its protected boundary all take effect together or none do.
Single-document atomicity keeps an order status and its embedded status details from changing halfway.

B

BSON
BSON is MongoDB’s binary document format, adding types such as dates, 64-bit integers, and decimals to JSON-like data.
An application saves a measurement timestamp as a date value supported by BSON.
Bucketing
Bucketing divides growing data into bounded groups, often by adding a day or month to an entity’s partition key.
Daily bucketing stops a machine’s lifetime event history accumulating in one partition.

C

Cache invalidation
Cache invalidation removes or replaces a cached copy after its source changes so readers can obtain current information.
A price update triggers cache invalidation for that product’s previously cached record.
Cache-aside
Cache-aside is a pattern in which the application checks a cache and loads missing values from the authoritative database.
With cache-aside, an expired product entry is fetched again from the catalog database on the next read.
CAP availability
CAP availability requires every request received by a non-failing node eventually to receive a non-error response.
Refusing writes on an isolated node gives up CAP availability even if most users can still transact.
CAP theorem
The CAP theorem states that during a network partition a distributed system cannot guarantee both linearizability and availability.
The CAP theorem explains why a seller’s node cut off by a network partition must refuse some requests or risk inconsistent sales.
Cardinality
Cardinality describes how many related records can occur on each side of a relationship, such as one-to-few or many-to-many.
The growing cardinality of post comments makes a permanently embedded full history unsuitable.
Causal consistency
Causal consistency preserves cause-before-effect order for dependent operations, while unrelated changes may be ordered differently.
Causal consistency keeps a reply from appearing before the question that caused it.
Change data capture
Change data capture reads committed changes from a database’s change log and delivers them to other systems or derived views.
Change data capture feeds accepted order changes into a graph without separate application dual writes.
Clustering column
A Cassandra clustering column orders rows within a partition and contributes to each row’s unique full primary key.
A timestamp clustering column puts the newest readings at the beginning of a sensor-day partition.
Collection
A collection groups documents in a document database, with records that can share a purpose while differing in fields.
The exhibits collection holds paintings with artists and fossils with estimated ages.
Columnar database
A columnar database stores columns separately to efficiently scan selected fields and aggregate many records in analytics.
A columnar database can total a few measures across a large warehouse without reading every field.
Consistency model
A consistency model specifies which values and ordering readers may observe while writes propagate through replicated data.
A consistency model determines whether a post-update read may legally return an older profile.
Consistent hashing
Consistent hashing assigns keys and node positions on a ring so adding capacity mainly transfers a new node’s share of keys.
Balanced consistent hashing moves about one fifth of keys when growing from four nodes to five.
Consistent prefix
Consistent prefix guarantees that a reader sees an initial segment of one agreed write order without gaps in that segment.
Consistent prefix allows events 1 and 2 to appear before event 3, but not event 3 without event 2.
CP behavior
CP behavior preserves consistency during a partition by refusing or delaying operations that cannot be safely coordinated.
CP behavior can stop a disconnected booking server from independently selling the last seat.
Cypher
Cypher is a graph query language that expresses node and relationship patterns to match, return, or change graph data.
A Cypher query follows outgoing FOLLOWS edges from one named person to their contacts.

D

Denormalization
Denormalization deliberately copies facts into multiple places so important reads require fewer lookups or joins.
Copying a display name into message previews is denormalization that creates work when the name changes.
Document
A document is a self-describing record of named fields that can include nested objects and arrays as well as simple values.
One order document holds its status, delivery address, and array of purchased items.
Dual write
A dual write sends one logical change to two stores separately, allowing only one to commit or updates to arrive in different orders.
A dual write can save an invoice while failing to update the search index that displays it.

E

Embedding
Embedding stores related data inside its parent document so a read or atomic write can handle the group together.
Embedding three delivery addresses in a profile keeps the small owned set beside the customer’s details.
Eventual consistency
Eventual consistency promises that replicas converge if new writes stop, without setting a fixed convergence deadline.
Eventual consistency allows two readers to see different like counts while replicas catch up.

F

Failover
Failover replaces an unavailable leader by promoting a follower, which may lack recent changes that had not reached it.
An application reconnects to the promoted follower after failover from a failed primary.

H

Hash
A Redis hash stores field-value pairs inside one key, allowing individual fields such as cart quantities to be changed.
A cart hash maps product codes to quantities so adding one item does not replace the entire cart.
Hash partitioning
Hash partitioning applies a hash to a key to choose its shard, spreading distinct keys without preserving original key order.
Hash partitioning scatters adjacent customer names, so an alphabetical range can involve several shards.
Hinted handoff
Hinted handoff retains a write intended for an unavailable replica and replays it after that replica becomes reachable.
Hinted handoff helps a returning replica receive updates it missed during a short outage.
Historical snapshot
A historical snapshot preserves values as they were at a particular event, so later changes do not rewrite that history.
The unit price in a completed order is a historical snapshot of what the buyer paid.
Hotspot
A hotspot is a key, partition, or server receiving a disproportionate share of traffic, creating a localized bottleneck.
A single popular post can remain a hotspot even when all other keys are evenly hashed.

I

Idempotent consumer
An idempotent consumer applies repeated delivery of the same event without producing an additional effect after the first application.
An idempotent consumer records event IDs so a retried purchase event does not increase a count twice.
Index-free adjacency
Index-free adjacency lets a native graph engine follow stored connections directly after it has found the start node.
With index-free adjacency, reaching a known person’s contacts follows that person’s stored relationships.

J

JSON
JSON is a text data format that represents named fields, arrays, and nested objects using a small set of value types.
A JSON event includes a device identifier, a numeric reading, and an array of warning codes.

K

Key-value store
A key-value store maps unique keys to values and supports direct operations by key, without searching inside plain values.
A key-value store retrieves a session from the token supplied with the user’s next request.

L

Last-write-wins
Last-write-wins resolves a conflict by retaining the value with the latest timestamp, potentially discarding concurrent updates.
Last-write-wins can keep one of two simultaneous cart changes while losing the other change.
Latency
Latency is the time an operation takes to respond, measured against the application’s requirement for that read or write.
A session lookup’s latency target affects whether an extra database round trip is acceptable.
Leaderless replication
Leaderless replication sends reads and writes to several replicas without one permanent leader, using response counts and repair.
Leaderless replication can wait for two write acknowledgments from the three replicas holding an item.
Linearizability
Linearizability makes operations behave as if they use one copy in real-time order, respecting completed writes in later reads.
Linearizability forbids a read begun after a completed update from returning a superseded value.

M

Monotonic reads
Monotonic reads is a session guarantee that later reads do not return older versions after the client has observed a newer one.
Monotonic reads prevents a device from showing version 9 and then version 7 after replica switching.
Multi-model database
A multi-model database supports several data representations in one engine, reducing the need to operate separate specialized stores.
A multi-model database can combine relational records and JSON attributes in one managed system.

N

Network partition
A network partition is a communication failure that prevents groups of nodes from exchanging messages while they may still run.
During a network partition, two data centers can each receive requests but cannot coordinate them.
Node
A node is an entity in a graph, such as a person, product, or order, that can have labels, properties, and relationships.
An Order node connects one customer to the several products bought in the same purchase.
NoSQL
NoSQL is a broad name for databases whose main storage model is non-relational, including document and graph models.
A team comparing NoSQL choices must still specify its query, transaction, and scale requirements.

O

Object-relational impedance mismatch
The object-relational impedance mismatch is the structural gap between application objects and normalized relational tables.
Mapping a nested profile into user, job, and phone tables exposes the object-relational impedance mismatch.

P

PACELC
PACELC describes availability versus consistency during partitions and latency versus consistency during normal communication.
PACELC highlights the normal delay introduced by waiting for replicas in a distant region.
Partition key
A Cassandra partition key groups rows into one partition and is hashed to select the replica nodes storing that group.
The sensor ID and day form a partition key that keeps one sensor’s daily readings together.
Pattern matching
Pattern matching finds nodes and relationships whose labels, properties, types, and directions fit a query’s structure.
Two-step pattern matching can reach the same endpoint through several intermediate people.
Polyglot persistence
Polyglot persistence uses several kinds of databases within one application, matching each to a particular storage or query need.
An app using relational orders and a recommendation graph practices polyglot persistence.
Property graph
A property graph represents entities as labeled nodes joined by typed, directed relationships, with properties on either.
A property graph links accounts to devices and records when each account used a device.

Q

Quorum
A quorum is a majority of an item’s replicas, requiring more than half to respond for the corresponding operation.
With seven replicas, a quorum needs four replies, leaving at most three replicas outside the majority.

R

Range partitioning
Range partitioning assigns continuous intervals of key values to shards, preserving locality for neighboring-key queries.
Range partitioning on increasing timestamps directs current writes to the newest interval.
RDF
RDF is a graph data model that represents facts as subject–predicate–object triples and is commonly queried with SPARQL.
An RDF dataset can express a person following another person as one subject–predicate–object fact.
Read repair
Read repair brings stale replicas up to date after a read discovers differences between the versions they hold.
Read repair copies a newer field value to a replica that returned an older value during a read.
Read-your-writes
Read-your-writes is a session guarantee that a client’s later reads reflect its own previous writes, even with replication.
Read-your-writes lets a user see their newly saved address when they reopen the profile.
Referencing
Referencing stores another record’s identifier to connect documents without copying all of the related record’s fields.
Referencing a shared supplier lets many products point to the same independently maintained details.
Region
An HBase region is a table segment containing a continuous range of row keys, used to distribute its ordered rows.
As a table grows, an HBase region can split so different row-key ranges are served separately.
Relational model
The relational model organizes records in tables whose keys, constraints, and joins express and enforce relationships.
A payroll design uses the relational model to link each payment to one employee record.
Relationship
A relationship is a typed, directed connection between two graph nodes and can carry properties describing that connection.
A FOLLOWS relationship records its start year without implying that the other person follows back.
Replication
Replication maintains copies of the same data on several nodes to support availability, read traffic, and failure recovery.
Replication lets another server serve a record when one machine’s disk becomes unavailable.
Replication factor
The replication factor is the number of responsible replicas storing an item, commonly denoted by N in quorum calculations.
A replication factor of five gives an item five copies even when a write waits for only three replies.
Replication lag
Replication lag is the delay before a follower reflects a change already confirmed by the leader, allowing stale follower reads.
A profile reload during replication lag can show the old photo just after a successful update.

S

Scatter-gather
Scatter-gather sends work to multiple shards and combines their responses when one shard cannot answer the whole query.
A daily total across customer-keyed shards needs scatter-gather to combine all customers’ orders.
Schema validation
Schema validation checks declared rules about a document’s required fields, types, or values when it is inserted or updated.
Schema validation rejects an inventory document missing the product identifier required by its validator.
Schema-on-read
Schema-on-read is interpreting record structure in reading code, allowing stored records to differ in their fields.
Schema-on-read requires the profile reader to handle records that have no address field.
Schema-on-write
Schema-on-write is checking data against declared structure and type rules when it is stored, before readers use it.
Schema-on-write rejects a product whose required quantity field contains a text description.
Secondary index
A secondary index is a lookup structure on a field other than the main identifier that can speed matching-record queries.
A secondary index on customer ID supports finding orders without examining the full collection.
Semi-structured data
Semi-structured data carries field names or tags that identify its structure while allowing records to have different shapes.
JSON profiles with optional language and address fields are semi-structured data.
Shard key
A shard key is the record value or combination of values used to decide which logical shard owns that record.
A customer shard key routes a customer-history query directly, but not a date-wide report.
Sharding
Sharding divides a dataset into logical groups whose records are assigned by key and distributed across multiple servers.
Sharding orders by customer ID makes one customer’s history local to a logical shard.
Shortest path
A shortest path uses the fewest relationships among the paths connecting its endpoints in an unweighted graph search.
The shortest path between two people may have two steps even if a longer route also exists.
Single-leader replication
Single-leader replication routes writes through one leader that records changes and sends them to follower replicas.
In single-leader replication, adding followers can spread reads while the leader still handles writes.
Sorted set
A Redis sorted set holds unique members with numeric scores and maintains their order for ranked reads and updates.
A sorted set orders participants by points so the app can retrieve the top three immediately.
Split brain
Split brain occurs when multiple nodes act as leader and accept conflicting writes, often after they lose communication.
A majority-election rule helps prevent split brain when one member becomes isolated.
Structured data
Structured data follows a fixed set of named, typed fields, making its records fit a declared tabular layout.
A shipment table with typed dates and masses in kilograms holds structured data for reports.
Subset pattern
The subset pattern embeds a bounded selection of related data while keeping the complete set separately for other reads.
A product page uses the subset pattern to display five recent reviews without loading its full history.
Supernode
A supernode is a graph node with an unusually large number of relationships, which can make traversals expand sharply.
A popular device used by many accounts becomes a supernode in a graph that links accounts to the devices they use.
Synchronous replication
Synchronous replication requires a designated replica acknowledgment before the client is told that a write succeeded.
Synchronous replication adds waiting when a required follower is far from the leader.
System of record
A system of record is the authoritative store for a fact, providing the basis for rebuilding or correcting derived copies.
The order database is the system of record when a recommendation graph disagrees about a purchase.

T

Time to live
A time to live is the duration before a key automatically expires, commonly used for sessions, codes, and cached results.
A one-time login code has a time to live of 120 seconds so it disappears without manual cleanup.
Transactional outbox
A transactional outbox saves a business change and an event in one local transaction, then publishes the committed event separately.
A transactional outbox retains the order event so the publisher can retry after a connection failure.
Traversal
A traversal follows relationships from node to node to find connected entities or paths matching a graph question.
A fraud traversal follows account-to-device links to find accounts sharing equipment.

U

Unstructured data
Unstructured data lacks a record layout that a database can query field by field, as with images, audio, or free text.
An uploaded recording is unstructured data even if its duration is stored in a separate table.
Upsert
An upsert inserts data if its key is absent and updates supplied values if the key already identifies an existing record.
A second upsert using the same event key changes that event’s value instead of adding another row.

V

Variable-length path
A variable-length path matches a repeated relationship over a range of depths, allowing several traversal lengths in one query.
A variable-length path limited to three steps searches a small neighborhood of the starting account.

W

Wide-column store
A wide-column store organizes keyed rows with varying populated columns and distributes them for large keyed workloads.
A wide-column store handles event histories whose main reads supply an entity key and time range.
Workload
A workload is the mix of operations, data size and growth, request rates, and correctness needs a database must support.
A workload of frequent token lookups and short-lived sessions fits direct keyed operations.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started