Data is the most durable part of a system. Verdalia's code has been reorganized several times in four months, but the orders from six years ago are still there, and they will still be there when the current application no longer exists. That is why deciding where and how each piece of data is stored is one of the architecture decisions with the most consequences. In this lesson you will learn the kinds of databases and storage, the criteria for choosing between them, and the risks of combining several. Verdalia will decide where each of its data lives and will resolve an issue pending since Module 2: the products table, shared by two modules. This lesson closes Module 3.
Relational Databases
A relational database organizes information in tables, made up of rows and columns, and relates tables to one another through keys. It is queried with the SQL language. PostgreSQL, Verdalia's database, is one of them.
Transactions and ACID
A transaction is a set of operations treated as one. Relational databases guarantee four properties, known by the acronym ACID:
| Property | What it guarantees | Example at Verdalia |
|---|---|---|
| Atomicity | All the operations happen or none does | If saving the order item fails, stock is not deducted |
| Consistency | The data always satisfies the integrity rules | Stock never goes negative |
| Isolation | Simultaneous transactions do not interfere with each other | Two customers do not buy the same unit at the same time |
| Durability | What is committed is not lost, even if the power goes out | A confirmed order is still there after a restart |
Normalization
Normalizing is organizing the tables so that each piece of data is stored in a single place. It is the DRY principle, applied to data. If a customer's address were copied into each of their orders, correcting it would mean modifying many rows, and forgetting one would leave contradictory data.
| Practical rule | Example |
|---|---|
| Each column holds a single value | One row per product in the order, not a list in a column |
| Each table describes a single thing | Customer data in customers; order data in orders |
| What can be calculated is not stored | The order total is obtained by adding up its items |
Sometimes it is broken on purpose. An order item stores the price at which the product was sold, because the catalog price will change and the order's price must not. It is not a copy of the same data: it is a different piece of data, the price at the moment of sale.
NoSQL Databases
The term NoSQL groups the databases that do not follow the relational model. They were born for cases in which the table model or the scaling of relational databases proved limiting. There are four families:
| Family | Data model | Queried... | Fits | Examples |
|---|---|---|---|---|
| Key-value | A value associated with a key | By the key, exclusively | Sessions, carts, counters | Redis, DynamoDB |
| Document | Documents, usually JSON, with a flexible structure | By any field of the document | Records with variable attributes | MongoDB |
| Column-family | Rows with variable columns, grouped in families | By row key; designed for heavy writing | Activity logs, large volumes | Cassandra |
| Graph | Nodes and relationships between them | By traversing relationships | Recommendations, contact networks | Neo4j |
What they have in common is that they force you to think about the queries first. In a relational database you model the data and then query whatever is needed. In a NoSQL database you design the storage to fit the expected queries, and an unexpected query can turn out to be very expensive.
Specialized Engines
| Kind | What it solves | Examples | Remarks |
|---|---|---|---|
| In-memory | Reads and writes in under a millisecond | Redis, Memcached | Memory is expensive and volatile: you have to decide what happens on a restart |
| Full-text search | Searching by words, with typo tolerance and ranking by relevance | Elasticsearch, OpenSearch | Almost always a copy of the data from another database, which has to be kept up to date |
| Time-series | Timestamped measurements, in large volume | InfluxDB, TimescaleDB | Designed for metrics and sensors |
Comparison, and ACID vs. BASE
| Kind | Strength | Weakness |
|---|---|---|
| Relational | Transactions, integrity, and flexible queries | Scaling writes across several machines is hard |
| Key-value | Speed and simplicity | Queried by key only |
| Document | Flexible structure; a whole object in one read | More limited relationships between documents and transactions |
| Column-family | Volume and write speed | Rigid queries |
| Graph | Queries over relationships | Poorly suited to everything else |
| In-memory | Minimal latency | Cost per gigabyte; limited durability |
| Search | Text search and relevance | Should not be the primary store |
| Time-series | Timestamped data, compressed and aggregated | Very specific use |
Many NoSQL databases give up part of the ACID guarantees in order to spread across many machines. Their model is summed up by the acronym BASE:
| Aspect | ACID | BASE |
|---|---|---|
| Priority | That the data is correct at all times | That the system always responds |
| After a write | Everyone reads the new value | For a while, some may read the previous one |
| Consistency | Immediate | Eventual, as we saw in the previous lesson |
| Fits | Money, stock, orders | Visit counters, recommendations, histories |
The boundary is no longer so sharp: there are NoSQL databases with transactions and relational databases that store JSON documents. The underlying reason why you have to choose between consistency and availability is something we will study in Module 4.
Kinds of Storage
Beneath any database, and beside it, there is storage. There are three kinds:
| Kind | How it looks | Accessed... | Typical use |
|---|---|---|---|
| Block | A raw disk | From a single server, which formats it | Server and database disks |
| File | Folders and files | By paths, shared between servers | Shared documents |
| Object | Objects with a key and metadata, grouped in buckets | Through an HTTP API | Images, videos, backups |
Object storage deserves attention. It has no real folders and does not allow modifying part of an object: it is uploaded and downloaded whole. In exchange, its capacity is practically unlimited, it is inexpensive, and each object has an address reachable over HTTP.
Depending on where it sits, storage can be:
| Location | Description | Advantage | Drawback |
|---|---|---|---|
| Local | The server's own disks | Fast and simple | If the server is lost, the data is lost. Not shared |
| Networked | Storage appliances reachable from several servers | Shared and centralized | It has to be bought and administered |
| In the cloud | A provider's service, pay per use | No practical capacity limit, with managed copies | Vendor dependence; variable cost |
Criteria for Choosing, and Polyglot Persistence
Criteria
| Criterion | Question |
|---|---|
| Data model | Are they related tables, loose objects, documents, relationships, or measurements over time? |
| Access patterns | How will they be read and written? By key, by several fields, by text? How many reads per write? |
| Consistency | What happens if someone reads stale data for a few seconds? |
| Volume and growth | How much space does it take today, and how much in three years? |
| Cost | How much do licenses, infrastructure, and, above all, operation cost? |
| Team experience | Do we know how to operate it, back it up, and recover it from a failure? |
The last criterion weighs more than it seems. A database the team masters, even if it is not the ideal one, usually gives better results than the ideal one operated blindly.
Polyglot Persistence
Polyglot persistence means using several kinds of data store in the same system, each for the data that fits it best. It makes sense, and it has risks:
| Risk | Consequence |
|---|---|
| More technologies to operate | Each one needs installation, monitoring, updates, and backups |
| No transactions across stores | An operation that writes to two can be left half done |
| Duplicated data | The copies have to be kept up to date, and you have to decide which one rules |
| Scattered knowledge | The team must master several tools |
The prudent rule is the one we have been applying: a new store is added when it solves a concrete problem that the current one cannot.
Verdalia's Data Map
In the last week of January, the team went over the store's data, item by item:
| Data | Owner | Characteristics | Store | Status |
|---|---|---|---|---|
| Orders and their items | Orders | Money; transactions | PostgreSQL | Kept |
| Stock | Inventory | Simultaneous writes; no room for error | PostgreSQL | Own table since January |
| Product records | Catalog | 15,000 products; many reads | PostgreSQL | Kept |
| Catalog search | Catalog | Free text | PostgreSQL full-text search | Dedicated engine, postponed |
| Product images | Catalog | 52,000 files, 41 GB; read a lot and rarely change | Object storage | Decided; migration in February |
| Sessions and carts | Cart | Ephemeral; access by key, very frequent | In-memory key-value store | Decided; to be adopted in Module 4 |
| Sent notifications | notification-service |
Few writes | The service's own database | In use |
| Messages in transit | RabbitMQ | Temporary | Durable queues | In use |
The reasons behind each decision:
- PostgreSQL remains the primary database. Orders and stock need transactions, the volume is modest, and the team knows it. Nothing justifies changing it.
- Images leave the server's disk. They are binary files taking up 41 GB on the same disk as the database and its backups. Object storage is their natural place: it costs under €5 a month for that volume, and the server stops being the only place where they exist. How to serve them quickly is a matter for Module 4.
- The search engine is postponed. Today the search uses
LIKEcomparisons, which neither tolerate typos nor rank by relevance. PostgreSQL includes full-text search, enough for 15,000 products. A dedicated engine would be one more piece and one more copy of the data to maintain. It will be reviewed if the catalog exceeds 100,000 products or if the business asks for suggestions and typo correction. - Sessions and carts fit an in-memory key-value store, such as Redis. They are always accessed by a key, they expire on their own, and they do not need to relate to anything. The
cart_itemstable has 310,000 rows today, and 94% belong to carts abandoned more than a month ago. Here we only decide that the data fits. The use of this kind of store as a performance technique is studied in Module 4.
A warning: among this data there is customers' personal data, such as names, addresses, and emails. Its processing and its location, especially when cloud services are contracted, are subject to data protection regulations. In a real system, these decisions must be reviewed with a compliance professional. We will come back to it in Module 5.
Data Ownership: The Products Table
The Problem
Since Module 2 we have been carrying a pending issue. The products table contained the product record and also the stock column. Catalog and inventory both read and wrote it, and the cart queried the stock on its own. It was the store's last mutual dependency.
The Rule
Each table has one owning module. Only that module reads and writes it. The other modules ask it for the data through its public interface. It is the microservices rule about data, applied inside the monolith and without needing to split the database.
flowchart LR
subgraph before["Before"]
c1["Catalog"] --> t1[("products, with stock")]
i1["Inventory"] --> t1
k1["Cart"] --> t1
end
subgraph after["After"]
c2["Catalog"] --> t2[("products")]
i2["Inventory"] --> t3[("stock")]
c2 -->|"check_stock"| i2
k2["Cart"] -->|"check_stock"| i2
end
The Schema
-- Owned by the catalog module
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
);
-- Owned by the inventory module
CREATE TABLE stock (
product_id INTEGER PRIMARY KEY REFERENCES products (id),
quantity INTEGER NOT NULL CHECK (quantity >= 0)
);Explanation:
PRIMARY KEYidentifies each row.NOT NULLmakes the value mandatory.CHECK (quantity >= 0)is an integrity constraint: the database rejects any operation that would leave stock negative. It is the last line of defense, not a business rule.REFERENCES products (id)prevents stock from existing for a nonexistent product.NUMERIC(10, 2)stores exact amounts, with two decimals.
In the catalog, the service stops receiving the stock from its repository and asks inventory for it:
# verdalia/catalog/service.py (excerpt)
class CatalogService:
def __init__(self, repository, inventory):
self._repository = repository
self._inventory = inventory
def product_details(self, product_id):
product = self._repository.find(product_id)
if product is None:
raise ProductNotFound(product_id)
stock = self._inventory.check_stock(product_id)
return ProductDetails(
name=product["name"],
final_price=price_with_vat(product["price"]),
notice=stock_notice(stock),
)The presentation has not changed. Catalog depends on inventory, and inventory no longer depends on catalog. The change was deployed on Tuesday, January 26.
The Last Olive Tree: A Transaction Step by Step
The Problem
One unit of the potted olive tree is left. Ana and Luis confirm their orders at the same instant. If the application reads the stock, decides, and then writes, this can happen:
| Moment | Ana | Luis | Stock |
|---|---|---|---|
| 1 | Reads: 1 left | 1 | |
| 2 | Reads: 1 left | 1 | |
| 3 | Decides she can buy and subtracts 1 | 0 | |
| 4 | Decides he can buy and subtracts 1 | -1 |
The same tree has been sold twice. The flaw lies in separating the check from the write: between one and the other, the data has changed.
The Solution
The check and the write must be a single operation, inside a transaction:
BEGIN;
UPDATE stock
SET quantity = quantity - 1
WHERE product_id = 2087
AND quantity >= 1;
-- If no row was modified, there were no units left: ROLLBACK
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1051, 2087, 1);
COMMIT;The condition AND quantity >= 1 is part of the modification itself. The database guarantees that two modifications of the same row do not run at the same time: the second waits for the first and, when its turn comes, the condition no longer holds.
The Example, Runnable
The example uses sqlite3 so that you can run it without installing anything. In PostgreSQL, the statements are the same.
import sqlite3
SCHEMA = """
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC NOT NULL CHECK (price >= 0)
);
CREATE TABLE stock (
product_id INTEGER PRIMARY KEY REFERENCES products (id),
quantity INTEGER NOT NULL CHECK (quantity >= 0)
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL REFERENCES products (id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);
INSERT INTO products VALUES (2087, 'Potted olive tree', 33.00);
INSERT INTO stock VALUES (2087, 1);
"""
class InsufficientStock(Exception):
"""Not enough units of the product are left."""
def sell(connection, order_id, product_id, quantity):
with connection: # transaction: COMMIT on exit, ROLLBACK if there is an exception
cursor = connection.execute(
"UPDATE stock SET quantity = quantity - ? "
"WHERE product_id = ? AND quantity >= ?",
(quantity, product_id, quantity),
)
if cursor.rowcount == 0:
raise InsufficientStock(product_id)
connection.execute(
"INSERT INTO order_items VALUES (?, ?, ?)",
(order_id, product_id, quantity),
)
def remaining(connection, product_id):
row = connection.execute(
"SELECT quantity FROM stock WHERE product_id = ?", (product_id,)
).fetchone()
return row[0]
connection = sqlite3.connect(":memory:")
connection.executescript(SCHEMA)
# 1. Atomicity: order 1050 already has an item with the olive tree and the insert fails
connection.execute("INSERT INTO order_items VALUES (1050, 2087, 1)")
connection.commit()
try:
sell(connection, 1050, 2087, 1)
except sqlite3.IntegrityError as error:
print(f"Order 1050: insert error ({error})")
print(f" Stock after the failure: {remaining(connection, 2087)}")
# 2. Two customers want the last olive tree
for order_id in (1051, 1052):
try:
sell(connection, order_id, 2087, 1)
print(f"Order {order_id}: olive tree sold")
except InsufficientStock:
print(f"Order {order_id}: no units left")
print(f" Final stock: {remaining(connection, 2087)}")Output:
Order 1050: insert error (UNIQUE constraint failed: order_items.order_id, order_items.product_id) Stock after the failure: 1 Order 1051: olive tree sold Order 1052: no units left Final stock: 0
Explanation:
with connection:opens a transaction. If the block ends well, it is committed withCOMMIT. If an exception occurs, it is undone withROLLBACK.cursor.rowcountindicates how many rows theUPDATEmodified. If it is zero, there were not enough units, and an exception with business vocabulary is raised.- First test: atomicity. To cause a failure halfway through the transaction, order 1050 already had an item with the olive tree. The
UPDATEsubtracts the unit, theINSERTfails, and the whole transaction is undone: stock goes back to 1. - Second test: the last olive tree. Order 1051 takes the tree. Order 1052 modifies no rows and receives
InsufficientStock. Stock ends at 0, not at -1. - This function belongs to the data access layer of the inventory module. It is the only code in the store that modifies the
stocktable.
A Nuance About Order
Today, stock is deducted after charging. If at that moment no units are left, the order has been charged and the money has to be refunded. With the transaction, the error no longer goes unnoticed, but the order of steps is still not ideal. The team has noted the improvement: reserve the unit before charging and release it if the charge is declined.
The Same Product as a Document
To contrast the models, this is how the olive tree would be stored in a document database:
{
"_id": 2087,
"name": "Potted olive tree",
"price": 33.00,
"categories": ["trees", "mediterranean"],
"attributes": {
"height_cm": 120,
"pot_diameter_cm": 30,
"exposure": "sun",
"watering": "low"
},
"images": ["products/2087/main.webp", "products/2087/detail-1.webp"],
"reviews": [
{"customer": "Carmen", "rating": 5, "comment": "Arrived in perfect condition"}
]
}| Aspect | Relational model | Document model |
|---|---|---|
| Where the product is | Spread across several tables: products, categories, attributes, images, reviews | In a single document |
| Reading the full record | One query joining several tables | One read |
| Different attributes per product | Hard: a pot has neither height nor watering | Natural: each document has its own |
| Renaming a category | One row is modified | Every document containing it has to be modified |
| Integrity | Guaranteed by the database | Must be guaranteed by the application |
| Deducting stock with guarantees | Natural, with a transaction | Possible, but not its strength |
The product record is a good candidate for the document model. Verdalia does not adopt it because the problem does not hurt enough: PostgreSQL allows storing the variable attributes in a JSON-type column, without adding another database to operate. Notice that the images are not in the document. They are in object storage, and the document keeps only their keys.
Module 3 Review
| Aspect | At the start of the module | End of January |
|---|---|---|
| Deployable pieces | 1: the store | 2: the store and notification-service |
| Catalog | SQL in 11 of its 14 routes | Three layers |
| Confirming an order, median | 3.5 seconds | 965 milliseconds |
| Confirmation emails | During the request | In the background, with RabbitMQ |
| Retrying charges | With risk of a duplicate charge | With an idempotency key |
| Dependencies between modules | 10, with 1 mutual | 8, with no mutual ones |
| Automated tests | 23 | 47 |
Lines in utils.py |
1,480 | 1,150 |
| Recorded decisions | ADR-001 and ADR-002 | ADR-003 and ADR-004 added |
What has not changed is the machine. Everything still runs on verdalia-prod-01, which now hosts Nginx, the store, PostgreSQL, RabbitMQ, and the two processes of the notification service. The limit is still around 250 simultaneous users.
Common Mistakes and Tips
- Choosing the database by fashion. The question is not which one is the most modern, but what data you have and how it will be queried.
- Checking and writing separately. Reading the stock, deciding in the application, and writing afterwards fails when there are two customers at once. The condition must go inside the modification itself.
- Storing large files in the database. Images make the database and its backups grow. They go in file or object storage, and the database keeps the reference.
- Sharing tables between modules. A change to a column affects everyone who reads it. Each table, one owner.
- Adding a store for every need. Every new technology is paid for in operation for years.
- Using a search engine or a cache as the primary store. They are copies. The original data must live in a durable store.
- Forgetting backups when adding a store. Every place where data lives needs its own backup plan. We will see it in Module 5.
- Practical tip. Before choosing, write down the five most frequent queries and the five most important writes. The right store is the one that handles them well.
Exercises
Exercise 1: Every Piece of Data in Its Place
Indicate the most suitable kind of store for each piece of data and justify your answer:
- Issued invoices, as PDFs.
- The store's response time, measured every 10 seconds.
- “Customers who bought this product also bought...”
- Single-use discount codes.
Exercise 2: A Stock Transfer
Verdalia opens a second warehouse. The stock table now has the key (product_id, warehouse_id). Write a function transfer(connection, product_id, source, target, quantity) that moves units from one warehouse to another without any being lost or duplicated.
Solutions
Solution to Exercise 1
- Object storage. They are files that are never modified. The relational database stores the invoice data and the file's key.
- Time-series database. They are timestamped measurements, in large volume, queried in aggregate.
- Graph database, if the volume justifies it. For a store the size of Verdalia, a SQL query calculated once a day is enough.
- Relational database. Redeeming a code requires the same guarantee as the last olive tree: that it is not used twice. A transaction is needed.
Common mistake: answering with the most specialized technology in every case. The third item shows that volume counts too.
Solution to Exercise 2
def transfer(connection, product_id, source, target, quantity):
with connection:
cursor = connection.execute(
"UPDATE stock SET quantity = quantity - ? "
"WHERE product_id = ? AND warehouse_id = ? AND quantity >= ?",
(quantity, product_id, source, quantity),
)
if cursor.rowcount == 0:
raise InsufficientStock(product_id)
connection.execute(
"UPDATE stock SET quantity = quantity + ? "
"WHERE product_id = ? AND warehouse_id = ?",
(quantity, product_id, target),
)Both modifications go in the same transaction. If the second fails, the first is undone and the units do not disappear. The first includes the condition on the quantity, so as not to leave the source warehouse negative. A complete version would also check that the second modification affected one row, in case the product was not registered at the target warehouse.
Conclusion
In this lesson you have learned the kinds of databases: relational ones, with their transactions and ACID guarantees; the four NoSQL families; and the in-memory, search, and time-series engines. You have distinguished block, file, and object storage, and learned to choose according to the data model, access patterns, consistency, volume, cost, and team experience. You have also seen that combining several stores makes sense, as long as each one solves a concrete problem.
At Verdalia, PostgreSQL remains the primary database, the images will go to object storage, and sessions and carts have been assigned an in-memory key-value store. The products table now has a single owner, and the last olive tree cannot be sold twice.
This lesson closes Module 3. In mid-November, Verdalia was a single application that made the customer wait while it sent an email. At the end of January it has a catalog organized in layers, an independent notification service, a versioned API, charges protected with idempotency keys, and a message queue that has brought order confirmation under one second. The decisions have been recorded in ADR-003 and ADR-004.
But all those pieces share a single server, which still fails from about 250 simultaneous users. Andrés expects 1,000 in the spring campaign, and about two months remain. The system is now better prepared to grow: its pieces are separated and its data has owners. In Module 4 we will make it grow. We will start with the most basic question: whether a bigger machine or several machines is the better choice. We will see it in the lesson “Horizontal and Vertical Scalability.”
