The first test with 1,000 users left a clear result: the application servers have plenty to spare and the database has nothing more to give. It is no coincidence. Throughout the module we have taken state out of the application servers so we could multiply them, and that state has ended up in the data layer. In this lesson you will learn the two techniques for scaling it, replication and partitioning, and the theoretical limit that governs them, the CAP theorem. With it we will keep a promise we have been carrying since Module 1: explaining why you have to choose between consistency and availability. Verdalia will give PostgreSQL a machine of its own and a read replica, and will decide not to partition.

Why the Database Is the Hardest Thing to Scale

A stateless application server is interchangeable: you add another just like it and the load balancer distributes. A database is not, because it has state. A second, empty machine is useless. It has to contain the same data as the first, and keep containing it after every write. All the difficulties stem from that: copying the data takes time, the copies may disagree, and an operation that touches data located on two machines can no longer be a simple transaction.

That is why the techniques are applied in order, from the cheapest to the most expensive:

Order Technique What it scales Cost
1 Optimizing queries and indexes Everything Low
2 Caching Reads Low, with the risk of stale data
3 Vertical scaling Everything, up to the machine's ceiling Medium
4 Read replicas Reads Medium: replication lag appears
5 Partitioning Reads and writes Very high

Verdalia has already climbed the first two rungs.

Replication

Replicating is keeping copies of the same data on several machines.

Primary and Replicas

In the most widespread model, called primary-replica or leader-follower, one machine accepts the writes, the primary, and sends every change to the others, the replicas, which only accept reads.

flowchart LR
    app["Application servers"] -->|"Writes and critical reads"| primary[("Primary")]
    app -->|"Catalog reads"| replica[("Replica")]
    primary -->|"Change stream"| replica

A replica serves three purposes: spreading out the reads, replacing the primary if it fails, and running heavy queries, such as reports, without bothering the store. In this lesson we deal with the first. The second is the subject of the next one.

Synchronous and Asynchronous

Aspect Synchronous replication Asynchronous replication
When a write is confirmed When the replica has received it When the primary has saved it
Write latency Higher: it includes the trip to the replica The primary's
If the primary is lost No confirmed data is lost The latest writes may be lost
If the replica goes down or slows Writes stop or are delayed The primary does not notice
Reads on the replica Up to date May lag behind

Replication Lag

With asynchronous replication, the replica is always somewhat behind. That replication lag is usually milliseconds, but it grows when the primary receives many writes or the replica is busy. It produces a very visible effect: a customer saves a change, the next page reads from the replica, and the change is not there. The customer thinks it was lost, and repeats it.

The guarantee that prevents it is called read your own writes: whoever has just written a piece of data must see it, even if everyone else takes a few more seconds. The usual way to achieve it is to send that client's reads to the primary for a short time after each write.

Multi-Primary

In multi-primary replication, several machines accept writes. It scales writes and tolerates the loss of any node, but it introduces a new problem: two simultaneous writes to the same data, on different nodes, conflict, and someone has to decide which one wins. It is the territory of systems spread across several continents. It is not Verdalia's case.

Partitioning

Partitioning is spreading the data across several databases, so that each one holds only a part.

Vertical and Horizontal

Type What is spread out Example
Vertical Different tables in different databases, by functional area The catalog in one database and the orders in another
Horizontal, or sharding The rows of the same table, according to a key Some customers' orders in one database and other customers' in another

Vertical is the easy sibling. The data ownership we established in Module 3, with each table assigned to a module, is exactly what makes it possible. Horizontal is the one that truly scales writes, and the one that brings the problems.

Key Strategies

Strategy How it is assigned Advantage Drawback
By range According to intervals of the key: 2026 orders, 2027 orders Range queries go to a single partition The distribution becomes unbalanced: all the activity goes to the most recent partition
By hash According to the hash of the key Uniform distribution Range queries scan every partition
By directory A table says where each key is Flexible: a key can be moved The directory is one more piece, and a single point of failure

Problems

Problem What it consists of
Cross-partition queries “The 10 best-selling products” requires asking every partition and combining the answers
Cross-partition transactions An operation that touches two partitions is no longer atomic without additional mechanisms
Rebalancing Adding a partition forces data to be moved, with the system running
Hot keys A customer or a product with far more activity than the rest overloads its partition
Operation Each partition needs its own replicas, backups, and updates

