In the previous lesson we settled the vocabulary and the numbers: 50 creations and 250 tracking queries per second at peak, an application layer that must scale horizontally, and three forms of state that currently prevent it. Scalability problems look very much alike from one organization to the next, which is why there are named solutions that have been proven thousands of times: patterns. This lesson presents the catalog and serves two purposes. On the one hand it is a map: several patterns have a lesson of their own later on, and here we only place them. On the other, it develops in depth those that do not: externalizing state, idempotency, pagination, rate limiting and backpressure, the CDN, and autoscaling.

Contents

  1. What a pattern is and how to use the catalog
  2. Decomposition into components and services
  3. Five patterns that have their own lesson
  4. Stateless services: externalizing state
  5. Idempotency
  6. Pagination, rate limiting, and backpressure
  7. CDN for static content
  8. Autoscaling: metrics and thresholds
  9. The Rutaverde map: problem, pattern, and lesson

  1. What a pattern is and how to use the catalog

A design pattern is a general, reusable solution to a recurring problem, described together with the context in which it works and with its costs. That last part is what sets it apart from a recipe: every pattern solves one problem and introduces others.

Three rules for using a catalog wisely:

  • Start from the problem, not from the pattern. "Let's add a cache" is not a design. "80% of the queries repeat the same read and saturate the database" is a problem that a cache solves.
  • Every pattern has a price, almost always in complexity or in consistency. Applying a pattern without having its problem means paying the price for nothing, against principle P3.
  • Patterns are combined. None is enough on its own; Rutaverde's target architecture will use about ten.
Pattern Problem it solves Main price
Decomposition Everything scales and fails together More components to operate
Stateless services Instances cannot be added The state has to be moved somewhere else
Replicas behind a load balancer One instance is not enough and is a single point of failure A new, critical component
Cache Repeated, expensive reads Data that may be stale
Read/write separation Reads compete with writes Eventual consistency
Asynchronous processing Slow work inside the user's request The result is not immediate
Partitioning The data does not fit or does not perform on a single node More complex queries and operations
Idempotency Retries duplicate operations Storing and checking identifiers
Rate limiting and backpressure One client or one peak drags everyone down Legitimate requests have to be rejected
CDN Static content consumes your own capacity Managing content expiration
Autoscaling Fixed capacity is either too much or too little Fine-tuning metrics and thresholds

  1. Decomposition into components and services

If the whole system is a single piece, it can only be scaled as a whole, and a problem in one function affects all of them. Decomposing means dividing the system into parts with clear boundaries so that each one can scale, fail, and evolve separately.

This is not a new idea in the course: it is exactly what ADR-001 decides. What we add here is the reading from a scalability standpoint. Decomposition pays off when the parts have different load profiles:

Part Load profile What it needs
Shipment creation Writes; 50 per second at peak; cannot fail Consistency and availability
Tracking Reads; 250 per second at peak; tolerates seconds of delay To scale a lot, cheaply
Notifications Depends on a slow external provider; tolerates minutes Isolation and retries
Reports Few queries, but very heavy ones To stay out of everything else's way

Four profiles, four treatments. That is why Tracking and Notifications are extracted as services, and why Reports, even though it stays inside the modular monolith, will get its own resources. Decomposition can be done at two levels: modules within a single deployment, with published interfaces, and services deployed separately. The second level is only justified when the first is not enough.

  1. Five patterns that have their own lesson

These five patterns are the backbone of the module. Here the idea is enough; each one is developed in its own lesson.

Replicas behind a load balancer

Several identical copies of a service are run, and a load balancer is placed in front of them to distribute the requests among them. It provides capacity and, at the same time, tolerance to the failure of one copy. Condition: the service must be stateless. It is developed in the lesson on load balancing.

Cache

The result of an expensive operation is stored so that it can be reused for subsequent identical requests. It works very well when there are many more reads than writes, as in tracking. Its price is occasionally serving slightly old data. It is developed in the lesson on caching and in-memory storage.

Read/write separation and CQRS

Reads and writes have different needs, so they are served through different paths. In its simplest form, reads are sent to copies of the database. In its full form, called CQRS (Command Query Responsibility Segregation), there are two data models: one optimized for writing and another, derived from the first, optimized for reading.

flowchart LR
    C["Commands: create shipment, change status"] --> ME["Write model"]
    ME -->|"changes"| ML["Read model"]
    Q["Queries: where is my package"] --> ML

