Verdalia is now fast and has capacity for 1,000 users. What is missing is the quality the business gave the most weight to in Module 1: availability. A system spread across eight machines has more things that can fail than one hosted on a single machine, and it will only be more reliable if it is designed so that the failure of one piece does not stop the whole. In this lesson you will learn to calculate a system's availability from that of its components, to locate single points of failure, to eliminate them with redundancy and failover, and to build applications that degrade instead of going down. Verdalia will decide which risks it eliminates and which it accepts, record it in ADR-006, and switch off a server in the middle of a load test. This lesson closes Module 4.
Availability in Series and in Parallel
In Module 1 we defined availability and the table of “nines.” Now we are interested in another question: how the availability of several components combines.
What It Depends On
A component's availability depends on two times: how long it takes to fail and how long it takes to work again.
There are, therefore, two ways to improve it: fail less or recover sooner. The second is usually cheaper. And the recovery time starts counting when the failure happens, not when someone discovers it: it includes the detection time.
In Series
Several components are in series when all of them are needed. If any one fails, the whole fails. Their availabilities multiply:
Three 99.9% components in series give 99.7%. The whole is always worse than the worst of its components, and every piece added to the chain makes it worse.
In Parallel
Several components are in parallel when it is enough for one of them to work. The whole fails only if all of them fail at once, so the probabilities of failure multiply:
Two 99% components in parallel give 99.99%. The formula has a condition that is easily forgotten: the failures must be independent. Two servers plugged into the same power strip, or with the same bug in the code, fail at the same time, and redundancy does not protect against that.
Single Points of Failure
A single point of failure is a component whose breakdown stops the system. To find them on a diagram, a simple method is enough: cross out each element, one by one, and ask whether a customer could complete a purchase without it.
You have to cross out more things than are drawn:
| What to review | Examples |
|---|---|
| Machines and processes | The load balancer, the database primary |
| Connections | The private network, the data center's internet access |
| External services | The payment gateway, DNS, the email provider |
| What the redundant pieces share | The data center, the power supply, the code version |
| People | The only person who knows how to perform a procedure |
Redundancy
Redundancy consists of having more components than strictly necessary, so that the failure of one does not stop the service.
| Model | How it works | Advantage | Drawback |
|---|---|---|---|
| Active-active | All the copies serve traffic at the same time | All the capacity is used; the failure of one is barely noticed | Requires the copies to be stateless, or to synchronize their state |
| Active-passive | One copy serves and another waits, ready | Simple; suitable for stateful components | You pay for a machine that does no work; the handover takes time |
| N+1 | If N copies are needed for the load, you have N+1 | Redundancy at low cost | Only covers the failure of one copy at a time |
Verdalia's three application servers work active-active and follow the N+1 model: two are enough for 1,000 users, and there are three.
Failover
Failover is the replacement of a broken component by its standby copy. It has three steps:
| Step | What happens | Difficulty |
|---|---|---|
| Detection | Someone, or something, notices that the component does not respond | Telling a breakdown apart from a passing slowdown |
| Promotion | The standby takes over the role of the broken component | If it has state, it must be up to date |
| Redirection | Traffic is directed to the standby | Customers should not have to change anything |
For redirection, a floating IP, or virtual IP, is used: an address that belongs to no specific machine, and that is assigned to whichever one is active at each moment. Customers always connect to the same address.
Split-Brain
Automatic failover carries a risk. Suppose the active and the passive stop seeing each other because of a failure in the network that joins them, even though both are working. The passive believes the active has gone down and promotes itself. Now there are two actives, and each believes it is the only one. That is split-brain. In a stateless load balancer it is a nuisance. In a database it is serious: two primaries accept different writes, and afterwards there is no simple way to merge them. It is a network partition like the ones we saw with the CAP theorem.
The solutions consist of preventing a node from deciding on its own: a third node that breaks the tie, so that only the one that sees the majority gets promoted, or a mechanism that shuts down the old active before promoting the new one. That is why automatic database failover requires specialized tools, and why many small teams do it by hand.
Fault Tolerance in the Application
Redundancy protects against machine breakdowns. The rest depends on the application. In Module 3 we studied three techniques that we will not repeat: timeouts, retries with exponential backoff, and circuit breakers. They are completed with four more:
| Technique | What it consists of | Example at Verdalia |
|---|---|---|
| Graceful degradation | If a secondary function fails, the system does without it and carries on | Without the cache, the product page is read from the database |
| Bulkheads | Resources are split into compartments, so that one problem does not consume them all | A maximum of 3 processes per server waiting on PagoRaíz |
| Rate limiting | A maximum number of requests per client and period is set | 2 searches per second per IP address |
| Load shedding | When the system is saturated, it rejects part of the traffic early in order to serve the rest well | Searches are rejected before order confirmations |
The name of bulkheads comes from ships, whose hull is divided into compartments so that a leak does not sink it. The incident of November 26 was a textbook case: the email provider was slow and the store's 4 processes ended up waiting on it. A bulkhead would have reserved processes for the catalog.
Degradation is designed component by component:
| If this fails... | The store... |
|---|---|
| The database replica | Reads the catalog from the primary |
| The cache | Reads from the database, more slowly |
| RabbitMQ or the notification service | Confirms the order; the email goes out later |
| PagoRaíz | Keeps the cart and asks the customer to try again in a few minutes |
| The CDN | Serves the images from the object storage |
Zones, Regions, and Chaos Engineering
Zones and Regions
Cloud providers organize their data centers into regions, which are geographic areas, and each region into several availability zones: separate data centers, with independent power and network, but close to one another and well connected. Spreading a system across zones protects against the failure of a data center. Spreading it across regions protects against a bigger disaster, in exchange for more latency and more complexity. Verdalia's eight machines are in the same data center of its provider. We will come back to that in Module 6.
Chaos Engineering and Drills
A recovery mechanism that has never been tested is a hypothesis. Chaos engineering consists of causing failures on purpose, in a controlled way, to check that the system withstands them. Its most accessible version is the failure drill, or game day: the team gets together, causes a specific breakdown, and observes.
| Step | Content |
|---|---|
| 1. Hypothesis | “If an application server is switched off, the store keeps selling” |
| 2. Scope | What is going to be broken, in which environment, and how the test is stopped |
| 3. Execution | The failure is caused, with real or simulated load |
| 4. Measurement | How long the interruption lasted and what the customers noticed |
| 5. Improvement | What did not work is fixed, and the drill is repeated |
You start in a test environment. You only move to production when there is confidence and a quick way to stop.
Calculating Availability in Python
import math
def availability(hours_between_failures, recovery_hours):
"""Fraction of the time a component is working."""
return hours_between_failures / (hours_between_failures + recovery_hours)
def series(*components):
"""All are needed: the availabilities multiply."""
return math.prod(components)
def parallel(*components):
"""It is enough for one to work: the probabilities of failure multiply."""
return 1 - math.prod(1 - component for component in components)
def report(name, value):
minutes = (1 - value) * 30 * 24 * 60
print(f" {name:28} {value * 100:8.4f}% {minutes:6.1f} min per month")
MACHINE = availability(4380, 4) # two breakdowns a year; 4 hours to replace it
PROCESS = availability(720, 0.5) # one hang a month; half an hour to restart
PAGORAIZ = 0.9995 # according to its service agreement
DEPLOYMENTS = 1 - 40 / (30 * 24 * 60) # two 20-minute downtimes a month
print("January: everything on verdalia-prod-01")
report("Total", series(MACHINE, PROCESS, DEPLOYMENTS, PAGORAIZ))
app_server = series(MACHINE, PROCESS)
balancing = parallel(MACHINE, MACHINE)
application = parallel(app_server, app_server, app_server)
database = availability(4380, 0.5) # manual promotion of the replica: 30 minutes
redis = availability(4380, 1) # reinstallation on another machine: 1 hour
print("March: distributed architecture")
report("Load balancers, in parallel", balancing)
report("Application, 3 in parallel", application)
report("Database", database)
report("Redis", redis)
report("PagoRaiz", PAGORAIZ)
report("Total", series(balancing, application, database, redis, PAGORAIZ))Output:
January: everything on verdalia-prod-01 Total 99.6971% 130.8 min per month March: distributed architecture Load balancers, in parallel 99.9999% 0.0 min per month Application, 3 in parallel 100.0000% 0.0 min per month Database 99.9886% 4.9 min per month Redis 99.9772% 9.9 min per month PagoRaiz 99.9500% 21.6 min per month Total 99.9157% 36.4 min per month
Explanation:
availabilityapplies the formula from the first section. 4,380 hours is half a year. The breakdown figures are Lucía's estimates, not measurements.seriesandparallelare the two formulas.math.prodmultiplies all the values it receives.- In January, everything was in series: the machine, the store's process, the deployment downtimes, and PagoRaíz.
- In March, the load balancers and the application servers are in parallel. The database and Redis are still a single piece each, but the database recovers in half an hour, counting detection, because there is a replica to promote.
- RabbitMQ does not appear, because its failure does not prevent buying.
Interpretation:
- The estimate goes from 131 minutes of downtime a month to 36. The 99.9% target allows 43.2.
- The application's 100% is a rounding, and an optimistic one at that. The formula assumes independent failures. A bug in the code, deployed on all three servers, would stop them at the same time.
- The redundant pieces have stopped counting. Of the 36 minutes, 21.6 belong to PagoRaíz, 9.9 to Redis, and 4.9 to the database. Availability is now decided by the pieces that are not duplicated.
- It is a model. The real availability will be known at the end of the month, by measuring.
A Rate Limiter
The token bucket is the most widespread rate limiting algorithm. Each client has a bucket of tokens, and each request spends one. The bucket refills at a constant rate, up to a maximum. If it is empty, the request is rejected.
class TokenBucket:
"""Rate limiter: each request spends one token."""
def __init__(self, capacity, tokens_per_second):
self.capacity = capacity
self.tokens_per_second = tokens_per_second
self._tokens = capacity
self._last = 0.0
def allow(self, now):
elapsed = now - self._last
self._tokens = min(self.capacity, self._tokens + elapsed * self.tokens_per_second)
self._last = now
if self._tokens >= 1:
self._tokens -= 1
return True
return False
bucket = TokenBucket(capacity=5, tokens_per_second=2)
# A program fires 10 searches per second for 3 seconds
for second in range(3):
times = [second + n / 10 for n in range(10)]
allowed = sum(1 for moment in times if bucket.allow(moment))
print(f"Second {second}: {allowed} allowed, {10 - allowed} rejected with code 429")
# A normal customer makes one search every 8 seconds
allowed = sum(1 for n in range(1, 6) if bucket.allow(10 + 8 * n))
print(f"Normal customer: {allowed} allowed out of 5")Output:
Second 0: 6 allowed, 4 rejected with code 429 Second 1: 2 allowed, 8 rejected with code 429 Second 2: 2 allowed, 8 rejected with code 429 Normal customer: 5 allowed out of 5
Explanation:
capacityis the size of the bucket: the burst that is tolerated.tokens_per_secondis the sustained rate that is allowed.allowuses no timer. Every time a request arrives, it calculates the tokens generated since the previous one and adds them, without exceeding the capacity.- The abusive program spends the 5 initial tokens in the first second. After that it only gets the 2 per second that keep being generated. The rest receive HTTP code 429, Too Many Requests.
- The normal customer never notices the limit.
In the real store there is one bucket per IP address, and the buckets are kept in Redis, because requests from the same client reach different servers. Nginx offers this function with the limit_req_zone and limit_req directives.
Verdalia: Inventory, ADR-006, and Drills
Inventory of Single Points of Failure
| Component | Single point? | If it fails... | Decision |
|---|---|---|---|
Load balancer, verdalia-lb-01 |
Yes | The store becomes unreachable | Duplicated |
| Application servers | No: there are 3 and 2 are enough | The others take over the load | |
| PostgreSQL, primary | Yes | No purchases possible | Manual promotion of the replica |
| PostgreSQL, replica | No | The catalog reads from the primary | |
Redis, on verdalia-aux-01 |
Yes | No sessions or carts: no purchases possible | Accepted |
RabbitMQ, on verdalia-aux-01 |
Yes, but it does not prevent buying | Emails are delayed | Accepted |
| PagoRaíz | Yes, external | No payments possible | Accepted, with degradation |
| Object storage and CDN | No: the provider duplicates them | ||
| Data center | Yes | Everything stops | Accepted until Module 6 |
| Lucía | Yes | Nobody else knows how to deploy or promote the replica | Íker rehearses the procedures |
ADR-006
ADR-006: Duplicate the load balancer and prepare the manual promotion of the replica, and accept Redis, RabbitMQ, and PagoRaíz as single points of failure
Status: Accepted
Date: 2027-03-10
Participants: Marta decides; Íker and Lucía consulted; Andrés informed, and he accepts the business risks.
Context
The distributed architecture has five single points of failure: the load balancer, the PostgreSQL primary, Redis, RabbitMQ, and PagoRaíz. Scenario QS-3 calls for an interruption under 5 minutes and a monthly availability of 99.9%. The campaign starts on March 20, the budget is €500 a month on an annual average, and there is no automatic outage detection yet.
Options considered
- A. Duplicate everything, with automatic failover. Maximum availability. It requires tools the team does not know, there is no time to test them, and a badly configured automatic failover can cause a split-brain in the database.
- B. Duplicate nothing else. No cost. The failure of the load balancer would stop the store for hours.
- C. Duplicate what is simple and cheap, prepare by hand what has state, and accept the rest.
Decision
We adopt option C. There will be a second load balancer,
verdalia-lb-02, in active-passive, with a floating IP and automatic failover. The replicaverdalia-db-02will be promoted to primary manually, with a written procedure rehearsed by two people. Replication will remain asynchronous. Redis, RabbitMQ, and PagoRaíz are accepted as single points of failure.Consequences
Positive:
- The failure of a load balancer or an application server resolves itself, in seconds.
- The failure of the primary is resolved in minutes, not hours.
- The additional cost is €33 a month.
Negative:
- The failure of the primary exceeds the 5 minutes of scenario QS-3: manual promotion takes between 12 and 19 minutes, plus the detection time.
- When the replica is promoted, the writes of the last few moments may be lost.
Accepted risks:
- The loss of
verdalia-aux-01prevents buying until Redis is reinstalled on another machine, about an hour. Redis keeps the carts on disk and recovers them.- A PagoRaíz outage prevents paying. The store keeps the carts.
- A charged order may not be on record after a promotion. It would be detected when reconciling with PagoRaíz's records.
Review conditions
It will be reviewed when the store moves to a cloud platform, to consider managed services with automatic failover; if an outage of the primary or of Redis happens during the campaign; and when automatic outage detection exists.
Lucía set up verdalia-lb-02, size S, on Friday, March 12. The two load balancers watch each other, and the passive one takes the floating IP when the active one stops responding. The promotion procedure is in docs/runbooks/replica-promotion.md.
The Drills
| Drill | Date | Result | QS-3: under 5 minutes |
|---|---|---|---|
| Promotion of the replica, in testing | March 12 | Lucía, 12 minutes. Íker, 19 minutes | Not met |
| Stopping the active load balancer, in testing | March 15 | 6 seconds of interruption | Met |
Switching off verdalia-app-02, with 1,000 users |
March 17 | 12 seconds of partial errors; 23 failed requests | Met |
The third was done during the final load test. At 11:42 a.m., Lucía switched off verdalia-app-02 without warning Íker. Nginx removed it after three failures and resent the reads to the other servers. 23 requests failed, the ones in progress on that machine. The store never stopped accepting orders, and the 95th percentile rose from 560 to 690 ms with two servers.
The drills taught two things that were not on any diagram. The promotion procedure had a step that only Lucía understood, and it was rewritten. And nobody would have found out about verdalia-app-02 being switched off had it not been caused on purpose: the store tolerated it, but it did not raise the alarm.
Module 4 Review
The Final Test
On Wednesday, March 17, Lucía ran the final test: 1,000 users for 60 minutes, in the test environment.
| Measure | Result | Target |
|---|---|---|
| 95th percentile of the catalog | 560 ms | Under 800 ms |
| 99th percentile of the catalog | 1.5 s | Under 2 s |
| Requests with errors | 0.08% | |
| Ramp from 40 to 1,000 users in 30 minutes | Withstood, with the three servers already running | |
| Time to add a fourth server | 1 hour and 50 minutes, by hand | Under 15 minutes |
The Status of the Scenarios
| Scenario | Status | Detail |
|---|---|---|
| QS-1, performance | Met in testing | 560 ms and 1.5 s with 1,000 users |
| QS-2, scalability | Partial | The load is withstood with capacity installed in advance. Expanding it takes almost two hours of manual work |
| QS-3, availability | Partial | Met against the failure of a server or a load balancer. Not met against the failure of the primary. The monthly 99.9% is an estimate |
| QS-4, security | Pending | The 2 credentials are still in config.py, and now they are copied on three servers |
| QS-5, maintainability | Met once, in Module 2 | No changes |
| QS-6, operability | Pending | The first rolling deployment in production, on Tuesday, March 16, had no downtime, but it took 40 minutes of manual work and there is no rehearsed rollback |
The Cost
| Component | Machine | Size | Monthly cost |
|---|---|---|---|
| Load balancers | verdalia-lb-01 and verdalia-lb-02 |
S | €60 |
| Floating IP | €3 | ||
| Application servers | verdalia-app-01, -02, and -03 |
M | €180 |
| PostgreSQL, primary and replica | verdalia-db-01 and verdalia-db-02 |
M | €120 |
Redis, RabbitMQ, and notification-service |
verdalia-aux-01 |
M | €60 |
| Object storage | €4 | ||
| CDN | €12 | ||
| Total during the campaign | €439 |
Outside the campaign, two application servers are enough, and the cost drops to €379. With three months of campaign a year, the annual average is €394, below the €500 limit. The cost per order comes to €0.16 during the campaign and €0.19 outside it, below the €0.25 target. The test environment, rented by the day, cost €210 in total. In January, Verdalia paid €120 a month for a server that failed at 250 users.
The Architecture
flowchart TB
subgraph application["Application servers, stateless"]
app1["verdalia-app-01"]
app2["verdalia-app-02"]
app3["verdalia-app-03"]
end
subgraph aux["verdalia-aux-01"]
redis[("Redis")]
rabbit["RabbitMQ"]
notif["notification-service"]
end
customers["Customers"] --> cdn["CDN"]
cdn --> objects[("Object storage")]
customers --> ip["Floating IP"]
ip --> lb1["verdalia-lb-01, active"]
ip -.-> lb2["verdalia-lb-02, passive"]
lb1 --> app1
lb1 --> app2
lb1 --> app3
application --> db1[("verdalia-db-01, primary")]
application --> db2[("verdalia-db-02, replica")]
db1 -->|"Asynchronous replication"| db2
application --> pagoraiz["PagoRaíz"]
application --> redis
application --> rabbit
rabbit --> notif
notif --> mail["Email provider"]
The Start of the Campaign
The spring campaign started on Saturday, March 20. The email with the offer went out at 10:30 a.m., the same time as the one on the day before Mother's Day the previous year. At 11:10 a.m. there were 870 simultaneous users, the peak of the day. The store did not go down. Between 10:30 a.m. and 1:30 p.m., 141 orders were confirmed.
There was one incident. At 12:05 p.m., verdalia-app-03 ran out of disk space: the activity logs, which are still local files, had filled it up. Nginx removed the server and the store carried on with the other two. No customer noticed. Neither did Lucía, who discovered it 40 minutes later, while reviewing the Nginx logs by hand. Fault tolerance worked. Detection did not.
Common Mistakes and Tips
- Duplicating the machines and forgetting what they share. Two servers in the same data center, with the same code and the same configuration, share many failures.
- Trusting a standby that has never been tested. A replica nobody has promoted is a hypothesis.
- Automating database failover without understanding split-brain. A manual, rehearsed handover is preferable to an automatic one that can corrupt the data.
- Leaving detection time out of the count. A 12-minute recovery that starts half an hour after the failure lasts 42.
- Retrying when the system is saturated. Retries add load. They are combined with limits and circuit breakers.
- Accepting risks without writing them down. A consciously accepted risk is recorded in an ADR, with its owner. An ignored one shows up by surprise.
- Depending on a single person. Critical procedures must be written down and rehearsed by at least two people.
- Practical tip. When you finish a design, cross out each element of the diagram, one by one, and write down what the customer would see. If you do not know, you already have your next drill.
Exercises
Exercise 1: Calculate the Availability
Using the functions from the lesson, calculate the availability of the whole and the minutes of downtime per month in two cases: if Verdalia contracted a second payment gateway, also at 99.95%, and could charge through either of the two; and if, in addition, it duplicated Redis with automatic failover, so that it ended up in parallel. Which of the two improvements pays off more?
Exercise 2: Find the Single Points of Failure
An online academy has this architecture: a load balancer managed by its cloud provider, 4 application servers in the same zone, a database with a replica in another zone and automatic failover, and a file server where students upload their assignments. Only one administrator knows the password to the provider's console. Identify the single points of failure.
Exercise 3: Design the Degradation
PagoRaíz stops responding on a campaign Saturday, for 20 minutes. Describe what the customer should see and which techniques from this lesson and from Module 3 come into play.
Solutions
Solution to Exercise 1
payments = parallel(PAGORAIZ, PAGORAIZ)
report("With two gateways", series(balancing, application, database, redis, payments))
report("And with Redis duplicated", series(balancing, application, database, parallel(redis, redis), payments))Output:
The second gateway saves 21.6 minutes a month, and duplicating Redis, a little under 10. The first pays off more, because PagoRaíz was the component contributing the most downtime. It is always best to start with the weakest link. The calculation says nothing about cost: integrating a second gateway is a development project, not one more machine.
Solution to Exercise 2
- The file server. It is a single machine, and it holds data that exists nowhere else.
- The application servers' zone. All four are in the same one. If that zone fails, the database survives in the other, but no application is left to use it.
- The administrator. If they cannot be reached, nobody can act.
- The cloud provider, as a risk that is normally accepted.
The managed load balancer and the database are not. Common mistake: counting the servers and taking the redundancy for granted without looking at what they share.
Solution to Exercise 3
The customer should be able to browse, search, and fill the cart as normal. At checkout, they should see within a few seconds a clear message: payment is not available right now, their cart has been saved, and they can try again in a few minutes. The techniques involved:
- Timeout on the call to PagoRaíz, so that the customer does not wait indefinitely.
- Circuit breaker, which after several failures stops calling the gateway and responds immediately.
- Bulkhead, which limits the processes waiting on PagoRaíz, so that the catalog keeps being served.
- Graceful degradation: the store loses payment, not the rest of its functions.
- Idempotency key, so that the customer's retries do not produce two charges.
What must not happen is the whole store stopping because of the outage of an external service.
Conclusion
In this lesson you have learned to calculate a system's availability: components in series reduce it and components in parallel increase it, as long as their failures are independent. You have learned to locate single points of failure, to eliminate them with redundancy and failover, and to recognize the risk of split-brain. You have completed the fault tolerance techniques with graceful degradation, bulkheads, rate limiting, and load shedding. And you have seen that a recovery mechanism is only reliable after a drill.
This lesson closes Module 4. At the end of January, Verdalia was a €120 server that failed at 250 users. On March 20 it served 870 without going down, with a 95th percentile of 560 ms in the tests with 1,000, for €439 a month. The path has followed an order worth remembering: first the direction was decided, recorded in ADR-005; then the store was optimized and cached, so as to need 3 servers instead of 7; then the store was spread out behind a load balancer and the database was given a machine of its own with a replica; and at the end it was decided, in ADR-006, which failures are eliminated and which are accepted. Not everything is solved: expanding capacity is still manual and slow, the failure of the primary exceeds five minutes, and nobody finds out about breakdowns until they go looking.
And there is a consequence we have not looked at. Where there was one machine there are now eight, connected by an internal network over which traffic travels unencrypted. Redis asks for no password. The two credentials in config.py are still in the repository, and now they are copied on three servers. The system withstands more, but it offers more surface to anyone who wants to attack it. That is what Module 5 is about, and it starts with the lesson “Security Principles.”
