The previous two lessons were about files: large, immutable, designed to be read straight through and analysed. But a data platform also has to serve data to applications: when a customer opens their cart on NovaMarket's website, the response must arrive in milliseconds, and it must arrive just as quickly for the thousands of customers doing the same thing at that very moment. A Parquet file is no use for that.
Traditionally that role has been filled by the relational database. It still does the job very well in a great many cases, but when the volume, velocity or variety of the data grows (the Vs from lesson 01-01), situations arise in which it falls short. NoSQL databases were born for those. In this lesson you will see why they emerged, how they differ from relational databases, the four main types that exist and what each would be used for at NovaMarket. You will practise with two of them, MongoDB and Redis, and learn the design rule that sets them apart most: you model with the queries in mind.
Why NoSQL emerged
A relational database (PostgreSQL, MySQL, Oracle, SQL Server) stores data in tables with a fixed schema, related to one another, and is queried with SQL. The data from NovaMarket's shop — customers, products, orders, order_lines — is a perfect example.
Around 2005-2010, the big internet companies ran into three limits of that model:
- Scale. A classic relational database lives on a single server and grows vertically (a bigger server). Spreading its tables across many servers is hard, above all because joins and transactions need related data to be kept together.
- Schema rigidity. All the rows in a table have the same columns. If each product has different attributes (a television has inches; a coffee maker, pressure), the schema fills up with empty columns or auxiliary tables.
- Availability. For a global service that can never go down, depending on one primary server is a risk.
NoSQL databases were born to scale horizontally on a cluster, applying the partitioning and replication from lesson 01-04, in exchange for giving up part of what the relational model offered. Today the name is read as Not Only SQL: they are not a replacement, but a complement.
Relational versus NoSQL
| Aspect | Relational | NoSQL (in general) |
|---|---|---|
| Data model | Tables with rows and columns | Key-value, documents, wide columns or graphs |
| Schema | Fixed, defined before writing | Flexible; each record can have different fields |
| Query language | Standard SQL | Specific to each product |
| Relationships between data | Joins between tables | Avoided: related data is stored together |
| Scaling | Mostly vertical | Horizontal, designed for clusters |
| Transactions | ACID across several tables | Limited, normally to one record or partition |
| Consistency | Strong | Often eventual or configurable |
| Design | You model the data; the queries come later | You model from the queries |
| Query flexibility | Very high: any question | Low: very fast for the queries foreseen |
The differences are not absolute: many NoSQL databases now offer transactions and SQL-like languages, and distributed relational databases exist. But the table describes each family's starting point well.
ACID, BASE and the CAP theorem
ACID
Relational databases guarantee the ACID properties in their transactions (groups of operations that must be treated as one):
| Property | Meaning | Example at NovaMarket |
|---|---|---|
| Atomicity | All or nothing | Creating the order and deducting the stock: both things happen or neither does |
| Consistency | The data always complies with the rules defined | Stock never goes negative |
| Isolation | Simultaneous transactions do not interfere with one another | Two customers do not buy the last unit at the same time |
| Durability | What has been confirmed is not lost | A confirmed order survives a power cut |
BASE
Many NoSQL databases adopt a more relaxed approach, christened BASE as a play on words:
- Basically Available: the system always responds, even if a node fails.
- Soft state: the state may be changing while the replicas synchronise.
- Eventually consistent: if changes stop arriving, all the replicas end up agreeing. This is the eventual consistency from lesson 01-04.
The relationship with CAP
In lesson 01-04 you saw the CAP theorem with the example of a television's stock between Valencia and Madrid: when the network splits, you have to choose between consistency (rejecting operations so as not to give contradictory data) and availability (carrying on responding even if the replicas diverge). ACID and BASE are the two philosophies that result from that choice:
| Prioritises consistency (CP) | Prioritises availability (AP) | |
|---|---|---|
| Philosophy | Close to ACID | BASE |
| When the network partitions | The side left in the minority stops accepting writes | All nodes keep accepting; they reconcile afterwards |
| Typical examples | HBase; MongoDB in its usual configuration | Cassandra, DynamoDB |
| Suitable for | Stock, balances, data that cannot tolerate contradiction | Carts, events, counters, catalogues |
Two nuances so as not to oversimplify:
- The choice is often configurable. Cassandra lets you decide, on every operation, how many replicas must acknowledge a write or respond to a read: more replicas, more consistency and less availability.
- CAP only talks about behaviour during a network failure. In normal operation, the real trade-off is between consistency and latency: waiting for all the replicas to acknowledge is safer, but slower.
The four types of NoSQL database
"NoSQL" covers some very different families. What distinguishes them is their data model.
flowchart TB
N[NoSQL databases]
N --> KV[Key-value<br/>Redis, DynamoDB]
N --> DOC[Documents<br/>MongoDB, Couchbase]
N --> COL[Wide columns<br/>Cassandra, HBase]
N --> GR[Graphs<br/>Neo4j]
KV --> U1[Cart and session]
DOC --> U2[Product catalogue]
COL --> U3[Event history by customer]
GR --> U4[Recommendations: bought together]
Key-value
This is the simplest model: one enormous dictionary. A value is stored against a key, and it can only be retrieved by the key.
- Representative product: Redis, which keeps the data in RAM and responds in under a millisecond. It also offers structured values (lists, sets, hash tables). Others: Amazon DynamoDB, Memcached.
- Strengths: extreme speed, simplicity, automatic expiry of data.
- Limit: there are no queries by content. You cannot ask "which carts contain product 142?".
- At NovaMarket: the cart and session data. They are read and written constantly, always by a known key, and can expire by themselves if the customer leaves.
Documents
Each record is a document: an object with fields, similar to JSON, which can contain lists and other nested objects. Documents are grouped into collections, and two documents in the same collection need not have the same fields.
{
"_id": 13,
"name": "Headphones Kore 910",
"category": "audio",
"price": 105.48,
"attributes": {"bluetooth": true, "noise_cancelling": true, "battery_life_h": 30}
}- Representative product: MongoDB. Others: Couchbase, Amazon DocumentDB, Azure Cosmos DB.
- Strengths: flexible schema, queries on any field, indexes, aggregations. It is the NoSQL type most similar in use to a relational database.
- Limit: joins between collections exist but are limited; if the model is full of relationships, a relational one is a better fit.
- At NovaMarket: the product catalogue shown on the website. A television, a coffee maker and a rug have completely different attributes, and each product page is read whole in one go.
Wide columns
The data is organised into tables with rows, but designed to be spread across a cluster: each row belongs to a partition, determined by its partition key, and within the partition the rows are stored in order. Reading a whole partition is very fast; writing, even more so.
- Representative products: Apache Cassandra (no primary node, high availability, the SQL-like CQL language) and Apache HBase (built on HDFS, strong consistency). Others: ScyllaDB, Google Bigtable.
- Strengths: enormous volumes, continuous heavy writing, almost linear scaling as nodes are added.
- Limit: you can only query efficiently by the partition key. No joins or arbitrary queries.
- At NovaMarket: the event history by customer. 40 million events are written a day and the website needs "the latest events for customer 770" instantly, to personalise the page.
Do not confuse "wide columns" with "columnar format". Parquet (lesson 02-02) stores data by columns in order to analyse it. Cassandra and HBase store rows grouped into partitions in order to serve reads and writes by key. The resemblance is in name only.
Graphs
The data is modelled as nodes (entities) and relationships between them, and both can have properties. What in a relational database would require chaining many joins is here a matter of traversing the graph.
flowchart LR
C1((Customer 770)) -- BOUGHT --> P1[Television]
C1 -- BOUGHT --> P2[TV Mount]
C2((Customer 86)) -- BOUGHT --> P1
C2 -- BOUGHT --> P2
C2 -- BOUGHT --> P3[Soundbar]
- Representative product: Neo4j, with its Cypher query language. Others: Amazon Neptune, JanusGraph.
- Strengths: questions about connections: paths, neighbours, communities.
- Limit: they are not designed for massive aggregations, nor for easily distributing a gigantic graph.
- At NovaMarket: the "bought together" recommendations and, in fraud detection, uncovering accounts that share a device, address or card.
As an illustration, this is how you would ask in Cypher which products were bought by those who bought product 20 (for reading only; there is no need to run it):
MATCH (p:Product {product_id: 20})<-[:BOUGHT]-(c:Customer)-[:BOUGHT]->(other:Product)
RETURN other.name, count(*) AS times
ORDER BY times DESC
LIMIT 5The query literally draws the path: product ← customer → other product.
Summary of the four types
| Type | Model | Product | Queried by | Use at NovaMarket |
|---|---|---|---|---|
| Key-value | Key → value | Redis | The exact key | Cart, session, cache, rankings |
| Documents | JSON-like documents | MongoDB | Any field (better with an index) | Product catalogue |
| Wide columns | Partitions of ordered rows | Cassandra, HBase | Partition key | Event history by customer |
| Graphs | Nodes and relationships | Neo4j | Graph traversals | Bought together, fraud |
Using several at once, each for what it does well, is common practice and is called polyglot persistence.
Hands-on with MongoDB
Optional exercise. It needs Docker (lesson 01-05). If you do not have it, read the commands and their outputs: the results have been checked in a real run, although the console may show them with different indentation or spread over more lines depending on the version.
Start a MongoDB server in a container and open its console, mongosh:
docker run -ddownloads the image the first time and starts the container in the background;--namegives it a name we can refer to it by.docker exec -it nm-mongo mongoshruns the console inside the container. The prompt changes totest>.
Inserting documents
use novamarket
db.products.insertMany([
{ _id: 4, name: "Monitor Turia 512", category: "computing", price: 228.62,
attributes: { inches: 27, resolution: "4K", connections: ["HDMI", "USB-C"] } },
{ _id: 7, name: "Speaker Nova 445", category: "audio", price: 492.62,
attributes: { bluetooth: true, power_w: 120 } },
{ _id: 11, name: "Coffee Maker Altea 552", category: "appliances", price: 188.83,
attributes: { capsules: true, pressure_bar: 19 } },
{ _id: 13, name: "Headphones Kore 910", category: "audio", price: 105.48,
attributes: { bluetooth: true, noise_cancelling: true, battery_life_h: 30 } }
])use novamarketselects the database. There is no need to create it or to define tables: the database and theproductscollection come into being when the first document is inserted._idis the mandatory primary key of every document; we use theproduct_idfrom the catalogue. The names, categories and prices are those inproducts.csv; theattributesare made up for the example.- Each product has different attributes, and one of them (
connections) is a list. In a relational table this would require many empty columns or additional tables.
Querying
find takes two objects: the filter (category audio and price lower than 200; $lt stands for less than) and the projection, which says which fields to return. It is equivalent to SELECT name, price FROM products WHERE category = 'audio' AND price < 200.
You can filter on nested fields using dot notation, and on the contents of a list:
db.products.find({ "attributes.bluetooth": true }, { name: 1, _id: 0 })
db.products.find({ "attributes.connections": "USB-C" }, { name: 1, _id: 0 })A simple aggregation
db.products.aggregate([
{ $group: { _id: "$category", num_products: { $sum: 1 }, avg_price: { $avg: "$price" } } },
{ $sort: { avg_price: -1 } }
])[
{ _id: 'audio', num_products: 2, avg_price: 299.05 },
{ _id: 'computing', num_products: 1, avg_price: 228.62 },
{ _id: 'appliances', num_products: 1, avg_price: 188.83 }
]aggregate takes a list of stages that are applied in order, like an assembly line. $group groups by category (the $ in front of category means "the value of that field"), counts and calculates the average; $sort sorts from highest to lowest (-1). It is the equivalent of GROUP BY and ORDER BY.
Creating an index
db.products.createIndex({ category: 1, price: 1 })
db.products.find({ category: "audio" }).explain().queryPlanner.winningPlan.inputStage.stageWithout an index, MongoDB scans the entire collection for every query (COLLSCAN). With the index on category and price, it goes straight to the documents of interest: IXSCAN (index scan) confirms it. With four documents you cannot tell; with the real catalogue, it is the difference between milliseconds and seconds.
Leave the console with exit. When you finish the lesson, remove the container with docker rm -f nm-mongo; the data is deleted along with it.
Hands-on with Redis
Optional exercise, again with Docker.
Simple key-value
127.0.0.1:6379> SET session:s-017684:customer 770 OK 127.0.0.1:6379> GET session:s-017684:customer "770"
SET stores a value under a key and GET retrieves it. The colons in the key mean nothing to Redis: they are a convention for giving it structure (type:identifier:field).
A cart as a hash
A hash is a value with fields, ideal for a cart: each field is a product and its value, the quantity.
127.0.0.1:6379> HSET cart:770 product:142 1 product:17 2 (integer) 2 127.0.0.1:6379> HINCRBY cart:770 product:142 1 (integer) 2 127.0.0.1:6379> HGETALL cart:770 1) "product:142" 2) "2" 3) "product:17" 4) "2"
HSETadds two products to customer 770's cart (it returns the number of fields created).HINCRBYincreases the quantity of product 142 by 1. The operation is atomic: even if two requests arrive at once, neither is lost.HGETALLreturns the whole cart as field-value pairs.
Automatic expiry (TTL)
EXPIRE says that the key must delete itself after 1,800 seconds (30 minutes), and TTL (time to live) shows how many it has left. If the customer leaves, the cart disappears without anyone having to clean it up. TTL returns -2 when the key no longer exists.
A ranking with a sorted set
A sorted set stores elements with a score and keeps them ordered by it. It is the perfect structure for "today's most viewed products":
127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:142 "1" 127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:17 "1" 127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:142 "2" 127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:88 "1" 127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:142 "3" 127.0.0.1:6379> ZINCRBY ranking:views:2026-06-15 1 product:17 "2" 127.0.0.1:6379> ZREVRANGE ranking:views:2026-06-15 0 2 WITHSCORES 1) "product:142" 2) "3" 3) "product:17" 4) "2" 5) "product:88" 6) "1"
- Each
ZINCRBYsimulates aproduct_viewevent: it adds 1 to the product's score and returns the new one. ZREVRANGE ... 0 2 WITHSCORESreturns positions 0 to 2 in descending order: the top 3, with their scores.
Getting the ranking does not require scanning or sorting anything: Redis keeps it ordered on every update. In NovaMarket's architecture, stream processing (lesson 03-05) would feed this ranking event by event, and the website would read it for its "Most viewed" section.
Leave with exit and remove the container with docker rm -f nm-redis.
Query-driven modelling and the partition key
In a relational database you normalise: each piece of data is stored only once and the queries recombine it with joins. The design starts from the data.
In NoSQL it works the other way round. The starting point is the question: "exactly which queries will the application make?". And you design a structure that answers each one by reading a single place, even if that forces you to duplicate data (denormalise).
An example with Cassandra
The query the website needs: "give me the latest events for customer X". The table in CQL (Cassandra's language) would be this one. There is no need to run it; what matters is understanding its last line.
CREATE TABLE events_by_customer (
customer_id int,
month text, -- '2026-06'
event_time timestamp,
event_id text,
event_type text,
product_id int,
device text,
PRIMARY KEY ((customer_id, month), event_time, event_id)
) WITH CLUSTERING ORDER BY (event_time DESC, event_id ASC);The primary key has two parts with different functions:
(customer_id, month)is the partition key. Cassandra applies a hash function to it to decide on which node of the cluster the row is stored (the key-based partitioning from lesson 01-04). All the rows with the same partition key live together on the same nodes.event_time, event_idare the clustering columns. They determine the order of the rows within the partition: here, from the most recent event to the oldest.
The website's query looks like this:
SELECT event_type, product_id, event_time
FROM events_by_customer
WHERE customer_id = 770 AND month = '2026-06'
LIMIT 20;Cassandra works out the node from the partition key, goes to it and reads the first 20 rows, which are already in order. It makes no difference whether the table has a thousand rows or a hundred billion: the cost is the same.
How to choose a good partition key
| Criterion | Why | In the example |
|---|---|---|
It must appear in the query's WHERE |
Without it, Cassandra would have to ask every node | The website always knows the customer_id |
| It must spread the data evenly | It avoids skew: giant partitions on some nodes and empty ones on others | There are many customers, with reasonably evenly spread activity |
| Partitions must not grow without limit | A huge partition is slow and hard to move | month is added: each customer starts a fresh partition every month |
A counterexample: using event_type as the partition key would create only four partitions, and 70% of the data (product_view) would land in one of them. Another: using device, with three values.
And what if tomorrow you need to query "all the events for product 142"? This table cannot answer efficiently. The usual solution is to create another table, events_by_product, with the same data and a different partition key. One table per query: storage is duplicated to gain read speed.
When NOT to use NoSQL
NoSQL is not "the modern version" of databases. In many situations, a relational database is the right choice:
- The data fits comfortably on one server. The vast majority of applications have no scale problems. NovaMarket's 50,000 daily orders are handled effortlessly by a well-configured relational database.
- Transactions across several entities are needed. Orders, payments, stock, invoicing: there ACID is non-negotiable.
- The queries are not known in advance. For exploratory analysis, with different questions every day, you need SQL with unrestricted joins. That is the territory of the data warehouse (lesson 02-05), not of NoSQL.
- The model is full of relationships that are queried in every direction.
- The team cannot take on the complexity. Operating a distributed cluster and reasoning with eventual consistency has a real cost.
That is why, in NovaMarket's architecture, the shop still runs on a relational database, and the NoSQL databases sit in the serving layer, for specific cases: cart and rankings in Redis, catalogue in MongoDB, history by customer in Cassandra.
Warning: carts, sessions and browsing histories linked to a
customer_idare personal data. Their storage, retention periods and protection are subject to data protection regulations, which are covered in Module 7. In a real project, these decisions must be reviewed with the compliance officer.
Common Mistakes and Tips
- Choosing NoSQL "because it scales" without having a scale problem. You pay for the complexity without getting the benefit.
- Designing the model as if it were relational. Normalising and expecting joins in Cassandra or Redis leads to doing the joins in the application, slowly. Start with the list of queries.
- Choosing a partition key with few values or very uneven ones. It produces skew and giant partitions. It is the most expensive design mistake to correct, because it forces you to rewrite the table.
- Forgetting indexes in MongoDB. Everything works fine in development, with little data, and collapses in production.
- Using Redis as the only store for data that cannot be lost. It is, first and foremost, an in-memory database. It has persistence mechanisms, but its natural role is as a cache and a store for ephemeral or rebuildable data.
- Assuming that "flexible schema" means "no schema". The schema still exists, but it is enforced by the application code. Without discipline, the collection ends up with five variants of the same field.
- Tip: when in doubt, start with a relational database and add a NoSQL one when a specific need arises that justifies it.
Exercises
Exercise 1: choosing the type of database
Say which type of database (relational or one of the four NoSQL types) you would use in each case and why:
- Storing the payments for orders, which must always tally with the accounts.
- Limiting login attempts to five per customer every ten minutes.
- Detecting groups of accounts that share a phone number or delivery address.
- Storing product reviews, which include text, a rating, optional photos and replies from the seller.
- Recording the temperature readings sent every minute by 20,000 sensors in the warehouses.
Exercise 2: designing a partition key
The website wants to show on each product page "the last 10 people who added it to their cart today". Design a Cassandra table in CQL for that query. State the partition key, the clustering columns and why you have not chosen product_id alone as the partition key.
Exercise 3: a search ranking in Redis (optional, with Docker)
Using redis-cli, keep a ranking of the day's most searched terms. Record these searches: laptop, headphones, laptop, coffee-maker, laptop, headphones. Show the top 2 with their scores and make the ranking expire in 24 hours.
Solutions
Exercise 1
- Relational. ACID transactions across several tables (payment, order, accounting entry); consistency is non-negotiable.
- Key-value (Redis). One counter per customer with a 600-second expiry:
INCRplusEXPIRE. - Graphs. It is a question about connections between entities.
- Documents. A variable, nested structure, which is read whole alongside the product.
- Wide columns. Continuous, heavy writing; queried by sensor and time range. (There are also databases specialised in time series.)
Exercise 2
CREATE TABLE cart_by_product (
product_id int,
event_date date,
event_time timestamp,
event_id text,
customer_id int,
PRIMARY KEY ((product_id, event_date), event_time, event_id)
) WITH CLUSTERING ORDER BY (event_time DESC, event_id ASC);
SELECT customer_id, event_time
FROM cart_by_product
WHERE product_id = 142 AND event_date = '2026-06-15'
LIMIT 10;The partition key is (product_id, event_date); the clustering columns are event_time (descending, to get the most recent first) and event_id (so that two events in the same second do not overwrite each other). With product_id alone, a popular product's partition would grow indefinitely; adding event_date bounds it to one day, which is also exactly what the query asks for.
Common mistake: forgetting event_id in the key. In Cassandra, two rows with the same complete primary key are the same row: the second overwrites the first without warning.
Exercise 3
The ZINCRBY is repeated with each term in the list, and then:
127.0.0.1:6379> ZREVRANGE ranking:searches:2026-06-15 0 1 WITHSCORES 1) "laptop" 2) "3" 3) "headphones" 4) "2" 127.0.0.1:6379> EXPIRE ranking:searches:2026-06-15 86400 (integer) 1
Including the date in the key means each day has its own ranking, and the 86,400-second EXPIRE cleans up the old ones automatically.
Conclusion
NoSQL databases emerged to scale horizontally and handle data of variable structure, in exchange for giving up part of the guarantees and query flexibility of the relational model. In place of ACID, many adopt BASE and eventual consistency, which is the practical face of the choice between consistency and availability in the CAP theorem. You have met their four families — key-value (Redis), documents (MongoDB), wide columns (Cassandra, HBase) and graphs (Neo4j) — with a specific use at NovaMarket for each, and the rule that governs them: you model from the queries, choosing the partition key with care. And also when not to use them: if the data fits on one server, needs transactions or is going to be queried in unpredictable ways, a relational database is still the best answer.
That last point leaves a question open. NoSQL databases serve the queries foreseen very quickly, but analysis consists precisely of asking unforeseen questions about all the historical data: events, orders, customers, everything together. Where is it brought together, and how is it organised so that it does not turn into a dumping ground for files? With the distributed file systems from lesson 02-01 and the formats from 02-02 you already have the ingredients. In the next lesson, Data Lakes, you will combine them to build NovaMarket's central data store.