The Tracking service, with its own data fed from the monolith, is a read model in this sense. The data side is developed in the lesson on the data layer.

Asynchronous processing with queues

Work that does not need to finish within the user's request is left in a queue, and another process carries it out later. The request responds right away and the queue absorbs the peaks. It is the solution to the SMS that today is sent synchronously inside the delivery confirmation. It is developed in the lesson on asynchronous communication.

Partitioning

When a data set is too large to handle as a single unit, it is divided into parts according to a key: by date, by city, by customer. Within a single database this is called table partitioning; across several databases, sharding. It is developed in the lesson on the data layer.

  1. Stateless services: externalizing state

We saw that RouteManager keeps three types of state in the instance itself. The pattern consists of moving each one to a place shared by all the instances.

State Where it is today Where it is externalized to Alternative
Portal session Memory of app-01 Shared, in-memory session store Identity inside a signed token that travels with every request
Temporary files (CSV imports) Local disk of app-01 Shared storage: the NAS today; object storage later on Processing the file in a single request, without storing it
Scheduled jobs Inside every instance A dedicated instance, outside load distribution A distributed lock so that only one instance runs them

The session

With the session in a shared store, any instance can serve any user:

sequenceDiagram
    participant N as Browser
    participant A as Instance A
    participant B as Instance B
    participant S as Session store
    N->>A: Login
    A->>S: Save session s-81f2
    A-->>N: Cookie with the identifier s-81f2
    N->>B: Next request with the cookie
    B->>S: Read session s-81f2
    S-->>B: User data
    B-->>N: Response

The browser only keeps an identifier; the data lives in the store. If instance A disappears, the user notices nothing. Exactly what that in-memory store is, we will see in the lesson on caching. The signed-token alternative belongs to authentication and is studied in Module 3.

One nuance: the merchant API is already stateless, because every request carries its API key. Only the web portal needs this change.

Scheduled jobs

For the 05:00 route planning and the overnight billing, Marta applies P3 and chooses the simplest option: a dedicated instance of the monolith, mono-batch-01, which receives no traffic from merchants or couriers and is the only one configured to run scheduled jobs. As an additional safety measure, each job takes a lock in the database before starting, so that if someone started a second instance of this type by mistake, the work would not be duplicated. This instance will have a second duty, serving the heavy reports, which we will pin down when we design the load balancing.

  1. Idempotency

In a distributed system, requests get repeated: the network cuts off the response, the client does not know whether the operation was carried out, and it retries. The most delicate case is that of the courier confirming a delivery in a building entrance with poor coverage: the app, which according to NFR-02 must keep operating for 15 minutes without a connection, stores the confirmation and resends it until it gets a response. Without precautions, a delivery can be recorded twice.

An operation is idempotent when executing it several times produces the same effect as executing it just once.

Operation Idempotent by nature? Why
Querying the status of a shipment Yes It changes nothing
Setting the status of a shipment to DELIVERED Yes Repeating it leaves the same status
Deleting a shipment draft Yes Once deleted, it stays deleted
Creating a shipment No Every repetition creates another shipment
Adding a delivery attempt to the counter No Every repetition adds one

Those that are not idempotent by nature are made idempotent with an idempotency key: a unique identifier that the client generates and sends with the request. The server remembers the keys it has already handled.

def create_shipment(request):
    key = request.header("Idempotency-Key")

    previous = handled_keys.find(key)
    if previous is not None:
        return previous.response           # repeated request: same response

    shipment = register_shipment(request.data)
    response = {"tracking_code": shipment.code, "status": "REGISTERED"}

    handled_keys.save(key, response, expiry_hours=24)
    return response

Explanation:

  • The client sends the Idempotency-Key header with a value that is unique per operation, normally a UUID. If it retries, it sends the same value.
  • handled_keys.find checks whether that key has already been processed. If so, nothing is created: the stored response is returned. The client cannot tell the retry from the original request.
  • If the key is new, the shipment is registered and the key is saved together with the response.
  • expiry_hours=24 keeps the table from growing without limit: a retry one day later is no longer reasonable.

An important detail that the pseudocode simplifies: saving the shipment and saving the key must happen in the same transaction, and the key must have a uniqueness constraint in the database. That way, if two copies of the request reach two instances at the same time, one of the two fails on insert and returns the result of the other.

Idempotency is the pattern that makes retries safe. We will need it again, on the side of whoever receives messages, in the lesson on asynchronous communication.

  1. Pagination, rate limiting, and backpressure

