Verdalia has found out late about everything that has happened to it. About the outage on the day before Mother's Day, after 25 minutes, from a customer on social media. About the full disk on verdalia-app-03, after 40 minutes, because Lucía checked the logs by hand. About the empty backups, after 22 nights. The system tolerates more and more failures without help, and that makes it quieter. In this lesson you will learn the difference between monitoring and observing, the three types of signal a system emits, and how quality targets are turned into numbers that watch themselves. You will see how to design alerts that deserve to wake someone up, and how to learn from an incident without looking for someone to blame. Verdalia will measure scenario QS-3, the last one left, and we will review Module 6.
One warning: activity logs easily collect personal data. What is logged, how long it is kept, and who can consult it must be reviewed with legal and compliance advice (GDPR).
Monitoring vs. Observability
Monitoring is watching signals chosen in advance, to know whether the system is fine. It answers known questions: is it up? Is there disk left? Observing is being able to understand what is happening inside the system from what it emits, including problems nobody anticipated. It answers new questions: why do orders with express shipping fail, and only since 11:40 a.m.?
| Monitoring | Observability | |
|---|---|---|
| Question | Does it work? | Why doesn't it work? |
| Problems it covers | The anticipated ones | The unanticipated ones too |
| Built with | Checks and thresholds | Rich signals, which can be cross-referenced and filtered |
| Result | An alert | An explanation |
They are not alternatives. Monitoring warns, and observability lets you understand the warning. Signals come in three types, the so-called three pillars.
Metrics
A metric is a number measured over time. It takes little space, is kept for months, and is the basis of alerts and dashboards.
| Type | What it is | Example |
|---|---|---|
| Counter | A value that only grows. What matters is its growth rate | Requests served, orders confirmed |
| Gauge | A value that goes up and down | Messages in a queue, replicas running |
| Histogram | Distributes observations into buckets, to calculate percentiles | Duration of requests |
Metrics carry labels, which allow breaking them down: the route, the response code. A label with thousands of distinct values, such as the customer identifier, multiplies the series and the cost. That detail goes to the logs.
Three guides help decide what to measure:
| Method | For what | What it measures |
|---|---|---|
| RED | Services that serve requests | Rate of requests, errors, and duration |
| USE | Resources: processor, memory, disk, and connections | Utilization, saturation, and errors |
| The four golden signals | Any user-facing system | Latency, traffic, errors, and saturation |
Saturation is the one that warns first: a growing waiting queue announces the problem when the errors have not yet started.
Logs
A log is the record of an event, with its moment and its context. The metric says that 2% of orders fail. The log says which ones, and with what error.
| Practice | Reason |
|---|---|
| Structured, in JSON | A program can filter by field. A free-form sentence has to be deciphered with regular expressions |
| With a level | DEBUG, INFO, WARNING, ERROR, and CRITICAL. In production, INFO and above are written |
| With a correlation ID | An identifier created when the request comes in and traveling with it through every component. It joins the lines of the same order |
| To standard output | The platform collects them. The application manages no files |
| Centralized | They are consulted in one place, not on each machine |
| With a defined retention | They are deleted after a period |
| Without personal data or secrets | What was decided in the lesson “Data Protection” |
import contextvars
import json
import logging
import sys
import uuid
correlation_id = contextvars.ContextVar("correlation_id", default="-")
class JsonFormatter(logging.Formatter):
"""Turns each log record into one line of JSON."""
def format(self, record):
data = {
"time": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname,
"service": "store",
"message": record.getMessage(),
"correlation_id": correlation_id.get(),
}
data.update(getattr(record, "fields", {}))
return json.dumps(data, ensure_ascii=False)
def configure_logging(level=logging.INFO):
output = logging.StreamHandler(sys.stdout) # to standard output, not to a file
output.setFormatter(JsonFormatter())
logging.basicConfig(level=level, handlers=[output], force=True)
def start_request(headers):
"""Reuses the identifier that arrives with the request, or creates a new one."""
correlation_id.set(headers.get("X-Correlation-Id") or uuid.uuid4().hex[:12])
logger = logging.getLogger("verdalia.orders")
def confirm_order(order_id, amount, payment_accepted):
logger.info("Confirmation started", extra={"fields": {"order_id": order_id}})
if not payment_accepted:
logger.warning("Payment declined", extra={"fields": {"order_id": order_id}})
return
logger.info("Order confirmed",
extra={"fields": {"order_id": order_id, "amount": amount, "duration_ms": 912}})
configure_logging()
start_request({"X-Correlation-Id": "c4f1a9e2b7d0"})
confirm_order(48213, 44.88, payment_accepted=True)
start_request({})
confirm_order(48214, 120.0, payment_accepted=False)
logger.debug("Not written: the configured level is INFO")Output. The date and the second identifier change on every run:
{"time": "2027-09-14T12:03:21", "level": "INFO", "service": "store", "message": "Confirmation started", "correlation_id": "c4f1a9e2b7d0", "order_id": 48213}
{"time": "2027-09-14T12:03:21", "level": "INFO", "service": "store", "message": "Order confirmed", "correlation_id": "c4f1a9e2b7d0", "order_id": 48213, "amount": 44.88, "duration_ms": 912}
{"time": "2027-09-14T12:03:21", "level": "INFO", "service": "store", "message": "Confirmation started", "correlation_id": "e24e2ca7b3df", "order_id": 48214}
{"time": "2027-09-14T12:03:21", "level": "WARNING", "service": "store", "message": "Payment declined", "correlation_id": "e24e2ca7b3df", "order_id": 48214}Explanation:
contextvars.ContextVarholds a value specific to each request in progress. It avoids passing the identifier as a parameter through every function.JsonFormatterinherits fromlogging.Formatterand overridesformat. It builds a dictionary with the fixed fields, adds whatever arrives infields, and turns it into one line.configure_loggingsends everything to standard output.force=Truereplaces any previous configuration.start_requestruns when each request is received. If the header brings an identifier, it keeps it. The store adds it to its calls to thenotification-serviceand to the messages it publishes to the queue, so that the worker writes its logs with the same value.- The
extraparameter ofloggingadds attributes to the record. Here, a dictionary with the event's fields. - The order identifier is logged, not the customer's email or address. A declined payment is a
WARNING: it is an expected business event, not a system failure.
Searching for c4f1a9e2b7d0 in the central store returns the complete history of order 48213, in the store and in the worker. And the logs no longer fill any disk: they leave the container as soon as they are written, and are kept for 30 days.
Distributed Traces
A trace reconstructs the journey of a request through several components, with the duration of each step.
| Concept | What it is |
|---|---|
| Trace | The complete journey of a request, with a unique identifier |
| Span | One operation within the trace: an HTTP call, a query, or a send to the queue. It has a start, a duration, and a parent span |
| Context propagation | The trace identifier and the span identifier travel in a header of every call, so that the next component links its spans |
| Sampling | Only a fraction of the traces is kept, because keeping them all is expensive |
In the confirmation of an order, which takes 965 ms, the trace would show four spans: finding the order, 12 ms; charging at PagoRaíz, 810 ms; saving the order and deducting stock, 95 ms; and publishing to the queue, 8 ms. The charge explains 84% of the time, and it does not depend on Verdalia.
The trace answers a question metrics and logs answer poorly: where the time goes. Its value grows with the number of services. In a system with twenty it is essential. In one with two, the correlation ID covers almost everything.
Tools
| Tool | Pillar | What it does |
|---|---|---|
| Prometheus | Metrics | Collects the metrics each service exposes, stores them as time series, queries them with PromQL, and evaluates alerting rules |
| Grafana | Visualization | Dashboards on top of Prometheus and other sources |
| OpenTelemetry | All three | An open standard and a set of libraries to instrument the code, without tying yourself to a vendor |
| Loki | Logs | Log store, indexed by labels. Inexpensive |
| ELK stack: Elasticsearch, Logstash, and Kibana | Logs | Full-text search. Powerful, and demanding to operate |
| Jaeger and Grafana Tempo | Traces | Trace storage and querying |
| Managed services | All three | Amazon CloudWatch, Azure Monitor, Google Cloud Observability. Several providers also offer managed Prometheus and Grafana |
One rule shapes the choice: the system that watches must not go down with the one being watched.
| Verdalia's decision | Reason |
|---|---|
| Adopts NubeAtlas's managed observability service, which is Prometheus-compatible, shows Grafana dashboards, and centralizes the logs | The queries, the rules, and the dashboards are standard, and there is nothing to operate |
| Adopts a synthetic check from an external service | It must work even if NubeAtlas fails |
| Discards installing Prometheus and Grafana on its own | One more machine to maintain, which would also have to be watched |
| Discards the ELK stack | It is out of proportion for the store's volume |
| Postpones distributed traces | There are two deployable pieces, and the correlation ID joins them. To be reviewed if a second service is extracted, or if a slowness appears that cannot be located |
Instrumenting the Store
Instrumenting is adding to the code what it needs to emit signals. The fragment uses the prometheus_client library. It is a reference: it needs the library installed and the store running.
# verdalia/orders/adapters/web.py (fragment)
from prometheus_client import Counter, Histogram
ORDERS = Counter("verdalia_orders", "Order confirmations, by result", ["result"])
DURATION = Histogram("verdalia_confirmation_seconds", "Duration of an order confirmation",
buckets=(0.25, 0.5, 1, 2, 4, 8))
@app.route("/orders/confirm", methods=["POST"])
def confirm():
with DURATION.time():
try:
confirmed = order_service.confirm(order_id_from_session())
except Exception:
ORDERS.labels(result="error").inc()
raise
ORDERS.labels(result="confirmed" if confirmed else "payment_declined").inc()
return result_page(confirmed)Countercreates a counter with one label,result, which only takes three values. Prometheus publishes it under the nameverdalia_orders_total.Histogramdistributes the durations into buckets. The boundaries are chosen around the target: a histogram whose buckets jump from 1 to 10 seconds is of little use if the target is 2.with DURATION.time()measures how long the block takes, also if it ends with an exception.- The declined payment is counted separately from the error. Mixing them would trigger the alerts every time a customer runs out of funds.
- The metrics are exposed on the
/metricsroute, which the observability service scrapes every 30 seconds. With several Gunicorn processes, the library must be configured in its multiprocess mode.
The general metrics, such as verdalia_requests_total and verdalia_duration_seconds, with the labels route and code, are added by a single point of the application for every route. The catalog's 95th percentile is obtained with this PromQL query:
histogram_quantile(
0.95,
sum by (le) (rate(verdalia_duration_seconds_bucket{route="/catalog"}[5m]))
)rate(...[5m]) calculates the per-second rate of each bucket over the last five minutes. sum by (le) adds up those of every replica, keeping the le label, which is the bucket boundary. histogram_quantile estimates the percentile. Percentiles cannot be averaged: the mean of the 95th percentiles of six replicas is not the 95th percentile of the whole. That is why the buckets are added up first and the calculation comes afterward.
SLI, SLO, SLA, and Error Budget
| Concept | What it is | Example |
|---|---|---|
| SLI, service level indicator | A measure of what the user perceives. Almost always, a ratio between good events and total events | Requests answered without error, out of the total |
| SLO, service level objective | The value the team commits to reaching, over a period | 99.9%, over 30 days |
| SLA, service level agreement | A contract with a customer, with consequences if it is breached | PagoRaíz's with Verdalia: 99.95% |
| Error budget | What the objective allows to fail: 100% minus the SLO | 0.1%: 43.2 minutes in 30 days |
The 99.9% target is the one we set with Andrés in Module 1. The error budget changes the conversation. 100% is not a target: it is impossible, and getting closer costs more and more. If the budget is almost intact, the team can take risks: deploy more and run drills in production. If it has been used up, changes that are not about reliability stop. Business and engineering stop arguing opinions and look at a number.
MINUTES_30_DAYS = 30 * 24 * 60
def error_budget(slo, total):
"""How much can fail without breaching the objective."""
return (1 - slo) * total
def consumed(failures, slo, total):
"""Fraction of the error budget already spent."""
return failures / error_budget(slo, total)
def burn_rate(failures, total, slo):
"""Spending speed. At 1, the budget runs out exactly at the end of the period."""
return (failures / total) / (1 - slo)
SLO = 0.999
print(f"Monthly budget: {error_budget(SLO, MINUTES_30_DAYS):.1f} minutes")
# July, in minutes: 7 from the cutover and 11 from the incident on the 15th
spent = 7 + 11
print(f"July: {spent} minutes, {consumed(spent, SLO, MINUTES_30_DAYS):.0%} of the budget. "
f"Availability: {1 - spent / MINUTES_30_DAYS:.3%}")
# September, in requests
requests, failed = 1_840_000, 610
print(f"September: {error_budget(SLO, requests):.0f} requests could fail "
f"and {failed} have failed, {consumed(failed, SLO, requests):.0%}")
# Burn rate of the last hour, in three situations
for situation, total, failures in (("Normal hour", 2_600, 1),
("August 24 deployment", 5_200, 78),
("Total outage", 5_200, 5_200)):
rate = burn_rate(failures, total, SLO)
alert = "critical" if rate >= 14.4 else "high" if rate >= 6 else "none"
print(f"{situation:28} rate {rate:7.1f} runs out in {30 * 24 / rate:7.1f} hours alert: {alert}")Output:
Monthly budget: 43.2 minutes July: 18 minutes, 42% of the budget. Availability: 99.958% September: 1840 requests could fail and 610 have failed, 33% Normal hour rate 0.4 runs out in 1872.0 hours alert: none August 24 deployment rate 15.0 runs out in 48.0 hours alert: critical Total outage rate 1000.0 runs out in 0.7 hours alert: critical
Explanation:
error_budgetworks for minutes and for requests: it depends on what is passed astotal. Measuring in requests is fairer, because a minute of downtime at 4:00 a.m. affects fewer customers than one at noon.- The burn rate compares the current error ratio with the one the objective allows. A rate of 1 uses up the budget in exactly 30 days. One of 15 uses it up in 2 days.
- The threshold of 14.4 is a widespread convention: at that pace, 2% of the month's budget is spent in one hour.
- The August 24 deployment failed 1.5% of requests. It was not an outage, and a fixed threshold of the kind “more than 5% errors” would not have seen it. The burn rate did.
Interpretation: July spent 42% of its budget, and 7 of its 18 minutes were those of the cutover, planned and announced. The budget is for that too: for spending it on purpose.
Alerts, On-Call, and Runbooks
An alert interrupts a person, and it must deserve to.
| Principle | Meaning |
|---|---|
| Alert on symptoms, not on causes | The symptom is what the user suffers: errors, slowness, or emails that do not arrive. A processor at 90% is a possible cause, and often nothing happens to anyone |
| Every alert demands an action | If there is nothing to do, it is not an alert: it is a data point for a dashboard |
| Severity | Critical: notifies whoever is on call, at any hour. High: notifies during working hours. Warning: creates a task |
| Every alert links to its runbook | Whoever receives it at 4:00 a.m. must not improvise |
| Alert fatigue | A team that receives twenty alerts a day stops reading them, and the important one gets lost among the rest. Every alert that does not lead to an action is fixed or deleted |
# alerts/store.yml
groups:
- name: store
rules:
- alert: ErrorBudgetFastBurn
expr: |
sum(rate(verdalia_requests_total{service="store", code=~"5.."}[1h]))
/ sum(rate(verdalia_requests_total{service="store"}[1h]))
> 14.4 * 0.001
for: 2m
labels:
severity: critical
annotations:
summary: "The store is burning its error budget 14 times faster than allowed"
runbook: "docs/runbooks/store-errors.md"
- alert: ConfirmationEmailsDelayed
expr: verdalia_queue_age_seconds{queue="emails.confirmation"} > 600
for: 5m
labels:
severity: high
annotations:
summary: "The oldest message in emails.confirmation has been waiting for more than 10 minutes"
runbook: "docs/runbooks/email-queue.md"
- alert: NightlyBackupSmall
expr: verdalia_backup_bytes < 0.8 * (verdalia_backup_bytes offset 1d)
labels:
severity: high
annotations:
summary: "The nightly backup is less than 80% the size of yesterday's"
runbook: "docs/runbooks/postgresql-restore.md"| Element | Meaning |
|---|---|
expr |
The condition, in PromQL. The first one divides the rate of responses with a 5xx code by the total rate |
The window, [1h] |
One hour avoids firing on a brief spike. It is common to combine it with a second, five-minute window, so that the alert clears soon after the problem stops |
14.4 * 0.001 |
The burn rate times the error ratio the objective allows |
for |
The condition must hold for that long before notifying |
labels |
The severity decides who is notified, and how |
annotations |
The text the person receives, with the link to the runbook |
offset 1d |
The value of the same metric 24 hours earlier |
On-call is the shift during which one person is responsible for the critical alerts. In Verdalia it rotates weekly among Marta, Íker, and Lucía, with compensation agreed with Andrés. Three people are few for an on-call rotation. It is only sustainable because there are two critical alerts, and because the system resolves most failures on its own.
Dashboards and Synthetic Checks
A main dashboard must fit on one screen and answer one question: is the store fine right now?
| Block | Content |
|---|---|
| Objectives | The status of each SLO and the error budget remaining |
| Golden signals | Traffic, errors, 95th and 99th percentiles, and saturation: replicas running and connections to the database |
| Business | Orders confirmed per hour, compared with the same day of the previous week |
| Dependencies | PagoRaíz, queues, database, and cache |
| Changes | A vertical mark at every deployment and every flag change |
The business metric is the most honest one. If orders per hour drop by half on a Saturday at 11:00 a.m., something is wrong, whatever the others say.
A synthetic check is a request a program makes at fixed intervals, as if it were a user. It is black-box monitoring: it looks at the system from outside, without knowing its inside. It detects what the internal metrics cannot see: a domain that has stopped resolving, an expired certificate, or a total outage, in which nothing is left to emit metrics. White-box monitoring, which looks from inside, explains. Black-box monitoring confirms that the customer can buy.
Postmortems
A postmortem is a short document written after an incident, to learn from it. It is blameless: it starts from the premise that people acted reasonably with the information they had, and looks for what made the error possible. If someone to blame is sought, next time nobody will tell what they know.
Verdalia's first one, summarized:
| Section | Content |
|---|---|
| Summary | On Tuesday, August 17, confirmation emails stopped being sent between 3:00 a.m. and 10:31 a.m. |
| Impact | 19 emails, with up to 7 and a half hours of delay. No order lost, and no email lost, thanks to the queue |
| Detection | At 10:12 a.m., by Carmen, after a customer's call. 7 hours and 12 minutes |
| Cause | The secrets manager rotated the queue service's credential at 3:00 a.m., as planned. The worker read it only at startup, and could not reconnect |
| Why the alert did not fire | It warned at more than 200 messages in emails.confirmation, a figure taken from the April 20 incident, in the middle of the campaign. In August, with 4 orders an hour, it would have taken two days |
| What worked | The queue held the messages. The store kept confirming orders |
| Actions | Alert on the age of the oldest message, not on the size: Lucía, August 18. The worker rereads the secret if authentication fails: Íker, August 24. Review everything that consumes secrets with rotation: Marta, August 31 |
It is the same lesson the empty backups left in Module 5: a security improvement, a correct one, broke something nobody remembered. And it adds another. The alert watched a cause, the size of the queue, and not the symptom: a customer without their email.
Verdalia: What Is Watched and Scenario QS-3
| What | Signal | Alert | Severity |
|---|---|---|---|
| Store | External synthetic check of /health and of the product page for product 2087, every 60 seconds, from two locations |
Two consecutive failures | Critical |
| Store | Requests, errors, and duration, by route | Burn rate above 14.4 | Critical |
| Store | The same | Burn rate above 6, over 6 hours | High |
| Catalog | 95th percentile | Above 800 ms for 10 minutes | High |
notification-service |
Emails sent and failed | See the queues | |
Queue emails.confirmation |
Age of the oldest message | More than 10 minutes | High |
Queue emails.failed |
Number of messages | Any, for 10 minutes | Warning |
| Database | Connections, replica lag, and failovers | More than 160 connections, or a failover | High |
| Backups | Size and time of the last correct backup | 20% smaller than the previous one, or none in 26 hours | High |
| Certificates | Days until expiration | Fewer than 21 | Warning |
| Spending | Accumulated spending for the month | €450 and €500 | Warning |
There are twelve rules, and only two of them are critical. The two queue alerts replace the daily check Lucía had been doing by hand since Module 3. The backup alert replaces the email from ADR-009.
| SLO | SLI | Target over 30 days | July | August | September |
|---|---|---|---|---|---|
| Store availability | Requests without a server error | 99.9% | 99.96% | 99.98% | 99.97% |
| Catalog latency | Requests served in under 800 ms | 95% | 97.8% | 98.4% | 98.1% |
| Order confirmation | Confirmations without a system error | 99.5% | 99.7% | 99.8% | 99.8% |
| Confirmation email | Emails sent in under 5 minutes | 99% | 99.6% | 99.2% | 99.9% |
The Drills
| Drill | Date | Result |
|---|---|---|
| Total outage of the store, in staging, with the production alerts | Thursday, September 2, 10:00:00 | The synthetic check fails at 10:00:40 and at 10:01:40. Íker's phone rings at 10:01:58. Detection: 1 minute and 58 seconds |
| Forced failover of the database, in production | Thursday, September 9, 7:30 | 72 seconds without writes. 9 failed requests. The catalog kept working with the cache and the read replica. Nobody intervened |
| Removal of one store replica, in production | Thursday, September 9, 7:45 | The load balancer stopped sending it traffic within 10 seconds. The service replaced it in 1 minute and 40 seconds. 3 failed requests |
Scenario QS-3 is met. Detection drops from 25 minutes to under 2. The failure of the primary, which required 12 to 19 minutes of manual work, resolves itself in 72 seconds. And monthly availability is no longer an estimate: it is measured, and has been above 99.9% for three months.
Module 6 Review
The Scenarios
| Scenario | Status | Last measurement |
|---|---|---|
| QS-1, performance | Met | July 8: 95th percentile of 570 ms and 99th percentile of 1.4 s, with 1,000 users |
| QS-2, scalability | Met | July 8: a new replica in under 2 minutes, without intervention |
| QS-3, availability | Met | September 2 and 9. Three months above 99.9% |
| QS-4, security | Met | April 28. The secret detector runs on every change |
| QS-5, maintainability | Met twice | August 5: pickup point shipping method, in 2 and a half days, touching one module |
| QS-6, operability | Met | July 27: no downtime, and rollback in 3 minutes and 40 seconds |
There are three exceptions, accepted in writing. A PagoRaíz outage still prevents paying, and the store degrades while keeping the cart. The loss of the entire region is resolved by recreating the infrastructure with Terraform and restoring the external backup: an estimated 4 hours, and it has not been rehearsed in full. And the web application firewall, intrusion detection, mTLS, and traces are still not adopted.
The Architecture
flowchart TB
customers(["Customers"])
staff(["Verdalia staff"])
cdn["CDN"]
synthetic["External synthetic check"]
subgraph cloud["NubeAtlas, region eu-sur-1, in two zones"]
subgraph public_subnet["Public subnet"]
lb["Managed load balancer, with TLS"]
vpn["Managed VPN"]
end
subgraph app_subnet["Application subnet: container service"]
store["Store, 2 to 10 replicas"]
api["Notifications, API"]
worker["Notifications, 2 workers"]
end
subgraph data_subnet["Data subnet: managed services"]
db[("PostgreSQL: primary, standby, and read replica")]
cache[("Redis-compatible cache")]
queues["AMQP-compatible queues"]
end
objects[("Object storage")]
secrets["Secrets manager"]
observability["Observability: metrics, logs, and alerts"]
end
pagoraiz[["PagoRaíz"]]
mail[["Email provider"]]
backups[("Backups, at a second provider")]
customers --> cdn --> objects
customers -->|"443"| lb --> store
staff --> vpn -->|"Panel"| lb
synthetic -->|"Every 60 seconds"| lb
store --> db
store --> cache
store --> api
store --> queues --> worker --> mail
store --> pagoraiz
secrets -.-> store
store -.-> observability
observability -.->|"Alerts"| staff
db -.->|"Nightly dump"| backups
There is no machine left that the team administers. The diagram is generated by a program from Terraform's output.
The Cost
| Item | Monthly cost |
|---|---|
| Store: 2.2 replicas on average off season | €88 |
notification-service: three small replicas |
€31 |
| Managed database and read replica, with a one-year reservation | €133 |
| Managed cache and queues | €58 |
| Managed load balancer and VPN | €32 |
| Object storage, secrets manager, and image registry | €12 |
| Managed observability and external synthetic check | €30 |
| CDN, external backups, and monthly restore | €20 |
| Staging and outbound transfer | €19 |
| Total off season | €423 |
The first full month, August, cost €480, €32 more than the €448 that ADR-010 estimated for a month without a campaign: observability and the image registry had not been foreseen. On September 22, with three months of data, Andrés approved reserving the database and its replica for a year, with a 30% discount: €57 less a month. During the campaign, with 4.4 replicas on average, the expected total is €512, and the annual average, €445. That is €13 more than the €432 of the rented servers. The cost per order, with about 2,600 orders a month on average, is €0.17, below the target of €0.25.
The Decisions
| ADR | Decision | Status |
|---|---|---|
| 001 | Modular monolith | In force. Reviewed on June 16: stands |
| 002 | Ports and adapters | In force |
| 003 | Notifications, the only independent service | In force |
| 004 | Message queue | In force, with a managed service |
| 005 | Stateless horizontal scaling | In force, with automatic adjustment |
| 006 | High availability with manual failover | Superseded by ADR-010 |
| 007 | Credentials in one file per server | Superseded by ADR-010 |
| 008 | Network in three zones | In force. The bastion host is replaced by the managed VPN |
| 009 | External backups and monthly restore | In force, with managed backups added |
| 010 | Migration to NubeAtlas | In force. May 19 |
| 011 | Managed containers, without Kubernetes | In force. June 23 |
| 012 | Delivery pipeline | In force. July 21 |
Twelve decisions, ten in force and two superseded. “Plant of the Month” was switched on on September 14 for 10% of customers, on the 21st for 50%, and on the 28th for everyone, without a single deployment.
Common Mistakes and Tips
- Alerting on processor usage. Alert on what the customer suffers, and leave the processor for the dashboard.
- Setting a threshold during the campaign and forgetting it in August. Absolute thresholds age badly. Ratios and ages hold up better.
- Logging personal data. A centralized log is one more copy of the data, with more readers.
- Averaging percentiles. The histogram buckets are added up and the calculation comes afterward.
- Watching only from inside. If everything goes down, nobody warns.
- Looking for someone to blame. The useful question is what allowed it to happen.
- Practical tip. Review every month the alerts that have fired. Those that led to no action are fixed or deleted.
Exercises
Exercise 1: Symptom or Cause
Classify these alerts as symptom or cause, and state which ones you would keep as alerts and which you would move to a dashboard: memory usage of one replica above 85%; more than 1% of order confirmations with an error; database disk at 70%; the store's certificate expires in 5 days; the cache hit rate drops below 60%.
Exercise 2: The Error Budget
The notification service has a target of 99% of emails sent in under 5 minutes, over 30 days. So far in the period it has sent 2,400 emails, and 19 arrived late. Calculate, with the lesson's functions, the budget, the fraction consumed, and the emails that can still be delayed. If in the last hour 40 emails were sent and 3 arrived late, what burn rate results?
Solutions
Solution to Exercise 1
| Alert | Type | Decision |
|---|---|---|
| Memory of one replica at 85% | Cause | Dashboard. If the replica fails, the service replaces it |
| More than 1% of confirmations with an error | Symptom | Alert. Better still to express it as a burn rate |
| Database disk at 70% | Cause, but it announces a certain failure | Low-severity alert, as a task: there is time to act |
| The certificate expires in 5 days | Cause, but it announces a certain failure | Alert, and with more notice |
| Cache hits below 60% | Cause | Dashboard. If it hurts the customer, the latency alert will fire |
The rule has one reasonable exception: causes that lead to a certain failure with a date, such as a disk filling up or a certificate expiring. Warning early costs little and buys time.
Solution to Exercise 2
print(f"{error_budget(0.99, 2400):.0f}", f"{consumed(19, 0.99, 2400):.0%}", f"{burn_rate(3, 40, 0.99):.1f}")The output is 24 79% 7.5. 24 emails can be delayed, and 19 already have been, 79%: 5 remain. The burn rate of the last hour is 7.5, because 7.5% fail when 1% is allowed. It exceeds the threshold of 6, which corresponds to a high alert. With only 40 emails, three delays may be coincidence, and that is why burn-rate alerts are evaluated over long windows when traffic is scarce. The 19 emails are those of the August 17 incident, which spent almost the whole month's budget in one night.
Conclusion
In this lesson you have learned that monitoring is knowing whether the system works, and observing, being able to understand why it does not. You have met the three pillars: metrics, with their types and the RED and USE methods; logs, structured and joined by a correlation ID; and traces, which show where the time goes. You have learned to turn a quality target into an indicator, an objective, and an error budget, and to alert on the speed at which that budget is consumed. You have seen that a good alert speaks of symptoms, demands an action, and links to a runbook, and that more is learned from an incident when nobody is looking for someone to blame.
This lesson ends Module 6. On May 1, Verdalia had ten machines installed by hand in a data center, three diagrams that contradicted each other, and a 38-step checklist. The path has had an order. First, being able to see the system: modeling tools, the C4 model, and documentation that is generated. Then, deciding where to go, with ADR-010, and how to run the store, with ADR-011. Then, ceasing to do by hand what can be described, with infrastructure as code and the pipeline of ADR-012. And at the end, getting the system to tell what is happening to it. The six quality scenarios Marta and Andrés wrote in Module 1 are met, with their exceptions recorded, for €445 a month on average.
A year has passed since the first meeting, and in that year Verdalia has made twelve decisions, one by one, each to solve the problem in front of it. It has never looked at the result as what it is: the design of an e-commerce system. The time has come to do so. To walk through it whole, end to end, as if it had to be explained to someone starting today, and then to compare it with very different systems, which solve problems Verdalia does not have. That is how Module 7 begins, with the lesson “Case Study: Architecture of an E-Commerce System.”
