So far we have scaled the easy part. The application instances are stateless and multiply behind a load balancer; the cache avoids most of the repeated tracking reads. But all the instances of the modular monolith still share db-01, the same database in which a heavy report took shipment creation out of service. Amdahl's law already warned us that the shared resource sets the ceiling. In this lesson we tackle the data layer: why it is the hardest to scale, what can be done before spreading the data across several machines, how replication and partitioning work, and how to choose the right store for each access pattern. We will finish with the data design of the Rutaverde platform and with a decision as important as the others: what we are not going to do yet.
Contents
- Why the database is the hardest bottleneck
- Vertical scaling and its limits
- The connection pool
- Primary-replica replication
- Read/write separation
- Table partitioning within a database
- Sharding: horizontal partitioning across servers
- One database per service or per module
- Choosing the store according to the access pattern
- Archiving historical data
- CAP and eventual consistency, applied
- Design for Rutaverde
- Why the database is the hardest bottleneck
A stateless application instance is interchangeable: it is created, destroyed, and copied without consequences. A database is exactly the opposite, because it is the place to which we have moved all the state.
| Difficulty | Explanation |
|---|---|
| Data is heavy | Copying 600 GB takes hours; an application instance starts in seconds |
| The copies must match | Two application instances do not need to agree with each other; two copies of a piece of data do |
| Writes are not easily distributed | If two nodes accept writes to the same data, conflicts appear |
| Guarantees are costly | Transactions, uniqueness, and integrity are simple on one node and very expensive across several |
| Errors are lasting | A faulty instance is replaced; corrupt data stays |
That is why the sensible strategy is a ladder: you start with the simplest measures and only climb a rung when the previous one is exhausted.
flowchart LR
A["1. Optimize queries and indexes"] --> B["2. Vertical scaling"]
B --> C["3. Connection pool and cache"]
C --> D["4. Read replicas"]
D --> E["5. Table partitioning and archiving"]
E --> F["6. Separate data by service"]
F --> G["7. Sharding"]
Each rung adds more complexity than the one before. The last one, sharding, is by far the most expensive and the hardest to undo.
- Vertical scaling and its limits
For a relational database, a more powerful machine is often the best investment: it changes nothing in the application and preserves all the guarantees. db-01, with 32 cores and 256 GB, is already a sizable machine. Its limits are the ones we saw when discussing vertical scaling:
- It has a ceiling, and the price grows faster than the power.
- Upgrading it requires buying hardware and stopping the service, against NFR-08.
- It does nothing for availability: it is still a single machine.
The conclusion is not to abandon vertical scaling, but to stop depending on it alone. The best way to "upgrade" db-01 is to take away work that does not belong to it.
- The connection pool
Opening a connection to the database is expensive, and every open connection consumes memory on the server. A connection pool is a set of connections that the application opens once and reuses: each request borrows one, uses it for a few milliseconds, and returns it.
The pool has a second effect, less obvious and more important for scalability: it limits how much simultaneous load can reach the database. It is a form of backpressure.
minimumis the number of connections kept open even when there is no activity, so that the first requests are served without delay.maximumis the cap per instance. If all 40 are in use, the next request waits.max_wait_mslimits that wait to 2 seconds; after that time, the request fails instead of hanging indefinitely.max_lifetime_minrenews the connections every so often to keep them from getting stuck in a faulty state.
The tricky point appears when this is combined with horizontal scaling: connections are multiplied by the number of instances. db-01 will accept a maximum of 300 connections. Let's do the math for a peak season:
| Source | Instances | Maximum connections per instance | Total |
|---|---|---|---|
| Main monolith group | 5 | 40 | 200 |
mono-batch-01 |
1 | 20 | 20 |
| Reserve for administration and replication | 30 | ||
| Total | 250 of 300 |
It fits with room to spare. But if someone switched on ten instances without reviewing this math, the database would reject connections and more instances would mean less service. When the number of instances varies a lot, a connection pooler is placed in between, a component that multiplexes many application connections over a few real connections; PgBouncer is a well-known example for PostgreSQL.
- Primary-replica replication
Replicating means keeping copies of the same data on several servers. In the most common setup there is a primary server, which is the only one that accepts writes, and one or more replicas, which continuously receive the changes from the primary and apply them.
flowchart LR
A["Application"] -->|"writes and critical reads"| P["Primary"]
P -->|"change stream"| R1["Replica 1"]
P -->|"change stream"| R2["Replica 2"]
I["Reports"] -->|"reads only"| R1
Replication serves three purposes: distributing reads, having a copy ready to replace the primary if it fails, and having a copy on which to run heavy jobs without disturbing anyone. The second use is developed in the lesson on high availability.
Synchronous and asynchronous
| Aspect | Synchronous replication | Asynchronous replication |
|---|---|---|
| When a write is confirmed | When both the primary and the replica have it | When the primary has it |
| Data loss if the primary goes down | None | The latest writes not yet sent |
| Effect on write latency | Increases it | None |
| Effect if the replica fails or falls behind | Writes stop or degrade | None on writes |
| Typical use | Replica intended to replace the primary | Read replicas |
Replication lag
In asynchronous replication, the replica is always somewhat behind the primary. That gap is called replication lag. Under normal conditions it is milliseconds or a few seconds; during a massive write load or a very long query on the replica it can reach minutes.
Its best-known consequence is the read-your-own-writes problem: a user saves a change, which goes to the primary, and immediately reloads the screen, which reads from the replica, where the change has not yet arrived. The user thinks the change has been lost.
| Solution | What it consists of |
|---|---|
| Critical reads go to the primary | What the user has just modified is always read from the primary |
| Window after the write | For a few seconds after writing, that user reads from the primary |
| Replicas only for what tolerates lag | Reports, historical listings, exports |
The third is the simplest and is the one we will apply.
- Read/write separation
With replicas available, the application splits its data traffic: writes go to the primary and certain reads go to the replicas. This is the simple form of the read/write separation pattern we introduced in the catalog.
The important decision is not technical but one of classification. For each read you have to ask how much staleness it tolerates:
| Read | Does it tolerate lag? | Destination |
|---|---|---|
| Checking a shipment that was just created | No | Primary |
| Data that feeds an invoice | No | Primary |
| Monthly activity report by city | Yes, minutes | Replica |
| Export of a merchant's history | Yes, minutes | Replica |
| A recipient's tracking query | Yes, seconds | Neither: Tracking's own store |
It is worth keeping the limits of this technique in mind: read replicas do not scale writes. All the writes still go through the primary and, on top of that, each replica has to apply them too.
- Table partitioning within a database
When a table reaches hundreds of millions of rows, even simple operations suffer: the indexes do not fit in memory, maintenance takes hours, and deleting old data is a long and risky operation. Table partitioning divides one logical table into several smaller physical tables, the partitions, within the same database. For the application it is still a single table.
The most frequent criterion is the date, because recent data is almost always what gets queried. An example in PostgreSQL for the history of shipment status changes:
CREATE TABLE shipments.shipment_event (
id bigint NOT NULL,
shipment_id bigint NOT NULL,
status text NOT NULL,
event_time timestamptz NOT NULL,
PRIMARY KEY (id, event_time)
) PARTITION BY RANGE (event_time);
CREATE TABLE shipments.shipment_event_2026_11
PARTITION OF shipments.shipment_event
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');Explanation:
- The first statement creates the
shipment_eventtable in theshipmentsschema. What sets it apart from a normal table is the last line:PARTITION BY RANGE (event_time)declares that it will be divided by ranges of theevent_timecolumn. That column is the partition key. - The primary key includes
event_timebecause PostgreSQL requires the partition key to be part of it. - The second statement creates the partition for November 2026.
FROM ... TO ...defines the range: from November 1, inclusive, to December 1, exclusive. There will be one partition per month, created automatically before the month begins.
What you gain:
| Benefit | Why |
|---|---|
| Faster queries | If the query filters by date, the engine only examines the partitions involved |
| Smaller indexes | Each partition has its own, and the recent ones fit in memory |
| Maintenance in parts | You reorganize or back up one partition, not the whole table |
| Immediate deletion and archiving | Removing a month means detaching a partition, not deleting millions of rows |
The condition is that queries include the partition key. A query that does not filter by date will have to scan all the partitions.
- Sharding: horizontal partitioning across servers
Sharding takes the idea one step further: the partitions, called shards, are no longer in the same database but on different servers. Each server stores a portion of the rows and handles its own reads and writes. It is the only technique in this lesson that scales writes beyond what a single machine can deliver.
The central decision is the partition key: the piece of data that determines which shard each row lives in. There are three ways of assigning it:
| Strategy | How it assigns | Advantage | Drawback |
|---|---|---|---|
| Range-based | Each shard covers an interval of the key | Range queries go to a single shard | Uneven distribution if the values are concentrated |
| Hash-based | A function is applied to the key and the result picks the shard | Uniform distribution | Range queries touch all the shards |
| Directory-based | A table says which shard each key is in | Flexible: a specific key can be moved | The directory is one more critical component |
And these are its problems, which explain why it is the last rung:
- Cross-shard queries. "All the shipments of this merchant" is trivial if the key is the merchant and extremely expensive if it is the city: you have to ask all the shards and combine the results. Joins between tables and transactions that affect several shards are even worse.
- Rebalancing. When a shard fills up, data has to be moved to another one, with the system running. It is a delicate operation; consistent hashing reduces how much has to be moved, but does not eliminate it.
- Hot keys. If one key concentrates the activity, its shard saturates while the others sit idle. With sharding by city, Madrid would be a hot key; by merchant, the largest customer would be.
- Multiplied operations. Backups, upgrades, schema changes, and monitoring are now done N times.
- It is almost irreversible. In the vocabulary of the previous module, it is a one-way door.
A good partition key distributes the load evenly, matches the way the data is queried, and never changes. One that meets all three conditions rarely exists.
- One database per service or per module
Another way of dividing the data is not by rows but by function: each service or module owns its data and nobody else accesses it directly. It is Rutaverde's principle P1, Every piece of data has a single owner, and it is what ADR-001 establishes by requiring a dedicated schema per module.
From a scalability standpoint, this matters for two reasons: it prevents the load of one function from affecting another, and it lets each one use the store and the size that suit it.
| Rung | Description | Situation at Rutaverde |
|---|---|---|
| Mixed tables | Everything in one schema; anyone reads any table | RouteManager today: 180 tables in one schema |
| One schema per module | Same database; each module with its own schema and its own user | Destination of the modular monolith |
| One database per service | Separate servers | Tracking |
The intermediate step has a cost that should be accepted from the start: queries that join tables from several modules are over. What used to be a join becomes a call to the other module's interface or a local copy of the necessary data, kept up to date.
The most delicate case is Reports, which today reads everyone's tables. The agreed solution: each module publishes read-only views with the data it agrees to expose, and Reports queries those views on the replica, never the internal tables or the primary. The views are a contract (P2): the module can reorganize its tables as long as it maintains the view.
- Choosing the store according to the access pattern
A relational database is good for almost everything, but it is not optimal for everything. The selection criterion is the access pattern: how the data is written and, above all, how it is read.
| Type of store | Model | Strength | Weakness | Example of use |
|---|---|---|---|---|
| Relational | Tables, joins, transactions | Consistency and flexible queries | Scaling writes | Shipments, billing |
| Key-value | One value per key | Speed and simple horizontal scaling | Can only be queried by key | Sessions, cache |
| Document | Documents with a flexible structure | Reading a complete aggregate in one go | Joins and transactions across documents | Tracking record |
| Object storage | Files with metadata | Almost unlimited, cheap capacity | Does not support queries | Delivery photos, labels, archives |
| Columnar analytical | Compressed columns | Aggregating billions of rows | Single-row writes | Historical reports |
The Tracking store
Tracking's access pattern is very particular: almost all reads are "give me everything related to this tracking code". There are no joins, no reports, no transactions across shipments. It is the textbook case for a document or key-value model: one document per shipment, with its current status and its history.
Marta evaluates three options with a decision matrix:
- A: managed PostgreSQL in the cloud, used as a document store: one row per shipment, with the key and a JSON column.
- B: a managed key-value or document store, proprietary to the provider.
- C: using only the in-memory store, with persistence enabled.
| Criterion | Weight | A: PostgreSQL with documents | B: provider's document store | C: in-memory store only |
|---|---|---|---|---|
| Fit with the access pattern | 0.30 | 4 | 5 | 3 |
| Fit with the team's skills | 0.25 | 5 | 2 | 3 |
| Portability, NFR-13 | 0.20 | 5 | 2 | 4 |
| Future scalability | 0.15 | 3 | 5 | 2 |
| Cost | 0.10 | 4 | 4 | 4 |
| Weighted total | 1.00 | 4.30 | 3.55 | 3.15 |
Option A wins. The data model is a document model, which is what the access pattern calls for, but on a technology the team has already mastered and that exists at any provider. Option C is also ruled out on principle: the cache is not a source of truth.
CREATE TABLE shipment_tracking (
tracking_code text PRIMARY KEY,
current_status text NOT NULL,
last_sequence integer NOT NULL,
updated timestamptz NOT NULL,
document jsonb NOT NULL
);tracking_codeis the key: every query comes in through it and is resolved with a single index lookup.current_statusandupdatedare stored as columns because they are used in almost every response.last_sequencerecords the number of the last change applied. We will need it in the next lesson to discard changes that are repeated or arrive out of order.documentcontains, in JSON format, everything else the page shows: the city, the estimated delivery time slot, and the status history.
Since access is hidden behind the service's interface (P2), switching to option B if the volume ever required it would be a reversible decision.
- Archiving historical data
Not all data deserves the same storage. Keeping ten years of history on the most expensive server in the company hurts performance, lengthens backups, and makes everything more expensive. Archiving moves old data to cheaper storage and removes it from the operational system.
| Tier | What it contains | Where | Access |
|---|---|---|---|
| Online | Data in use: the last few months | Main database | Milliseconds |
| Archive | Old data that has to be kept | Object storage, in compressed files in an open format | On request, in minutes or hours |
| Deleted | Data whose retention period has expired | Nowhere | None |
Date-based partitioning and archiving fit together perfectly: archiving a month consists of exporting its partition, verifying the copy, and detaching the partition from the table.
A warning: how long each piece of data is kept is not decided by the architect. There are minimum periods, because of tax and contractual obligations, and maximum periods, because data protection regulations prevent personal data from being kept longer than necessary. The periods that appear in this lesson are illustrative and must be validated by the regulatory compliance department and the head of security. The protection of that data is covered in Module 3.
- CAP and eventual consistency, applied
In the previous module we saw that, when communication between nodes fails, you have to choose between consistency and availability, and that the right choice depends on the function. Now that we have several copies of the data, that choice stops being theoretical:
| Function | Priority | How it materializes |
|---|---|---|
| Shipment creation | Consistency | Only the primary writes. If the primary is not available, the operation is rejected until there is a new primary |
| Billing | Consistency | It reads and writes on the primary; it never uses replicas or the cache |
| Tracking | Availability | It responds from its cache and its own store even if the data center is unreachable; it may show an outdated status |
| Reports | Availability, with lag | It reads from an asynchronous replica and states the time of the data |
Eventual consistency has two concrete, measurable sides here:
- The replication lag between the primary and the read replica: target, under 5 seconds under normal conditions.
- The propagation lag between the monolith and Tracking: target, p95 under 5 seconds.
Turning "eventually" into a number is what makes this trade-off manageable: it can be measured, monitored, and explained to the business.
- Design for Rutaverde
flowchart TB
subgraph DC["Zaragoza data center"]
MONO["mono-01 to mono-03: writes and critical reads"] --> P["db-01: primary, one schema per module"]
BATCH["mono-batch-01: scheduled jobs"] --> P
BATCH -->|"reports, read only"| R["db-02: asynchronous read replica"]
P -->|"asynchronous replication"| R
end
subgraph CLOUD["Public cloud"]
TRK["Tracking instances"] --> CS["cache-tracking"]
TRK --> BS["db-tracking: managed PostgreSQL in two zones"]
OBJ["Object storage: historical archive and backups"]
end
P -.->|"old partitions"| OBJ
The decisions, one by one:
- Per-module schemas in
db-01:customers,shipments,planning,delivery,billing, andreports, each with its own database user. The single user with all the permissions disappears. - Read replica
db-02: a server with 16 cores and 128 GB in the data center, with asynchronous replication. It serves the reports and the exports, whichmono-batch-01runs against it. The episode of the report that brought down shipment creation is no longer possible: reports and creation no longer share either application instances or a database server. - Tracking's own store,
db-tracking: managed PostgreSQL in the cloud, with 4 vCPU and 16 GB, with a primary and a standby replica in two zones. It stores one document per shipment and keeps it for 90 days after delivery. - Monthly partitioning of
shipments.shipment_event, the fastest-growing table: about 292 million rows per year at 200,000 shipments per day. 13 months are kept online; older partitions are archived in object storage in the cloud. - Connection pool: 40 per instance in the main group, 20 in
mono-batch-01, and a maximum of 300 ondb-01.
Why sharding is not needed yet
It is tempting to get ready "just in case." The numbers say it is not needed:
| Factor | Figure at the target peak | Assessment |
|---|---|---|
| Writes | 50 creations and about 200 status changes per second: fewer than 1,000 transactions per second | Within reach of a single server such as db-01 |
| Reads | Tracking and reports no longer reach the primary | The primary is relieved |
| Online volume | With archiving, around 1 TB | Manageable on one server |
| Geographic distribution | A single region | No need to distribute data by territory |
Sharding would solve a problem Rutaverde does not have, in exchange for problems it would have. What gets recorded is when the question would have to be reopened.
# ADR-006: Data strategy: read replica, Tracking's own store, and date-based partitioning, with no sharding
Status: Accepted
Date: 2026-05-07
Participants: Marta (architecture), Íñigo (operations), Clara (security)
## Context
A single database serves all the functions; a report took shipment
creation out of service. The event table will grow by about 292 million
rows per year. ADR-001 requires one schema per module and dedicated data
for Tracking.
## Options considered
A. Upgrade db-01 and keep the current design.
B. Read replica, Tracking's own store, and partitioning.
C. Sharding of the main database.
## Decision
We will adopt option B. db-01 will be the primary, with one schema and
one user per module. db-02 will be an asynchronous replica for reports
and exports, through views published by each module. Tracking will have
its own store, db-tracking, on managed PostgreSQL with a
document-per-shipment model and 90 days of retention after delivery. We
will partition shipments.shipment_event by month, with 13 months online
and an archive in object storage. We will not do sharding.
We will review this decision if sustained writes exceed 2,000 per
second, if the CPU of the primary exceeds 70% in a sustained way at
peak after optimizing, or if online data exceeds 2 TB.
## Consequences
Positive: reports stop affecting operations; tracking does not depend
on db-01; the online size stabilizes.
Negative: reports may be seconds or minutes behind; queries that join
tables from several modules are over; three databases to operate
instead of one.
Risks: the retention periods are pending validation by regulatory
compliance; db-01 is still the only one for writes.The last risk is not an oversight. We have solved the capacity of db-01, not its availability: if it fails, shipment creation stops. We will tackle that in the lesson on high availability.
Common Mistakes and Tips
- Starting with sharding. It is the last rung. Most systems never need it.
- Reading from the replica what has just been written. It produces the "my change has disappeared" effect. Classify each read before redirecting it.
- Believing that replicas scale writes. They only distribute reads.
- Forgetting that connections are multiplied by instances. Autoscaling the application can exhaust the database.
- Partitioning by a key the queries do not use. Every query scans every partition and the result is worse than before.
- Sharing a database between services "temporarily." It is the fastest way to cancel out the independence that was sought by separating them.
- Choosing the store because it is fashionable. It is chosen by access pattern and by the team's ability to operate it.
- Never archiving. Data only grows. Without an archiving policy, the problem is certain to arrive; only the date is unknown.
- Tip: before proposing a technique from this lesson, measure three things: the ratio of reads to writes, the ten most expensive queries, and the growth rate of the largest tables. With that, the right rung is usually obvious.
Exercises
Exercise 1
State whether each read should go to the primary db-01, to the replica db-02, or somewhere else, and why:
- A merchant creates a shipment and the portal then shows the detail screen for that shipment.
- The business director opens the report of shipments by city for the previous quarter.
- The overnight billing process calculates the amounts for the month.
- A recipient checks where their package is.
Exercise 2
During a peak season, someone proposes switching on three more instances in the main group, up to a total of eight, "to be on the safe side." With the values from this lesson:
- How many connections could the application as a whole end up opening?
- What would happen?
- Propose two solutions.
Exercise 3
A colleague proposes sharding the main database using the city as the partition key, arguing that "this way each city is independent and we comply with P5." The six current cities split the shipments as follows: Madrid 38%, Barcelona 27%, Valencia 12%, Seville 10%, Zaragoza 7%, Bilbao 6%. Evaluate the proposal.
Solutions
Solution 1
- Primary. This is the read-your-own-writes case: on the replica the shipment might not have arrived yet.
- Replica. It is a heavy query on old data, which easily tolerates seconds or minutes of lag.
- Primary. Even though it is a heavy process, the amounts must be calculated on exact, complete data. It runs at night, from
mono-batch-01, precisely so as not to compete with operations. - Neither. It is handled by the Tracking service, first from
cache-trackingand, on a miss, fromdb-tracking.
Solution 2
- 8 × 40 = 320 from the main group, plus 20 from
mono-batch-01: 340, not counting the reserve of 30. db-01accepts 300. As it approached the limit it would reject connections: errors would appear on random instances, and each open connection would also consume server memory. More instances would deliver less service.- Reduce the pool maximum per instance, for example to 30 (8 × 30 + 20 + 30 = 290); or place a connection pooler in between to multiplex. Simply raising the limit on
db-01is not a solution: every connection has a cost and the limit exists to protect it. And before anything else, ask whether the eight instances are needed: five already cover the requirement.
Solution 3
The proposal does not hold up, for several reasons:
- There is no problem to solve. The expected writes are far below the capacity of one server. We would be paying for the most expensive pattern in exchange for nothing.
- Hot keys. Madrid and Barcelona account for 65% of the shipments. The Madrid shard would have more than six times the load of the Bilbao shard.
- Cross-shard queries. A merchant with stores in several cities would force us to query several shards to list its shipments or issue its invoice.
- P5 does not require this. The principle says that adding a city is configuration, not development. With sharding by city, adding a city would require deciding which shard it goes in and perhaps rebalancing: the opposite of what is intended.
- It is a one-way door. It deserves a far more thorough analysis than the argument given.
The right answer is the one in ADR-006: do not shard, and set the thresholds that would force us to reconsider.
Conclusion
The data layer is the hardest to scale because it concentrates the state, and that is why it is approached as a ladder: optimize, scale vertically, control the connections, replicate to distribute reads, partition the large tables, separate the data by function and, only at the end, spread the rows across servers. We have seen the difference between synchronous and asynchronous replication, replication lag and its consequences, date-based partitioning, the problems of sharding, choosing the store according to the access pattern, and archiving. And we have turned CAP and eventual consistency into concrete decisions with numbers.
ADR-006 gives Rutaverde a data layer with four pieces: db-01 as the primary with one schema per module, db-02 as a replica for reports, db-tracking as Tracking's own store, and a historical archive in object storage. And it puts in writing why there will be no sharding and when it would have to be reconsidered.
There is one loose end that we have already mentioned three times. db-tracking is in the cloud and the status changes happen in the monolith, in the data center. How does Tracking find out that a shipment has been delivered, without the monolith having to wait for it or depend on it? And how do we stop sending the SMS inside the delivery confirmation? The answer to both questions is the same: asynchronous communication, through message queues and events.
Technological Architecture Course
Module 1: Fundamentals of Technological Architecture
- Introduction to Technological Architecture
- System Design Principles
- Components of a Technological Architecture
- Architecture Models
- Non-Functional Requirements and Quality Attributes
- Architecture Decisions and Trade-off Analysis
Module 2: Designing Scalable Systems
- Scalability Concepts
- Scalable Design Patterns
- Load Balancing
- Caching and In-Memory Storage
- Data Layer Scalability: Replication and Partitioning
- Asynchronous Communication: Message Queues and Events
- High Availability and Resilience
Module 3: Security in Technological Architecture
- Security Fundamentals
- Authentication and Authorization
- Data Protection
- Cloud Security
- Network Security and Zero Trust Architecture
- Threat Modeling
Module 4: Efficiency and Optimization
- Resource Optimization
- Monitoring and Maintenance
- Process Automation
- Performance Evaluation
- Technology Cost Management (FinOps)
- Business Continuity and Disaster Recovery
Module 5: Managing Technological Architecture
- IT Governance
- Technology Project Management
- Documentation and Communication
- Evaluation and Continuous Improvement
- Technical Debt and the Evolution of Legacy Systems