These three patterns share one idea: no request and no client should be able to consume an unlimited amount of resources.

Pagination

A large merchant asks for "all my shipments for the year." With no limit, the response is hundreds of thousands of records: memory, database, and network tied up by a single request. Pagination returns the results in chunks of bounded size.

Type How it works Advantage Drawback
Offset-based "Skip 10,000 and give me 50" Simple; lets you jump to page N The database scans the 10,000 skipped rows; each page is slower
Cursor-based "Give me 50 starting from this point" Constant cost on any page Does not let you jump to an arbitrary page

For large volumes, the cursor is used. The response includes the point from which to continue:

{
  "data": [
    { "tracking_code": "RV-0048213", "status": "DELIVERED" },
    { "tracking_code": "RV-0048214", "status": "OUT_FOR_DELIVERY" }
  ],
  "next_cursor": "eyJsYXN0IjoiUlYtMDA0ODIxNCJ9",
  "has_more": true
}
  • data contains the current page (trimmed here to two items).
  • next_cursor is an opaque value: the client does not interpret it, it just sends it back in the next request.
  • has_more indicates whether there are results left.

At Rutaverde, API listings will return 50 items by default and 200 at most.

Rate limiting

Rate limiting sets how many requests a client can make per unit of time. It protects against integration errors, such as an endless loop in a merchant's system, against abuse, and against the client that, with no ill intent, hogs everyone's capacity.

Algorithm Idea Comment
Fixed window N requests per clock minute Simple; allows a double burst at the window boundary
Sliding window N requests in the last 60 seconds Fairer; somewhat more expensive
Token bucket Tokens are replenished at a fixed rate; each request spends one Allows bursts up to the size of the bucket
Leaky bucket Requests leave at a constant rate; those that do not fit are rejected Smooths the traffic

Rutaverde already has an Nginx in front of the application, and Nginx includes rate limiting:

limit_req_zone $http_x_api_key zone=per_merchant:10m rate=20r/s;

server {
    location /api/ {
        limit_req zone=per_merchant burst=40 nodelay;
        limit_req_status 429;
        proxy_pass http://rutaverde_monolith;
    }
}

Line by line:

  • limit_req_zone defines a memory zone called per_merchant, of 10 MB, where Nginx keeps count. The key for the count is $http_x_api_key, that is, the value of the X-Api-Key header: each merchant has its own counter. rate=20r/s sets the sustained rate at 20 requests per second.
  • limit_req ... burst=40 allows a burst of up to 40 requests above the rate. nodelay makes those burst requests be served immediately instead of being held back.
  • limit_req_status 429 makes the excess receive HTTP status code 429, "too many requests," instead of the 503 that Nginx uses by default.
  • proxy_pass sends whatever is accepted to the application.

A well-designed limit is communicated: it appears in the API documentation, and the 429 response carries a Retry-After header indicating how many seconds to wait. The 20 requests per second per merchant are generous: the largest current customer does not exceed 5.

Backpressure

Rate limiting protects against one specific client. Backpressure protects against the total: it is the mechanism by which a saturated component lets whoever is sending it work know, so that they slow down.

Without backpressure, an overloaded system accepts everything, queues without limit, each request takes longer, clients retry, and the load increases even more. With backpressure, the system accepts what it can serve well and rejects the rest early and explicitly:

  • Bounded queues: every internal queue has a maximum size.
  • Concurrency limit: each instance serves at most a certain number of requests at a time.
  • Early rejection: whatever exceeds the limit immediately gets a 503 with Retry-After, without consuming resources.

Serving 90% well and clearly rejecting 10% is much better than serving 100% badly. It is a direct application of P4: Everything fails, and we plan for it.

  1. CDN for static content

A CDN (Content Delivery Network) is a network of geographically distributed servers, the points of presence, that keep copies of the content and serve it from the one closest to the user. Your own server, called the origin, only receives the first request for each file.

flowchart LR
    U["Recipient in Seville"] --> P["Nearby point of presence"]
    P -->|"only if it has no copy"| O["Origin: object storage"]
    P -->|"data requests"| S["Tracking service"]

Static content is content that is the same for all users: style sheets, JavaScript code, images, fonts. A visit to the tracking page downloads about 12 static files and makes a single data call. Without a CDN, 250 visits per second are more than 3,000 requests per second against your own servers; with a CDN, only the 250 data calls arrive.