For all these reasons, horizontal partitioning is the last resort. It is adopted when a single machine cannot handle the writes, after exhausting everything above. And the most delicate decision, the partition key, is very hard to change afterwards.

The CAP Theorem and PACELC

The Three Letters

The CAP theorem refers to systems that keep the same data on several machines connected by a network. Its three letters are frequently misunderstood:

Letter Name What it really means What it does not mean
C Consistency Every read returns the last confirmed write, as if there were a single copy It is not the C of ACID, which refers to integrity rules
A Availability Every working node responds to requests, without error It is not the percentage of “nines”
P Partition tolerance The system keeps working even if the nodes cannot communicate with each other It is not the data partitioning of the previous section

A network partition is a break in communication between nodes that are otherwise working. The primary and the replica are running, but they cannot see each other.

What It Says

The theorem is usually summarized as “of the three properties, pick two.” That summary misleads, because it suggests that you can give up P. You cannot: networks fail, and it does not depend on us. The useful statement is a different one:

When a network partition occurs, you have to choose between consistency and availability.

Let's see it with two nodes that have stopped seeing each other. A read arrives at the one that has been left isolated. It has only two options:

Option What the isolated node does What is sacrificed It is called
Answer with what it has Returns data that may be stale Consistency AP system
Refuse to answer Returns an error until communication is restored Availability CP system

There is no third option. The node cannot know whether its data is the latest, because it cannot ask.

PACELC

Partitions are infrequent. The rest of the time there is another trade-off, which the PACELC model adds to the previous one: if there is a partition, you choose between availability and consistency; and else, when there is none, you choose between latency and consistency. It is the choice between synchronous and asynchronous replication we have just seen: waiting for the replica gives consistency and costs latency.

The Last Olive Tree in Two Carts

In Module 1 we posed the case: one olive tree is left, two customers have it in their cart, and, at checkout, the system cannot check the stock. Now we can name it. Rejecting the purchase until the check is possible is choosing consistency. Accepting it and checking later is choosing availability. And the conclusion from back then is still the important one: the choice is not made once for the whole system, but one piece of data at a time.

Strong and Eventual Consistency, One Piece of Data at a Time

With strong consistency, every read sees the last write. With eventual consistency, which we met in Module 3, the copies may disagree for a while and end up matching. Verdalia's map:

Data Consistency Where it is read Reason
Stock, when confirming the order Strong Primary The last olive tree is not sold twice
Orders and charges Strong Primary It is money
Account data, just modified Read your own writes Primary, for 5 seconds The customer must see their change
Catalog product pages and listings Eventual, minutes Cache and replica Read a lot and changed little
Stock displayed on the product page Eventual, 10 seconds Cache and replica The notice is indicative
Product reviews Eventual, seconds Replica Nobody decides anything based on them
“People viewing this product” counter Eventual and approximate Redis It only has to be plausible
Confirmation email Eventual, seconds Message queue The customer does not wait for its result

The question that decides each row is always the same: what happens if someone acts on stale data.

A Read and Write Router in Python

The example simulates a primary, a replica with 2 seconds of lag, and a router that decides where each operation goes. Time is passed as a parameter, so there is no need to wait.

class Primary:
    def __init__(self):
        self.data = {}
        self.log = []           # changes, in order: (time, key, value)

    def write(self, key, value, now):
        self.data[key] = value
        self.log.append((now, key, value))

    def read(self, key):
        return self.data.get(key)


class Replica:
    def __init__(self, primary, lag):
        self.data = {}
        self._primary = primary
        self._lag = lag              # seconds each change takes to arrive
        self._applied = 0

    def read(self, key, now):
        log = self._primary.log
        while (self._applied < len(log)
               and log[self._applied][0] + self._lag <= now):
            _, changed_key, value = log[self._applied]
            self.data[changed_key] = value
            self._applied += 1
        return self.data.get(key)


