Monitoring a Rails shop: logs, metrics, errors and uptime
TL;DR
Difficulty: Intermediate
Monitoring means the shop tells you it is unwell before a customer has to.
- Measure the four golden signals: latency (as percentiles, not averages), traffic, errors and saturation (busy threads, not CPU).
- Write logs as structured JSON events with the request id, using Rails 8.1's Rails.event, and rotate them.
- Send every exception through Rails.error to one error tracker, and act on new issues, not on totals.
- Check from the outside: an uptime check, and a synthetic script that walks to the payment form every 10 minutes.
- Compare orders per hour with what that hour should bring, and know that a small shop needs about an hour of silence before it means something.
- Alert on error budget burn rates, page only when waiting costs more than waking someone, and keep personal data in logs small and short lived.
What to read first
Most small shops learn about an outage from a customer email. This chapter builds the monitoring that gets there first, layer by layer, for an invented homeware shop in Leeds on Rails and Solidus: logs, errors, metrics, uptime and synthetic checks, business monitoring, and alerts tuned until every page is worth getting up for.
Your customers should not be your monitoring system
Every shop has monitoring, whether it planned it or not. If nothing else is in place, the monitoring is a customer who writes an email that says "your checkout doesn't work". That email arrives late, it arrives after other customers have quietly left, and it rarely says what broke.
Monitoring, done properly, means the shop tells you it is unwell before a customer has to. It has five parts, and this chapter takes them one at a time: logs (what happened, line by line), errors (every exception in one place), metrics (numbers over time), checks from the outside (does the shop work for a stranger?) and business monitoring (are orders arriving at the rate they should?). On top of them sit alerts, which decide when a person is interrupted, and a dashboard, which answers "is the shop all right?" on one screen.
The example throughout is Wrenfield Home, the invented homeware shop in Leeds from the rest of this series: owner Priya, developer Callum, who runs operations part time. The shop runs Ruby on Rails 8 and Solidus on two application servers with one managed PostgreSQL database at a European cloud provider, deployed with Kamal. It serves about 3.6 million requests a month, peaks at 40 requests a second on Black Friday, and takes 1,980 orders a month at an average order value of £72. All numbers about Wrenfield Home are invented for the example. If you have not read how the shop is deployed, the Kamal chapter of this series is the place to start.
Example: what a late warning costs on a Tuesday evening
The first question is money, because it decides how much monitoring is worth. The cost of a broken checkout is roughly the orders you would have taken while nobody knew:
Here is the lost revenue, the orders you expect per hour at that time of day, the average order value and the hours the problem goes unnoticed and unfixed. It is a simple rate times a duration (Foundations: ratios and rates).
Wrenfield Home takes 1,980 orders a month, about 66 a day. They do not arrive evenly. Between 7pm and 8pm on a Tuesday, the busiest hour, the shop expects about 6.0 orders. So one hour of a broken checkout at that time costs:
That is £432 an hour at the peak. At 3am the shop expects 0.2 orders an hour, so the same hour costs , about £14. The average hour, 66 orders over 24 hours, is 2.75 orders, so about £198. Keep these three numbers in mind. They decide later in this chapter when it is worth waking Callum and when a problem can wait until morning. Some customers come back later, so these are upper bounds, but abandoned baskets rarely all return.
The four golden signals: what to measure first
Google's Site Reliability Engineering (SRE) book, written by the people who run Google's production systems, names four signals that matter most for any system that serves users. "The four golden signals of monitoring are latency, traffic, errors, and saturation"1. The book adds that if you can only measure four things about a system that serves users, these are the four to focus on1.
- Latency is "the time it takes to service a request"1. For a shop: how long a product page or a checkout step takes to answer.
- Traffic is "a measure of how much demand is being placed on your system"1. For a shop: requests per second, and, one level up, sessions and orders.
- Errors are requests that fail. The book counts failures that are explicit (an error page), implicit (a page that answers but shows the wrong thing) and by policy (a page slower than you promised)1.
- Saturation is "how 'full' your service is"1: how close the servers, the database and the job queue are to their limit.
One detail in the book saves a lot of confusion: "it's important to distinguish between the latency of successful requests and the latency of failed requests"1. A failing database can make error pages very fast. If you mix them with real pages, the average gets better while the shop gets worse.
Example: Wrenfield Home's four signals in numbers
Callum writes down what each signal means for the shop and what normal looks like (invented figures):
| Signal | What Callum measures | Normal | Busiest moment |
|---|---|---|---|
| Latency | Time from request to response, per page type, as percentiles | Median 0.15 seconds, 95th percentile 0.8 seconds | Black Friday, 95th percentile 1.6 seconds |
| Traffic | Requests per second, and orders per hour | 1.4 requests a second on average, 3.6 million a month | 40 requests a second |
| Errors | Share of requests answered with a 5xx status, and failed checkout steps | Under 0.05% | Under 0.2% |
| Saturation | Busy Puma threads, database connections in use, job queue waiting time, disk | Under 20% of threads busy | About 83% of threads busy |
The traffic average is plain arithmetic: 3.6 million requests over a 30 day month of 2,592,000 seconds is about 1.4 a second. The saturation figure needs one more idea, which the next section works through.
Saturation: how close the shop is to full
Saturation is the signal small shops measure least, and it is the one that predicts trouble. A shop rarely falls over because one request is slow. It falls over because too many requests wait at the same time.
A Rails application served by Puma handles a fixed number of requests at once. A new Rails 8 app sets three threads per Puma process by default, "deemed a decent compromise" in the generated configuration2. Multiply by the number of processes and servers and you have the shop's capacity in requests in flight.
How many requests are in flight at once? Little's law answers it, and it holds for almost any queue in a steady state3. In symbols:
Here is the average number of requests in the system at once, the arrival rate in requests per second and the average time each request spends in the system in seconds (Foundations: ratios and rates).
Example: Black Friday against the thread count
Wrenfield Home runs two application servers. Each runs two Puma processes with three threads, so each server handles 6 requests at once and the shop handles 12.
On an ordinary Tuesday evening, about 3 requests a second arrive and each takes 0.2 seconds on average:
Fewer than one request is in flight on average, so of 12 threads, 5% saturation. On Black Friday, 40 requests a second arrive and the average time rises to 0.25 seconds because the database is busier:
Ten of 12 threads are busy on average, 83%. That is close to full. Arrivals are not perfectly even, so for some seconds more than 12 requests arrive, and the extra ones wait in a queue. Waiting raises , a higher raises , and the shop slides from slow to stuck. The lesson for monitoring: watch busy threads and request queue time, not CPU alone. CPU on the Wrenfield servers was 45% at that moment, which looked relaxed.
The same reasoning applies to the database. Each Puma process keeps its own pool of database connections, usually as many as it has threads, plus the job workers. Four web processes with three connections each are 12, Solid Queue's workers add their own, and the managed database plan has a connection limit of its own. Counting connections in use against that limit is a saturation metric too. The Solid Queue chapter shows how the job side is sized.
Averages hide the customers who wait
An average latency of 0.24 seconds sounds fine. It can hide one customer in twenty waiting almost a second, and one in a hundred waiting more than two. That is why the SRE book prefers percentiles: "Using percentiles for indicators allows you to consider the shape of the distribution"4. The 95th percentile, written p95, is the time that 95% of requests beat. The median, p50, is the time half of them beat.
Prometheus, the open source metrics system used later in this chapter, stores latency as a histogram: counts of requests that finished within each of a fixed set of limits, called buckets. To get a percentile it finds the bucket that contains it and assumes the requests are spread evenly inside that bucket, which its documentation calls linear interpolation5:
Here is the estimated percentile, the rank you want (for p95, 95% of all requests), and the lower and upper limits of the bucket that contains that rank, and and the cumulative counts at those two limits (Foundations: median and mode).
Example: the p95 of one evening hour
In one hour Wrenfield Home answered 5,000 requests. The histogram counted, cumulatively:
| Finished within | Requests so far |
|---|---|
| 0.1 seconds | 1,900 |
| 0.25 seconds | 3,900 |
| 0.5 seconds | 4,600 |
| 1 second | 4,850 |
| 2.5 seconds | 4,980 |
| any time | 5,000 |
The p95 rank is . The count passes 4,750 between 0.5 seconds (4,600) and 1 second (4,850), so that is the bucket:
So p95 is about 0.8 seconds. The same method gives the median, rank 2,500, inside the 0.1 to 0.25 bucket: , about 0.15 seconds. And p99, rank 4,950, inside the 1 to 2.5 bucket: seconds. The average over the same hour was 0.24 seconds. One number says "fast", the other says "fifty customers waited over two seconds in one hour". Both are true, and only the percentile tells you about those fifty. The estimate is only as good as the buckets: if most requests sit in one wide bucket, the percentile is a guess, so choose limits around the times you care about.
Symptoms page you, causes explain
The SRE book separates two questions: "what's broken, and why?"1. The symptom is what a customer feels (the checkout is slow). The cause is the reason (a missing database index). It also separates two kinds of monitoring. Black box monitoring looks from the outside, like a customer: it sees symptoms, and it shows problems that are happening now rather than ones that are coming1. White box monitoring reads the system's own numbers and allows "detection of imminent problems, failures masked by retries, and so forth"1.
The practical rule that follows: alert on symptoms, investigate with causes. A page at night should say "customers cannot pay", not "CPU at 85%". High CPU is a fine thing to see on a dashboard while you work out why customers cannot pay.
Example: two ways to watch the same problem
On a Thursday the nightly supplier feed import runs long and holds database connections. Customers see product pages slowing down.
- The cause view: connections in use 46 of a limit of 50, CPU on the database 70%, the import job running for 48 minutes instead of 12.
- The symptom view: p95 latency of product pages up from 0.8 to 2.9 seconds, the share of failed requests up from 0.03% to 0.4%.
Callum's alert fires on the symptom view, because that is what costs money. The cause view sits on the dashboard and gives him the answer in two minutes once he looks: the import job. The fix, a smaller batch size and a lower priority queue for the import, is a cause fix, but he only learned he needed it from the symptom.
Logs: write them for a machine, read them as a person
A log is the shop's diary: one line per thing that happened. Rails writes one by default, and a new Rails 8 app already makes three good choices in config/environments/production.rb: it logs to standard output, it tags every line with the request id, and it keeps health checks out of the log6. The generated lines read:
# config/environments/production.rb (as generated by Rails 8.1)
config.log_tags = [ :request_id ]
config.logger = ActiveSupport::TaggedLogging.logger(STDOUT)
config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info")
config.silence_healthcheck_path = "/up"
Standard output matters with Kamal, because the app runs in a Docker container and Docker collects whatever the container prints. Two things follow. First, kamal app logs shows those lines from all servers. Second, Docker's default json file driver keeps them forever unless told otherwise: its max-size setting defaults to unlimited7. A busy shop fills a disk with logs that nobody reads. Kamal passes logging options straight to Docker8. Callum adds a limit:
# config/deploy.yml (excerpt)
logging:
driver: json-file
options:
max-size: 50m
max-file: "5"
That keeps at most five files of 50 MB per container on each server, 250 MB, and rotates the oldest away. The logs you want to keep longer should be shipped somewhere else, which is the next step.
Example: why the request id is worth more than the message
A customer emails at 9.42pm: "the payment page hung and then showed an error". Callum has a time and nothing else. Because every line carries the request id, he searches the logs for the minutes around 9.41pm for the checkout payment path, finds one request with status 500, copies its id, and searches again for that id. Now he sees every line from that one request in order: the controller, the call to the payment provider, the timeout after 10 seconds, the error. Without the id he would have read 3,000 lines from that minute, from both servers, interleaved. Rails reuses an incoming X-Request-Id header when a proxy or load balancer sets one and generates a random id otherwise9, so the same id can join the proxy's line and the app's lines.
Structured logs: one event, one line of JSON
The default Rails log is written for people. The Rails 8.1 release notes say it plainly: it is great for people to read, but less suited to processing by machines10. Searching it means guessing at text. A structured log writes each event as a set of named fields, usually one line of JSON, so a log tool can ask "all checkout requests over 2 seconds with status 500 in the last hour" and get an exact answer.
Rails 8.1, released in October 2025, added a structured event reporter for exactly this, Rails.event10. You call Rails.event.notify with an event name and a payload, and any subscriber you register receives a hash with the name, payload, tags, context, a timestamp in nanoseconds and the source location11. Subscribers are plain Ruby objects with an emit method, and they are "responsible for encoding events"11, so you decide the format.
Rails also has an older, lower layer: ActiveSupport::Notifications. The framework itself announces things through it, such as every finished controller action (process_action.action_controller), every SQL query and every job performed, and you can subscribe to any of them12. The finished action event carries the controller, action, method, path, status, and the time spent in the database and in views. If the action raised an error it also carries the exception12.
The two together make a clean structured request log.
Example: the request log, one event per line
Callum adds two small initialisers. The first turns every finished controller action into one structured event:
# config/initializers/request_events.rb
# One structured event per finished controller action.
ActiveSupport::Notifications.subscribe("process_action.action_controller") do |event|
payload = event.payload
exception_class = payload[:exception]&.first
status = payload[:status] ||
(exception_class && ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class))
Rails.event.notify("http.request",
controller: payload[:controller],
action: payload[:action],
method: payload[:method],
path: payload[:path].to_s.split("?").first, # drop the query string, it can carry tokens
status: status,
duration_ms: event.duration.round(1),
db_ms: payload[:db_runtime]&.round(1),
view_ms: payload[:view_runtime]&.round(1),
error: exception_class)
end
When an action raises, the status is not set yet, because Rails turns the exception into a response later. ActionDispatch::ExceptionWrapper.status_code_for_exception returns the status Rails will use, so a missing record still logs as 404 and not as 500. The second initialiser writes every event as one line of JSON to standard output, and adds the request id to the context of every event:
# config/initializers/event_log.rb
class JsonLogSubscriber
def initialize(io = $stdout)
@io = io
@io.sync = true
end
def emit(event)
line = {
time: Time.at(0, event[:timestamp], :nanosecond).utc.iso8601(3),
event: event[:name],
**event[:payload].to_h,
**event[:context],
tags: event[:tags].presence
}.compact
@io.puts(JSON.generate(line))
end
end
Rails.event.subscribe(JsonLogSubscriber.new) if Rails.env.production?
# app/controllers/application_controller.rb (excerpt)
class ApplicationController < ActionController::Base
before_action { Rails.event.set_context(request_id: request.request_id) }
end
Rails clears this context before and after each request11, so one request's id never leaks into the next. A slow payment step now produces one line like this:
{"time":"2027-03-02T21:41:07.512Z","event":"http.request","controller":"CheckoutsController","action":"update","method":"PATCH","path":"/checkout/update/payment","status":500,"duration_ms":10412.6,"db_ms":38.2,"view_ms":null,"error":"Net::ReadTimeout","request_id":"8c1f2e7a3b"}
Every field is searchable. "How many checkout updates took over 5 seconds this week, and which errors did they end in?" becomes a query, not an afternoon. Callum ships these lines from Docker to a log store. Whether that is a hosted service or a self run Grafana Loki is a cost question for a later chapter in this series on running costs. The default human readable lines stay on, tagged with the same request id, for reading on the server. If you prefer a gem, Lograge is a long standing alternative that condenses Rails' request logging into one line per request13.
What a log line must never carry
The rule from the error handling article still holds: an order id in a log line, never an email address, a card number or a street. Two places leak quietly. The query string can carry reset tokens and tracking ids, which is why the subscriber above drops it. And the proxy in front of the app logs its own line: kamal-proxy records, among other fields, the client address, the user agent and the raw query string of every request14. That is personal data in your logs whether your Rails code is careful or not, which the section on the law comes back to.
Errors: one place to see every exception
An error tracker collects every exception from the shop, groups identical ones into one issue, counts them and shows the stack trace with the context. The question it answers is not "did something fail?" (something always fails) but "is this new, and is it getting worse?".
Rails has one front door for this: the error reporter, Rails.error. Unhandled errors in requests and jobs are already reported through it, and any object with a report method can subscribe15:
# config/initializers/error_metrics.rb
# Counts every reported error by class, so errors can be graphed and alerted on.
ERRORS_REPORTED = Prometheus::Client.registry.counter(
:shop_errors_reported_total,
docstring: "Errors reported through Rails.error",
labels: [:error_class, :handled]
)
class ErrorMetricsSubscriber
def report(error, handled:, severity:, context:, source: nil)
ERRORS_REPORTED.increment(labels: { error_class: error.class.name, handled: handled.to_s })
end
end
Rails.error.subscribe(ErrorMetricsSubscriber.new)
The signature, report(error, handled:, severity:, context:, source: nil), is the one the Rails guide documents15. The counter itself is a Prometheus metric, which the section on metrics below sets up. Error tracking services plug into the same door, so the choice of tool is a separate decision from the code.
Where the error data can live
There are three families of tools, and each fits a different shop:
| Approach | Examples | Where the data lives | Effort |
|---|---|---|---|
| Hosted error tracking service | Sentry16, Honeybadger17, AppSignal18 | The vendor's servers, in the region you choose where offered | A gem and an initialiser |
| Self hosted service | Sentry self hosted19, GlitchTip, which is open source and works with Sentry's client libraries20 | Your own server | A server to run, update and back up |
| Inside the app | Solid Errors, an exception tracker that lives inside the Rails app and stores errors in a database21 | Your own database | A gem, a database and a protected admin page |
None of these is right for every shop. A hosted service gives grouping, release tracking and notifications for little effort, and its prices are on its own pricing page. A self hosted one keeps the data at home and costs a server and your time. An in app tracker is the smallest step and depends on the shop being up to show you that the shop is down, so it never replaces checks from the outside. Whatever you choose, it receives personal data as soon as a stack trace or context includes it, which makes the vendor a processor under data protection law.
Example: a week of errors, read properly
In one week Wrenfield Home's tracker received 1,240 error events, grouped into nine issues (invented figures):
| Issue | Events | New this week? | Action |
|---|---|---|---|
ActionController::RoutingError from bots probing old URLs | 820 | No | Ignore in the tracker, count only |
ActiveRecord::RecordNotFound on deleted products | 260 | No | Redirect retired products, then ignore |
Stripe::CardError (declined cards) | 96 | No | Normal customer life, dashboard only |
Net::ReadTimeout from the courier's rate service | 38 | No | Known, handled with a fallback rate |
NoMethodError in the new gift note step | 14 | Yes | Ticket, fixed next morning |
| Four other issues | 12 | Mixed | Read once, then decide |
The count says 1,240. The truth is one new bug, introduced by Tuesday's release, affecting 14 checkouts. Callum's rule: a new issue creates a ticket automatically. A known issue only alerts if its rate jumps. That turns a noisy number into one item of work.
Metrics: numbers over time, kept for months
Logs tell you about one request. Metrics tell you about all of them, as numbers sampled over time: requests per second, p95 latency, busy threads, orders per hour. They are small, so you can keep them for a year and compare this Black Friday with the last one.
Prometheus is the open source standard for this. It pulls numbers from an endpoint on each server at a fixed interval, every 15 seconds at Wrenfield (it calls this scraping), stores them as time series and evaluates rules on them. Its Ruby client, the prometheus-client gem (version 5.0 in November 2026), ships two Rack middlewares: one that measures every HTTP request and one that serves the numbers at /metrics22. The request middleware counts requests by status code, method and path in http_server_requests_total and records their durations in a histogram, http_server_request_duration_seconds23.
# config.ru
require_relative "config/environment"
require "prometheus/middleware/collector"
require "prometheus/middleware/exporter"
use Rack::Deflater
use Prometheus::Middleware::Collector
use Prometheus::Middleware::Exporter
run Rails.application
One trap catches almost everyone. Puma with several processes means several copies of every counter, and a scrape reaches only one process. The client's documentation says multi process servers need a shared store, DirectFileStore, configured before any metric is created22:
# config/initializers/0_prometheus_store.rb
# The leading 0 makes this initialiser load first, before any metric is declared.
require "prometheus/client"
require "prometheus/client/data_stores/direct_file_store"
Prometheus::Client.config.data_store =
Prometheus::Client::DataStores::DirectFileStore.new(dir: "/tmp/prometheus_metrics")
The directory must be emptied when the server starts, before Puma forks. Then two exporters cover what the Rails app cannot see: node_exporter for the machine (CPU, memory, disk, network)24 and postgres_exporter for the database25, which on a managed database runs with a role that has the pg_monitor privilege for reading the monitoring views26. The /metrics endpoint itself must not be public: Callum lets only the monitoring server's address reach it.
Prometheus answers questions in its own query language, PromQL. The p95 of all requests over five minutes is the documented pattern5:
histogram_quantile(0.95,
sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))
and the average is the rate of the sum divided by the rate of the count5:
rate(http_server_request_duration_seconds_sum[5m])
/ rate(http_server_request_duration_seconds_count[5m])
A note on averaging: never average p95 values from two servers. The Prometheus documentation warns that averaging quantiles "yields statistically nonsensical values"5. Add the buckets first, as the query above does, then take the percentile.
Hosted metrics services such as Grafana Cloud27, Datadog28 and New Relic29 do the same job without a server of your own. OpenTelemetry is the vendor neutral standard for traces, metrics and logs, and worth knowing for later: in November 2026 its Ruby traces are stable while Ruby metrics and logs are still marked as in development30.
Example: where Wrenfield Home's monitoring runs
Callum's layout (invented, and one sensible choice among several):
- Both application servers expose
/metricsfrom Rails, plusnode_exporter, reachable only from the monitoring server. - A third, small server at the same provider runs Prometheus, Alertmanager and Grafana for dashboards, and
postgres_exporterfor the managed database. - Uptime and synthetic checks run at a different provider, so they still work when the shop's provider has a bad day.
- Prometheus is configured to keep 400 days of metrics, about 13 months. At one sample every 15 seconds, a single series has samples a day. The shop has about 2,000 series, so about 11.5 million samples a day, which Prometheus stores compactly.
The last point is why metrics are where history lives. Logs answer "what happened at 9.41pm". Metrics answer "is this Black Friday worse than last year's".
Uptime checks: look from the outside
All of the above lives inside the shop. If the server is off, the network is down or a certificate expired, the inside sees nothing because nothing arrives. An uptime check is a black box: a service somewhere else requests your page every minute or so and alerts you when it fails.
Rails 8 includes a health endpoint at /up. It returns 200 "if the app has booted with no exceptions, and a 500 status code otherwise", and the documentation is explicit that it does not reflect the database or other dependencies31. That is deliberate: Kamal's proxy uses it during deploys, and a health check that fails whenever the database blinks would take every server out of rotation at once. So keep /up as it is, and point your uptime service at a real page as well, such as a product page, with a check that the page contains the price.
Options range from hosted uptime services such as UptimeRobot32 and Better Stack33 to self hosted tools such as Uptime Kuma, which describes itself as a self hosted monitoring tool34 and should then run somewhere other than the shop.
Example: three uptime checks and one rule
Callum sets up three checks, each from three locations:
https://wrenfieldhome.example/upevery minute: the app boots.- The Hollin oak side table page every minute: status 200 and the text "£189" present.
- The certificate: alert 14 days before it expires.
The rule: alert only when at least two of the three locations fail twice in a row. One location failing once is usually that location's own network. In the first week, before the rule, two alerts came from a single location at 4am and were nothing. After the rule, none.
Synthetic checks: walk through the checkout like a customer
An uptime check proves a page answers. It does not prove a customer can buy. A synthetic check is a small script that behaves like a customer: it opens a product page, adds the product to the basket, goes to the checkout and stops just before paying. It catches the failures that every inside signal misses, because nothing on the server fails.
Playwright, a browser automation library with an official Python version35, is a common way to write one. Services such as Checkly run Playwright checks on a schedule from several locations36. A heartbeat service such as Healthchecks.io receives a "success" or "fail" ping from the script and alerts if a fail arrives or if no ping arrives at all, which also catches a check that silently stopped running37.
Example: the synthetic checkout script
# synthetic_checkout.py
# Runs every 10 minutes on a small machine at a different provider.
# It walks to the payment step and stops: it never pays and never completes an order.
import os
import time
import urllib.request
from playwright.sync_api import sync_playwright, expect
SHOP = os.environ.get("SHOP_URL", "https://wrenfieldhome.example")
HEARTBEAT = os.environ["HEARTBEAT_URL"] # the check's ping URL, kept out of the code
EMAIL = "synthetic-check@wrenfieldhome.example"
def ping(suffix: str = "", message: str = "") -> None:
data = message.encode()[:1000] if message else None
urllib.request.urlopen(HEARTBEAT + suffix, data=data, timeout=10)
def walk_to_payment() -> float:
started = time.monotonic()
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(user_agent="WrenfieldSyntheticCheck/1.0")
page.goto(SHOP + "/products/hollin-oak-side-table")
expect(page.get_by_test_id("price")).to_contain_text("£189")
page.get_by_role("button", name="Add to basket").click()
expect(page.get_by_test_id("basket-count")).to_contain_text("1")
page.goto(SHOP + "/checkout")
page.get_by_label("Email").fill(EMAIL)
page.get_by_label("Postcode").fill("LS1 4AP")
page.get_by_role("button", name="Continue to delivery").click()
page.get_by_role("button", name="Continue to payment").click()
# The payment provider's form renders in an iframe. If its script is blocked,
# the page still loads with status 200, but this iframe never appears.
expect(page.locator('[data-testid="payment-form"] iframe').first).to_be_visible(timeout=15000)
browser.close()
return time.monotonic() - started
if __name__ == "__main__":
for attempt in (1, 2):
try:
seconds = walk_to_payment()
ping(message=f"ok in {seconds:.1f}s")
break
except Exception as error: # any failure: wait a minute, then try once more
if attempt == 2:
ping("/fail", f"{type(error).__name__}: {error}")
else:
time.sleep(60)
The test ids and button labels are the example shop's own. Callum added data-testid attributes to the storefront so that a design change does not break the check. A real checkout needs more fields than this, and the script fills whatever the shop asks for. Two consequences need care:
- Every run leaves an incomplete order in
spree_orders, 144 a day. A nightly job deletes incomplete orders with the synthetic email address older than a day, and the data team filters that address out of every report. This is the same family of problem as the 40 test and staff orders a year that already pollute Wrenfield's order table, and it is far easier to label at the source than to clean later. - The script's user agent lets analytics and the logs ignore these visits.
The full purchase, including payment, runs once a day on the staging shop against the payment provider's test mode. Production only ever goes as far as the payment form.
Example: the Tuesday the server saw nothing wrong
On a Tuesday in week two (invented), Callum releases at 7.04pm. The release tightens the Content Security Policy, the header that tells browsers which scripts a page may load. One line is wrong, and browsers now refuse the payment provider's script. The payment page loads with status 200. No exception is raised, because nothing fails on the server. Here is what each kind of monitoring saw:
/up: green. The app booted.- The uptime check on the product page: green.
- The error tracker: silent. The error happened in the customer's browser.
- Latency, traffic, server errors: normal, slightly fewer requests to the order completion step, too few to notice in an hour.
- The synthetic check at 7.10pm: the payment iframe never appeared. Retry at 7.11pm: same. Fail ping, Callum's phone rings at 7.11pm.
Callum checks the release register, sees the policy change as the only change in that release, and rolls back with Kamal. Checkout works again at 7.24pm. Twenty minutes of a broken payment step at 6.0 expected orders an hour cost about 2.0 orders, or £144. The next section shows what the same evening would have cost without the synthetic check.
Business monitoring: orders per hour against what you expect
The most honest health signal of a shop is the one the owner cares about: are orders arriving? If they stop, something is wrong, whatever the servers say. Business monitoring compares the orders that arrived with the orders you expected at this hour, on this weekday.
Use the shop's own database for this, never web analytics. Wrenfield's GA4 shows about 15% fewer purchases than the shop because of consent choices and blockers, and that gap moves with every change to the consent banner. The order table does not lie about orders.
Orders arrive one by one, independently, at a rate that changes through the day. The Poisson distribution describes counts like this38. If the expected number of orders in a period is , the chance of seeing exactly is:
Here is the number of orders that actually arrive in the period, a particular count (0, 1, 2 and so on), the expected count for that period, the base of the natural logarithm, about 2.718, and the factorial of (Foundations: probability and Foundations: distributions). The Poisson regression article goes deeper into counting models.
The case that matters most is zero orders. With the formula shrinks to . Over a window of hours at an expected rate of orders an hour:
Here is the expected orders per hour and the length of the window in hours (Foundations: probability). If you want to alert only when silence is so unlikely that it is almost certainly a fault, say a chance below , solve for :
Here is the natural logarithm and the chance of a false alarm you accept (Foundations: logarithms). With , is about 6.9.
Example: how fast silence becomes a signal
At Wrenfield Home's busiest hour, 7pm to 8pm on a Tuesday, :
So 1.15 hours, 69 minutes, without an order is the first moment silence is a reliable alarm. On an average hour, , it takes hours. At 3am, , it takes 34.5 hours, which means business monitoring cannot detect a night outage at all.
This is the honest limit of a small shop. A shop with 2,000 orders an hour notices a broken checkout in seconds from its order rate. A shop with 66 a day cannot. So business monitoring is the safety net for slow, partial and silent failures (a payment method broken for one bank, a shipping rule that blocks one country, a tracking change that empties the basket), and synthetic checks are the fast alarm.
Back to the Tuesday. Without the synthetic check, silence would have become significant 69 minutes after the release at 7.04pm (the last order had come in just before it), at 8.13pm, and the check that runs every 15 minutes would have raised it at 8.15pm. With eight minutes to roll back, checkout would have been broken for 79 minutes, about 8.1 lost orders at the expected rates of 6.0 and 6.5 an hour, about £583. Without business monitoring either, the first signal was a customer email at 8.50pm: 114 minutes, about 11.9 orders, about £856.
Example: the expected band, and the job behind it
Callum computes the expected count from history: the same weekday and the same hour over the last eight weeks, averaged. For a band, he takes the Poisson range that holds 95% of outcomes for that expected value. The chart shows that Tuesday as it would have looked without the synthetic check (invented numbers).
The chart makes the limit visible. For most of the day the lower edge of the band is zero: a single hour with no orders is normal at 9am. Only in the evening does an empty hour fall outside the band. That is why the alert does not test single hours. It asks one question every 15 minutes: how long since the last real order, and how many orders did that same stretch of time bring on the same weekday in the last eight weeks? When that expected number passes 6.9, the chance of silence falls below 0.001 and the job raises the alarm. The rule only catches a full stop. A partial failure, such as one payment method broken, shows up as orders below the band over a whole day, and Callum compares orders per payment method each morning for exactly that.
The job runs every 15 minutes from Solid Queue's recurring schedule39. The schedule and the job:
# config/recurring.yml
production:
order_rate_check:
class: OrderRateCheckJob
schedule: every 15 minutes
# app/jobs/order_rate_check_job.rb
require "net/http"
class OrderRateCheckJob < ApplicationJob
queue_as :monitoring
WEEKS_OF_HISTORY = 8
ALARM_PROBABILITY = 0.001 # alarm when silence this long had less than a 0.1% chance
SYNTHETIC_EMAIL = "synthetic-check@wrenfieldhome.example"
def perform
now = Time.current
last_order_at = real_orders.maximum(:completed_at) || now - 1.day
# How many orders the same stretch of time brought on the same weekday, averaged over 8 weeks
expected = (1..WEEKS_OF_HISTORY).sum { |weeks|
real_orders.where(completed_at: (last_order_at - weeks.weeks)...(now - weeks.weeks)).count
} / WEEKS_OF_HISTORY.to_f
probability = Math.exp(-expected) # chance of no order at all in that stretch
minutes = ((now - last_order_at) / 60).round
Rails.event.notify("orders.silence_check", minutes_without_order: minutes,
expected: expected.round(1), probability: probability.round(5))
if probability < ALARM_PROBABILITY
ping("/fail", "No order for #{minutes} minutes, #{expected.round(1)} expected")
else
ping("") # the ping also proves the check itself still runs
end
end
private
def real_orders
Spree::Order.complete.where.not(email: SYNTHETIC_EMAIL)
end
def ping(suffix, message = nil)
uri = URI(ENV.fetch("ORDER_RATE_HEARTBEAT_URL") + suffix)
message ? Net::HTTP.post(uri, message) : Net::HTTP.get(uri)
end
end
Three details make this work. weeks.weeks moves the window back by calendar weeks in the app's time zone, so the comparison is always the same Tuesday evening stretch even across the change to summer time, which sidesteps the UTC against local time trap that Wrenfield's 3PL data already suffers from. Spree::Order.complete is Solidus's own scope for orders with a completion time. And the job pings its heartbeat every time, so if Solid Queue stops running jobs, the missing ping raises the alarm too. History has to be cleaned of special days: a newsletter send or Black Friday distorts eight weeks of averages, which is why the forecasting chapter on seasonality is worth reading before you trust the expected line. The same thinking, applied to data pipelines instead of orders, is in the data observability chapter.
Alerts that wake you only when it matters
Everything so far produces signals. An alert decides that a signal needs a person. The SRE book is strict about the ones that interrupt someone, which it calls pages: "Every page should be actionable", "Every page response should require intelligence", and pages "should be about a novel problem or an event that hasn't been seen before"1. It suggests three questions for every rule, among them: "Will I ever be able to ignore this alert, knowing it's benign?" and "Does this alert definitely indicate that users are being negatively affected?"1.
Service level objectives and the error budget
A threshold such as "alert on any 5xx" sounds careful and is useless: a shop with millions of requests always has a few. The SRE answer is to agree how good is good enough, and alert only when you are using up that margin too fast.
A service level indicator (SLI) is "a carefully defined quantitative measure of some aspect of the level of service", and a service level objective (SLO) is "a target value or range of values for a service level that is measured by an SLI"4. For a shop: "99.9% of requests over 30 days are answered without a server error". The 0.1% you allow to fail is the error budget:
Here is the error budget in failed requests, the SLO as a fraction (0.999) and the requests in the period (Foundations: percentages).
The SRE workbook then defines the burn rate: "how fast, relative to the SLO, the service consumes the error budget"40. A burn rate of 1 spends exactly the whole budget by the end of the period:
Here is the burn rate, the share of requests failing right now and the SLO (Foundations: ratios and rates). And the share of the budget an alert lets you lose before it fires is:
Here is the share of the budget consumed, the alert's window and the SLO period, in the same unit as (Foundations: ratios and rates). The workbook recommends, for a 99.9% SLO, paging when 2% of the budget is gone in one hour (burn rate 14.4, checked also over 5 minutes), paging when 5% is gone in six hours (burn rate 6, checked also over 30 minutes), and opening a ticket when 10% is gone in three days (burn rate 1, checked also over 6 hours)40. Each alert fires only when both its long and its short window exceed the rate, so it stops quickly once the problem is fixed40.
Example: an error budget for 3.6 million requests
Wrenfield serves 3.6 million requests a month and sets :
So : 3,600 requests may fail in a month. In time, the same budget is 0.1% of 43,200 minutes, about 43 minutes of complete outage. The fast burn page fires at a burn rate of 14.4, which means a failure share of:
So 1.44% of requests failing, sustained over an hour. In an average hour of 5,000 requests that is 72 failed requests. Check the budget: , 2% of the month's budget in one hour, matching the workbook. And note what the rule ignores: a single 5xx, or ten, which would each have been a page under the old "any error" rule.
Low traffic breaks this arithmetic, and the workbook says so: with 10 requests an hour, one failure looks like a huge burn rate40. At night Wrenfield sees about 500 requests an hour, so seven failures would already cross 1.44%. Callum adds a minimum: the page needs at least 1,000 requests in the hour. In Prometheus alerting rules, the for field sets how long a condition must hold before an alert fires41; here the two windows do that job:
# prometheus/rules/shop_slo.yml
groups:
- name: wrenfield-slo
rules:
- record: shop:request_error_ratio:rate1h
expr: |
sum(rate(http_server_requests_total{code=~"5.."}[1h]))
/ sum(rate(http_server_requests_total[1h]))
- record: shop:request_error_ratio:rate5m
expr: |
sum(rate(http_server_requests_total{code=~"5.."}[5m]))
/ sum(rate(http_server_requests_total[5m]))
- alert: ShopErrorBudgetFastBurn
expr: |
shop:request_error_ratio:rate1h > (14.4 * 0.001)
and shop:request_error_ratio:rate5m > (14.4 * 0.001)
and sum(increase(http_server_requests_total[1h])) > 1000
labels:
severity: page
annotations:
summary: "Over 1.44% of requests failing: 2% of the monthly error budget gone in one hour"
runbook: "https://wiki.wrenfieldhome.example/runbooks/error-budget"
The six hour page and the three day ticket follow the same pattern with burn rates 6 and 1. Prometheus sends firing alerts to Alertmanager, which handles "deduplicating, grouping, and routing" them to email, a phone app or a chat channel, and "silencing and inhibition" during planned work42.
Who gets woken, and when
The cost formula from the start of the chapter now earns its place. A broken checkout costs about £432 an hour at 7pm and about £14 at 3am. Waking a part time developer at 3am for £14 an hour is a poor trade, and a tired developer makes the next day's work worse. Callum and Priya agree a written policy:
- 7am to 11pm: pages go to Callum's phone.
- 11pm to 7am: only the synthetic check and a full outage page him. Everything else becomes a ticket for the morning.
- Every page links to a runbook: one page of steps for that alert.
This is a business decision, made with numbers, not a technical one. A shop with heavy night traffic from other time zones would decide differently.
Example: one week of alerts, tuned
Callum's first rules were the usual ones. In the first week they fired 60 times (invented figures). He counted how many of them needed him to act. The share of alerts that needed action is the alert precision:
Here is the number of alerts that needed action and the number of alerts that fired (Foundations: ratios and rates).
| Rule in week one | Fired | Needed action | Change for week two |
|---|---|---|---|
| CPU over 80% for 5 minutes | 14 | 0 | Removed, dashboard only |
| Any 5xx response | 23 | 2 | Replaced by the burn rate rules |
| p95 over 1 second for 5 minutes | 9 | 1 | Checkout pages only, over 1.5 seconds for 15 minutes, as a ticket |
| Disk over 80% | 1 | 1 | Replaced by "disk full within 7 days at the current rate", as a ticket |
| Any failed job | 11 | 1 | Page only for the payments and order email queues, others in a daily summary |
| Uptime check failed | 2 | 0 | Two of three locations, twice in a row |
| Synthetic checkout (new) | 0 | 0 | Added in week two |
| Order rate check (new) | 0 | 0 | Added in week two |
Week one: , about 8%. More than nine alerts in ten trained Callum to ignore his phone.
In week two the rules fired six times. The burn rate rule once, when the courier's API failed for 40 minutes and the fallback rate had a bug. The latency ticket once, for a slow category page with a missing index. The payment queue once. The synthetic check three times: the Tuesday payment form, once because a release renamed the "Continue to payment" button (a fix to the check, still worth knowing), and once on Saturday at 2am when the provider's network had a short fault, which the night policy turned into a morning ticket. Five of six needed action:
Precision rose from to , from 8% to 83%. The goal is not zero alerts. The goal is that when the phone rings, Callum gets up.
Dashboards: one screen that answers "is the shop all right?"
A dashboard is not for watching. Nobody should stare at graphs all day. It is for the two moments that matter: when an alert fires and you need context, and once a week when you look for trends before they become alerts. Grafana is the common open source choice on top of Prometheus43, and the hosted services bring their own.
The first screen should answer one question for Priya as well as for Callum. Everything else goes on a second screen for investigation.
| Panel | What it shows | Why it is on the first screen |
|---|---|---|
| Orders per hour against the expected band | The business view | The one panel Priya reads |
| Synthetic checkout | Last run, result, time to the payment form | Can a stranger buy right now? |
| Failed request share and error budget left | Errors against the SLO | Are errors eating the margin too fast? |
| p95 latency by page type | Product, category, basket, checkout | Is the shop slow, and where? |
| Requests per second | Traffic | Context for everything above |
| Busy Puma threads and database connections | Saturation | How close to full? |
| Job queue waiting time | Jobs waiting in solid_queue_ready_executions | Are emails and stock updates late? |
| New error issues this week | From the error tracker | What changed since the last release? |
Example: Priya's Monday look
Every Monday at 9am Priya opens the first screen for two minutes. This week she sees orders inside the band every day except Tuesday evening, which she knows about. The error budget shows 81% left for the month, so the Tuesday incident and the courier fault together used 19%. Checkout p95 drifted from 0.9 to 1.2 seconds over three weeks. She does not need to know why. She asks Callum for a ticket, and he finds that a new product recommendations block runs four queries per product. A trend caught on a Monday, fixed on a Wednesday, never became an alert. A later chapter in this series, on the performance of a Solidus shop, goes into fixing problems like this one. For now the point is that the dashboard noticed.
Monitoring data is personal data too
Logs, error reports and session recordings are processing of personal data whenever they contain an IP address, an email, a customer id or a free text field. This section is general information about the law in the UK, not legal advice.
The Court of Justice of the European Union held in Breyer (C 582/14, 19 October 2016) that a dynamic IP address can be personal data for a website operator, because the operator has legal means to identify the person behind it with the help of others44. The UK GDPR uses the same definition: personal data is any information relating to a person who can be identified, directly or indirectly, and the definition names an "online identifier" as one way45. So treat the proxy's log line from earlier, with its client address and user agent, as personal data.
What the UK GDPR asks of monitoring data:
- Data minimisation and storage limitation. Article 5 requires personal data to be "adequate, relevant and limited to what is necessary" and kept "for no longer than is necessary"46. The Information Commission's (formerly the ICO's) guidance on storage limitation asks you to set and justify retention periods and to review them47. There is no fixed number of days for logs in the law; you decide and write down why.
- A lawful basis. For security and fault finding, the usual basis is legitimate interests under Article 6(1)(f), with a balancing test. The EU GDPR's recital 49 names network and information security as a legitimate interest48, and the UK GDPR keeps the same Article 6(1)(f).
- Security of processing. Article 32 asks for "the ability to ensure the ongoing confidentiality, integrity, availability and resilience of processing systems and services" and "a process for regularly testing, assessing and evaluating" the measures49. Monitoring is part of how you meet this, and its records help you show it.
- Processors. A hosted log store or error tracker processes the data for you, so it needs a processor contract under Article 28, and transfers outside the UK need a lawful route.
One part changed recently and is good news for monitoring in the browser. The cookie rule in the Privacy and Electronic Communications Regulations (PECR), regulation 6, covers storing or reading anything on a visitor's device, including a JavaScript error tracker that keeps an identifier. Since 5 February 2026, a new Schedule A1, inserted by the Data (Use and Access) Act 2025, lists among the examples of strictly necessary storage or access that it is "to prevent or detect technical faults in connection with the provision of the service requested"50. The Information Commission's guidance lists the same example and warns: "If you use it for any other purpose as well, the exception does not apply"51. So a browser error tracker used only for finding faults can run without consent in the UK. The same tool also used for marketing analytics, or recording sessions to study behaviour, cannot. Server side monitoring touches no device and is outside this rule altogether. On my own site, front end analytics only run after consent.
Example: a retention plan for monitoring data
Callum writes one table into the shop's record of processing:
| Data | Contains | Kept for | Reason |
|---|---|---|---|
| Application logs (JSON events) | Order ids, request ids, no names or emails | 14 days | Finding faults. Anything older is investigated from metrics |
| Proxy logs | IP address, user agent | 14 days | Security and abuse investigation |
| Error tracker events | Stack traces, order ids, scrubbed parameters | 30 days | Long enough to see whether a fix worked |
| Metrics | Counts and durations, no personal data | 13 months | Year on year comparison, including Black Friday |
| Synthetic check results | Timings, pass or fail | 90 days | Trends in checkout speed |
The longest retention sits on the data without personal data. That is the pattern to copy. The privacy engineering chapter shows how to build deletion into the pipeline so the table above is enforced by code, not by memory.
Where to start, in order
Not every shop needs everything on day one. This is the order I would build it in for a shop like Wrenfield Home, each step useful on its own:
- Uptime check and certificate check, from outside. An hour of work. It catches the total outage.
- Error tracking through
Rails.error. A gem and an initialiser. It catches the new bug after a release. - The synthetic checkout check. A day of work, mostly test ids in the storefront. It catches the silent failures.
- Log rotation and structured request events. Half a day. It turns "something happened at 9.41pm" into a query.
- Metrics with the four golden signals, and the burn rate alerts. Two to three days with a hosted service, more if self run.
- The order rate check and the first dashboard. A day, once there are eight weeks of clean history.
- The alert policy, the runbooks, and a review after the first week. Never finished, reviewed every month.
Monitoring also belongs in the release process. I put every release through a test gate and a release register, and the register is what let Callum find the one change in the Tuesday release within a minute. A release is not finished when it deploys. It is finished when the synthetic check passes after it.
My view: for a small shop, the synthetic checkout check is the most valuable single piece of monitoring, more valuable than any metric. A shop with 66 orders a day cannot detect a broken checkout from its order rate in less than an hour at the busiest time, and not at all at night, while every server signal can stay green through a failure in the customer's browser. Build it first after the uptime check, keep it walking right up to the payment form, and treat a failed run as seriously as a failed deploy. Then tune alerts by one measure only: when the phone rings, does the person get up? If not, change the rule, not the person.
Conclusion
Monitoring a Rails shop is five layers that each catch what the others miss. Logs, written as structured events with a request id, answer what happened to one request. An error tracker behind Rails.error tells you what is new. Metrics built on the four golden signals, with percentiles rather than averages and saturation counted in busy threads, show the trend. Uptime and synthetic checks look from the outside, and only the synthetic check proves a stranger can still reach the payment form. Business monitoring compares orders with what the hour should bring, honest about how slowly silence becomes a signal in a small shop.
On top sit alerts built on an error budget and burn rates, a written policy on who gets woken and when, and one dashboard screen that the owner reads too. Keep the personal data in all of it small and short lived, and keep the long history in metrics that contain none.