How long the CDN keeps each copy is decided by the origin with the Cache-Control header:

Cache-Control: public, max-age=31536000, immutable    <- files with a fingerprint in the name, such as app.3f9a1c.js
Cache-Control: public, max-age=300                    <- the HTML page
Cache-Control: no-store                               <- responses with data about a shipment
  • The first line allows the file to be kept for a year. It is safe because the name includes a fingerprint of its content: if the file changes, the name changes.
  • The second limits the HTML page to 5 minutes, so that a deployment propagates quickly.
  • The third forbids storing data responses. In this first phase, Rutaverde's CDN serves static content only; data queries go to the Tracking service, which will have its own cache.

Rutaverde has no CDN, and today the static files for the portal and for tracking are served by the application itself. The decision is to place a CDN in front of tracking.rutaverde.example and portal.rutaverde.example, with the static files in object storage in the cloud. Besides offloading work, the CDN absorbs part of the peaks and brings the content closer to the 20 planned cities.

  1. Autoscaling: metrics and thresholds

The previous lesson introduced the concept. Designing a policy requires four decisions.

Which metric to use. It must go up when the load goes up and go down when instances are added:

Metric Suitable for Caution
Average CPU usage Compute-bound services Useless if the limit is the database
Requests per second per instance Web services with homogeneous requests Requires knowing the capacity of one instance
Latency Protecting the requirement directly Rises for many reasons unrelated to a shortage of instances
Pending messages in a queue Queue consumers You have to decide what delay is acceptable

Which thresholds. You scale out before saturation, because a new instance takes time to start. A target of 60% CPU leaves headroom.

How long to wait. You scale out fast and in slowly. A cooldown period after each action prevents oscillation.

Which limits. A minimum that guarantees availability even when there is no load, and a maximum that protects the budget and the systems behind.

Rutaverde's policy, in an illustrative format independent of any provider:

service: tracking
instances:
  minimum: 2
  maximum: 8
metric:
  type: average_cpu
  target: 60              # percent
scale_out:
  condition: average_cpu > 60 for 2 min
  action: add 2 instances
  cooldown: 3 min
scale_in:
  condition: average_cpu < 35 for 10 min
  action: remove 1 instance
  cooldown: 10 min
scheduled:
  - name: black-friday-peak
    from: 2026-11-23
    until: 2026-12-01
    minimum: 4

Explanation:

  • minimum: 2 ensures that there are always two instances, one per zone, even if there is no traffic in the early hours. maximum: 8 caps the spending; with a hypothesis of 100 queries per second per instance, eight comfortably cover the 250 in the requirement.
  • scale_out acts early (2 minutes) and decisively (two instances at once).
  • scale_in is deliberately lazy: it waits 10 minutes and removes one at a time. The gap between 35 and 60 is the hysteresis that prevents adding and removing nonstop.
  • scheduled raises the minimum to 4 during the peak season. For a peak that is known months in advance, it makes no sense to wait for the metric to react.

The Notifications service, which will consume messages from a queue, will scale between 2 and 6 instances based on pending messages. The modular monolith, which stays in the data center, cannot have real autoscaling: it will go from 3 to 5 instances on a schedule before each peak season, by switching on virtual machines prepared in advance.

  1. The Rutaverde map: problem, pattern, and lesson

Rutaverde problem Pattern Where it is developed
A heavy report brings down shipment creation Decomposition; separate resources for Reports This lesson; load balancing; data layer
A single active instance; 40-minute manual standby Replicas behind a load balancer Load balancing
The session, the files, and the jobs live on app-01 Externalizing state This lesson
Tracking above 8 s during peaks Cache; dedicated read model Caching; data layer
A single 180-table database for everything Read/write separation; replicas; partitioning Data layer
Synchronous SMS inside the delivery confirmation Asynchronous processing with queues Asynchronous communication
App retries that could duplicate deliveries Idempotency This lesson; asynchronous communication
One merchant can saturate the API Rate limiting and pagination This lesson
Overload that ends in a total outage Backpressure This lesson; high availability
Static files consume our own capacity CDN This lesson
Fixed capacity: too much for eleven months and too little in peak season Autoscaling and scheduled scaling This lesson
The maps provider, with no timeout, blocks the application Resilience patterns High availability and resilience

Several of these patterns also have a security side: rate limiting slows down attacks and the CDN can filter malicious traffic. That perspective belongs to Module 3.