class DataRouter:
    """Decides which server each operation goes to."""

    SECONDS_AFTER_WRITE = 5         # after writing, the customer reads from the primary

    def __init__(self, primary, replica):
        self._primary = primary
        self._replica = replica
        self._last_write = {}            # customer -> time of their last write

    def write(self, customer, key, value, now):
        self._primary.write(key, value, now)
        self._last_write[customer] = now

    def read(self, customer, key, now, require_fresh=False):
        has_written = customer in self._last_write and (
            now - self._last_write[customer] < self.SECONDS_AFTER_WRITE)
        if require_fresh or has_written:
            return "primary", self._primary.read(key)
        return "replica", self._replica.read(key, now)


def show(label, result):
    server, value = result
    print(f"  {label:26} {server}: {value}")


primary = Primary()
replica = Replica(primary, lag=2)
data = DataRouter(primary, replica)
primary.write("stock:2087", 3, now=0)

# Second 10: Ana posts a review and Luis buys an olive tree
data.write("ana", "review:2087:ana", "5 stars", now=10)
data.write("luis", "stock:2087", 2, now=10)

print("Second 10.5")
show("Ana, without router", ("replica", replica.read("review:2087:ana", 10.5)))
show("Ana, with router", data.read("ana", "review:2087:ana", 10.5))
show("Pablo sees the review", data.read("pablo", "review:2087:ana", 10.5))
show("Pablo sees the stock", data.read("pablo", "stock:2087", 10.5))
show("Pablo confirms his order",
     data.read("pablo", "stock:2087", 10.5, require_fresh=True))
print("Second 13")
show("Pablo sees the review", data.read("pablo", "review:2087:ana", 13))
show("Pablo sees the stock", data.read("pablo", "stock:2087", 13))

Output:

Second 10.5
  Ana, without router        replica: None
  Ana, with router           primary: 5 stars
  Pablo sees the review      replica: None
  Pablo sees the stock       replica: 3
  Pablo confirms his order   primary: 2
Second 13
  Pablo sees the review      replica: 5 stars
  Pablo sees the stock       replica: 2

Explanation of the code:

  • Primary holds the data and records every change in a log, with its time. Real databases do the same: the replica feeds on that change log.
  • Replica.read applies, before answering, the changes that have had time to arrive: those whose time plus the lag does not exceed the current moment.
  • DataRouter sends every write to the primary and remembers when each customer wrote. Reads go to the replica, with two exceptions: the customer has written in the last 5 seconds, or the operation declares, with require_fresh, that it needs up-to-date data.

Interpretation:

  • Without the router, Ana's review disappears. Half a second after posting it, the replica does not have it. With the router, Ana reads from the primary and sees it.
  • Pablo does not see the review yet, and it does not matter. He will see it 2 seconds later. That is eventual consistency, and for this data it is enough.
  • Pablo sees 3 in stock, and 2 are left. To display the product page, that is acceptable. To confirm the order, the read goes to the primary, which returns 2. And remember that the definitive guarantee is not this read, but the conditional UPDATE from Module 3.
  • A design detail. The _last_write dictionary is state in the process's memory, exactly what we learned to avoid. In the store, that time is kept in the customer's session, in Redis, because the next request may be served by another server.

Partition Assignment by Hash

Verdalia is not going to partition, but the mechanism is easier to understand with an example:

import hashlib
from collections import Counter


def partition(key, partitions):
    """Assigns a key to a partition, always the same one."""
    digest = hashlib.sha256(str(key).encode("utf-8")).hexdigest()
    return int(digest, 16) % partitions


customers = range(1, 10001)

distribution = Counter(partition(customer_id, 4) for customer_id in customers)
print("Distribution across 4 partitions:", sorted(distribution.items()))
print("Customer 5310 is in partition", partition(5310, 4))

moved = sum(1 for c in customers if partition(c, 4) != partition(c, 5))
print(f"Going from 4 to 5 partitions moves {moved} customers out of 10000")

Output:

Distribution across 4 partitions: [(0, 2509), (1, 2464), (2, 2420), (3, 2607)]
Customer 5310 is in partition 0
Going from 4 to 5 partitions moves 7969 customers out of 10000