Common Mistakes and Tips

  • Collecting patterns. Every pattern added without a problem that justifies it is gratuitous complexity. The table above starts with the problem column on purpose.
  • Applying CQRS everywhere. It is valuable where reads and writes differ greatly, as in Tracking. In an ordinary back-office module it only doubles the work.
  • Retrying without idempotency. Retries without idempotency turn a network failure into duplicated data.
  • Generating a new idempotency key on every retry. It defeats the mechanism. The key identifies the operation, not the attempt.
  • Secret rate limits. A limit the client does not know about is perceived as a malfunction. Document it and respond with 429 and Retry-After.
  • Queues with no maximum size. They only delay the crash and make it worse.
  • Scaling in as fast as scaling out. It causes continuous oscillation.
  • Autoscaling with no maximum. A programming error or an attack can turn into an exorbitant bill.
  • Tip: before adopting a pattern, complete the sentence "this will cost us...". If you cannot finish it, you do not know the pattern well enough yet.

Exercises

Exercise 1

State which pattern or patterns you would apply to each situation and why:

  1. The merchant portal shows a price list by city that changes once a month and is consulted thousands of times a day.
  2. When a delivery photo is uploaded, the app waits for the server to generate three thumbnails before considering the delivery confirmed.
  3. A badly programmed online store queries the status of its 5,000 open shipments every 10 seconds.
  4. The logo and the fonts of the tracking page are served from the monolith.

Exercise 2

The courier app sends the operation "record a failed delivery attempt," which increments the shipment's attempt counter by one. Because of a bad connection, the same request arrives three times.

  1. What happens if the operation is not idempotent?
  2. Describe how to make it idempotent.
  3. Who should generate the key, and at what point?

Exercise 3

With the Nginx configuration from this lesson (20 requests per second and a burst of 40), a merchant sends 30 requests per second for 10 seconds in a row.

  1. How many requests does it send in total?
  2. Roughly how many are accepted and how many get a 429?
  3. From which second do the rejections start?

Solutions

Solution 1

  1. Cache. Data that almost never changes and is read constantly is the ideal case. A one-hour expiration is more than enough.
  2. Asynchronous processing. The confirmation must respond as soon as the photo is saved; the thumbnails are generated afterwards from a message in a queue.
  3. Rate limiting, to protect the other clients, and pagination, so that each query is bounded. It is also worth offering the merchant a better alternative than constantly asking; we will see it when we deal with events.
  4. CDN. It is static content, identical for all users.

Solution 2

  1. The counter goes up by three instead of one. The shipment could reach the maximum number of attempts and be returned to the merchant for no reason.
  2. The app sends an idempotency key with the operation. The server, in a single transaction, checks whether the key exists; if it does not, it increments the counter and saves the key; if it does, it returns the previous response without touching the counter. Another option is to redesign the operation so that it is idempotent by nature: instead of "add one," "record the attempt with identifier X," and the counter is obtained by counting distinct attempts.
  3. The app, at the moment the courier taps the button, before the first send. The key is stored together with the pending operation and is reused in all retries, including those that happen after coverage is recovered.

Solution 3

  1. 30 × 10 = 300 requests.
  2. The sustained rate allows 20 × 10 = 200, and the burst, 40 more. About 240 are accepted and about 60 are rejected.
  3. Every second there are 10 requests in excess of the rate, which gradually use up the burst of 40. It runs out after 4 seconds: from the fifth second on, about 10 requests per second are rejected. The behavior is the desired one: a short burst is tolerated; a sustained excess is not.

Conclusion

Scalable design patterns are solutions with a name, a context, and a price. We have placed on the map the five that form the backbone of the module (replicas behind a load balancer, cache, read/write separation, asynchronous processing, and partitioning) and we have developed those that will not have a lesson of their own. Externalizing state makes horizontal scaling possible; idempotency makes retries safe; pagination, rate limiting, and backpressure prevent a request, a client, or a peak from consuming resources without limit; the CDN takes static content off your own servers; and autoscaling adjusts capacity to demand.

The Rutaverde platform now has its first new pieces: an externalized session, a mono-batch-01 instance for scheduled jobs, idempotency keys on write operations, a limit of 20 requests per second per merchant, a CDN for static files, and a scaling policy for Tracking.

All of this rests on an assumption we have not yet built: that there are several instances and something that distributes the requests among them. That something is the load balancer, and it is the topic of the next lesson.

© Copyright 2026. All rights reserved