Explanation:

  • hashlib.sha256 computes a digest of the key: a very large number that looks random, but is always the same for the same key. The remainder of dividing it by the number of partitions, obtained with %, indicates the partition.
  • hashlib is used and not Python's hash function, because the latter may give different results on each run of the program. A key that changed partition on restart would be a disaster.
  • Counter counts how many customers fall into each partition. The distribution is nearly uniform.
  • The last line shows the rebalancing problem: when a fifth partition is added, 80% of the customers change place. Almost all the data would have to be moved. The consistent hashing from the previous lesson reduces that movement to a fifth.

Verdalia: PostgreSQL With a Read Replica

The Machines

Machine Size Role Monthly price
verdalia-db-01 M: 4 cores, 8 GB, SSD disk PostgreSQL, primary €60
verdalia-db-02 M, identical PostgreSQL, read replica €60

The database takes up 6 GB since the images left the disk and the cart_items table disappeared, so it fits entirely in the memory of a size M machine. Replication is asynchronous. Marta ruled out synchronous because, with a single replica, its failure would stop the writes: the replica would become another single point of failure. The price is that, if the primary were lost, the writes of the last few moments could be lost. It is a risk that has to be decided consciously, and we will do so in the next lesson.

What Goes Where

Operation Destination
Catalog listings, product pages, and searches Replica
Confirming an order: read, charge, save, and deduct stock Primary
Customer account and “My orders” Primary
Admin panel Primary
Nightly sales report Replica

The split was done by module, not query by query. Since every table has an owning module and the catalog is organized in layers, the change was concentrated in the composition root:

# verdalia/app.py (excerpt)
primary_pool = create_connection_pool(host="verdalia-db-01")
replica_pool = create_connection_pool(host="verdalia-db-02")

product_repository = ProductRepository(read=replica_pool, write=primary_pool)
order_repository = PostgresOrderRepository(primary_pool)

The catalog repository receives two connection pools: it reads from the replica and writes to the primary. The orders repository only knows the primary. Neither the services nor the web layer have changed. If the replica does not respond, the catalog repository reads from the primary: the store loses capacity, but it keeps working.

Why It Is Not Partitioned

Question Answer at Verdalia
How many writes are there? Between 2,000 and 3,000 orders a month. In the best expected hour, 84 orders, which is last year's 60 plus 40%: fewer than 2 per minute
How much space does the data take? 6 GB. It grows about 2 GB a year
What was the bottleneck? Catalog reads and a shared disk, not writes
What would partitioning cost? Cross-partition queries and transactions, and several databases to operate among three people

A single PostgreSQL server handles thousands of writes per second. Verdalia has several orders of magnitude to spare. Partitioning would be paying the highest cost on the list to solve a problem it does not have: the YAGNI principle from Module 2, applied to data. The decision will be reviewed under the conditions of ADR-001, among them exceeding 10,000 orders a month.

Migration and Measurement

The migration took place on Tuesday, March 9, with 15 minutes of downtime. That day, RabbitMQ and notification-service moved to verdalia-aux-01, and verdalia-prod-01 was left switched off, waiting to be decommissioned at the end of the month. On Thursday, March 11, Lucía repeated the test with 1,000 users:

Measure March 4 March 11 QS-1 target
95th percentile of the catalog 870 ms 540 ms Under 800 ms
99th percentile of the catalog 2.3 s 1.4 s Under 2 s
Requests with errors 0.4% 0.1%
CPU usage, primary 35%
CPU usage, replica 41%
Replication lag, median 40 ms
Replication lag, maximum 1.8 s

For the first time, scenario QS-1 is met with 1,000 users, in the test environment.

Scaling the Queue Consumers

In Module 3 we left pending one of the answers to backpressure: adding consumers. A point-to-point queue distributes messages among all the consumers connected to it, so scaling consumption consists of starting more copies of the worker. It is horizontal scaling, and it demands the same as in the store:

Requirement Status at Verdalia
Stateless workers The identifiers of processed messages are in the service's store, not in memory
Idempotent consumers They have been since Module 3
Fair distribution prefetch_count=1: the broker does not deliver another message to a busy worker
Not depending on order With several consumers, the arrival order is not preserved

One worker sends about 45 emails per minute, and the store confirms fewer than 2 orders per minute in its best hour. For capacity, one would be enough. Verdalia starts two copies of worker.py for another reason: if one stops, the other carries on. If the emails.confirmation queue grew steadily, more would be added. It is worth knowing that, when consumers are multiplied, the limit moves to the next link: the email provider, which also has a maximum number of sends per minute.

Common Mistakes and Tips

  • Partitioning too early. It is the most expensive decision and the hardest to reverse. There are four rungs before it.
  • Reading from the replica right after writing. The customer does not see their own change. Read-your-own-writes must be guaranteed.
  • Deciding with data from the replica. Stock at confirmation and balances are read from the primary.
  • Interpreting CAP as “pick two.” Partition tolerance is not optional. The choice is between consistency and availability, and only while the partition lasts.
  • Demanding strong consistency for everything. It is paid for in latency and availability. Most of a store's data tolerates seconds of staleness.
  • Believing that a replica is a backup. An accidental deletion replicates in milliseconds. Backups are covered in Module 5.
  • Not watching the replication lag. A replica minutes behind serves false data without raising any error.
  • Practical tip. Split the reads by use case, not query by query. “The catalog reads from the replica” is a rule the whole team can remember.

Exercises

Exercise 1: Primary or Replica?

Say where you would send each read, and why:

  1. The home page, with the 12 best-selling products of the week.
  2. The confirmation page the customer sees right after paying.
  3. The monthly sales report Andrés asks for.
  4. The check of whether a single-use discount code has already been redeemed.

Exercise 2: A Network Partition

A network failure cuts verdalia-db-01 and verdalia-db-02 off from each other for 3 minutes. The application servers can see both. Describe what happens to the catalog reads and to the order confirmations, and say what Verdalia has chosen in each case, consistency or availability.

Exercise 3: The Partition Key

A store a hundred times bigger than Verdalia decides to partition the orders table. Compare two keys: the order's month, by range, and the customer's identifier, by hash. Which would you choose?

Solutions

Solution to Exercise 1

  1. Replica, and cache as well. A lag of minutes affects nobody.
  2. Primary. The customer has just written the order, and must see it.
  3. Replica. It is a heavy query that must not compete with sales.
  4. Primary, inside the transaction that redeems it. It is a decision with consequences, like the one about the last olive tree.

Solution to Exercise 2

The replica stops receiving changes, but keeps responding. The catalog shows data up to 3 minutes stale. For that data, Verdalia chooses availability: it prefers a slightly outdated product page to an error page.

Confirmations go to the primary, which works normally. They read and write the real data, so orders and stock keep their consistency. The price would be paid in a different case: if it were the primary that became unreachable, no orders could be confirmed, even though the replica had the data.

When the network is restored, the replica receives the pending changes and catches up. It is the same system with two different answers, one per kind of data.

Solution to Exercise 3

Aspect By month, with range By customer, with hash
Load distribution Bad: every write goes to the current month's partition Uniform
“My orders” Scans several partitions A single partition
Monthly sales report A single partition Scans all of them
Archiving old orders Simple: a whole partition is retired Hard

For a store in operation, the customer key is better: it spreads out the writes, which are the reason for partitioning, and resolves the most frequent query within one partition. Reports can run on a copy of the data prepared for that purpose. The date range key fits historical data, where what matters is archiving.

Conclusion

In this lesson you have learned why the data layer is the hardest to scale, and the two techniques for doing it. Replication copies the data to several machines and spreads out the reads, with replication lag as the price. Partitioning spreads out the writes too, and it is so costly that it is reserved as a last resort. You have seen what the CAP theorem really says: when the nodes cannot communicate, you have to choose between consistency and availability, and that choice is made one piece of data at a time.

At Verdalia, PostgreSQL has a machine of its own, verdalia-db-01, and a read replica, verdalia-db-02. The catalog reads from the replica and everything that moves money or stock goes to the primary. It is not partitioned, because there is no problem that justifies it. With 1,000 users, the 95th percentile of the catalog is 540 ms and the 99th percentile, 1.4 seconds: scenario QS-1 is met for the first time.

The system is now fast and has capacity. What remains to be seen is whether it is resilient. There is a single load balancer, a single primary, a single Redis, and a single RabbitMQ, and the campaign starts in nine days. In the last lesson of the module, “High Availability and Fault Tolerance,” we will hunt down every single point of failure, decide which ones are eliminated and which are accepted, and switch off a server in the middle of a load test to see what happens.

© Copyright 2026. All rights reserved