AlgoViz

Monitoring server-side errors

medium 30 min

Catch errors in one place, add the facts that explain them, group the same fault into one issue, count them as a share of all requests, and call a person only when users are hurt.

Video lesson · Chapter 1 of 6

Turn an exception into an incident signal

0:00 / 4:01

Theory

Read or listen first. About 1 min.

What it is

Server-side error monitoring means finding, recording, grouping and reporting the errors that happen inside your own services.

Two tools share the work. Metrics count errors: how many, which share, since when. An error tracker keeps single errors with their stack trace and groups equal ones. Metrics wake people. The tracker tells them what to repair.

Why it exists

Most users who meet an error never write to you. They leave. If you wait for letters you learn about a fraction of the faults, hours late.

Raw errors are too many to read. One broken line of code can raise five thousand errors in a minute. Grouping makes one issue of them, with a count.

And not every error deserves a call at night. A clear rule, based on what was promised to users, keeps the team calm and the calls rare.

A short history

  1. May 1996

    RFC 1945 describes HTTP/1.0 with the 500, 501, 502 and 503 status codes.

  2. April 2012

    RFC 6585 adds 429 Too Many Requests.

  3. June 2022

    RFC 9110 becomes the common definition of HTTP status codes for all versions.

  4. July 2023

    RFC 9457 defines problem details, a standard JSON answer for errors.

Words to know

Exception
A signal in a program that something unusual happened. It can be caught.
Stack trace
The list of calls that led to the exception.
Fingerprint
A short key. Errors with the same key belong to the same issue.
Issue and event
One fault, and one time it happened.
SLI
What you measure, such as the share of good requests.
SLO
The target for it, such as 99.9%.
SLA
A contract with consequences, usually weaker than the SLO.
Error budget
What the target allows to fail: 0.1% for 99.9%.
Alert fatigue
People stop reacting because most alerts mean nothing.

Understand it

Start here

Burnt pancakes

The pancake kitchen

Nobody throws a burnt pancake away without a note.

In the kitchenIn the system
Burnt pancakeFailed request
CardContext of the error
PlatesIssues, grouped by fingerprint
Share on the boardError rate
Tokens in the jarError budget

The idea

Six goals

What good error monitoring gives

  • Detection

    You know within minutes.

  • Grouping

    Equal errors are one issue.

  • Priority

    Many users or money first.

  • Alerting

    The right person, at the right time.

  • Context

    Enough facts to repair it.

  • Trends

    More or fewer than last week, and since which release.

Codes

Whose fault is it?

CodeMeaningWhat to do
400Bad inputCount. A jump after a release is ours
401, 403Not signed in, not allowedCount. A jump may be a broken login or an attack
404Not foundCount. A jump may be a broken link of ours
429Too many requestsCount. Check the limit
500Our program failedIssue
502A server behind us answered badlyLook at that service
503Overloaded or in maintenanceCapacity; tell clients when to come back
504A server behind us was too slowLook at timeouts
RFC 9110: 4xx means that the request cannot be fulfilled as sent, 5xx that the server failed to fulfil an apparently valid request.

What to do with a failed request

Codes made by the load balancer itself are a separate case. See load balancer monitoring.

Kinds

Six families of errors

FamilyExamplesFirst severity
RuntimeNull pointer, TypeError, IndexErrorHigh
DatabaseConnection timeout, deadlock, failed queryCritical
Other servicesHTTP timeout, DNS, certificateHigh
ResourcesOut of memory, disk full, no free threadCritical
ValidationBad JSON, missing field, wrong typeLow
Login and rightsInvalid token, expired session, deniedMedium
A start for sorting. How many users are hurt decides in the end.

Three words

WordMeaning
ErrorA wrong state. In Java also a class for serious problems that a reasonable program should not catch, such as no memory
ExceptionA signal that can be caught and handled
FailureUsers do not get what they expect
An exception that is retried with success is no failure. A wrong total without any exception is one.

The whole

From a throw to a call

Two paths

Users call a service. Its error handler sends events to an error tracker and counts to a metrics store. The metrics store sends alerts to the person on call, who opens the tracker.
Orange: details of single errors. Pink: counts. The alert comes from the counts.

One exception

The user gets an answer first. Reporting must never make an error slower.
  1. 1

    Capture

    One middleware at the edge of the service catches what nobody else caught. Workers and scheduled jobs need the same.

  2. 2

    Enrich

    Add the trace id, the route, the release, the pseudonym of the user.

  3. 3

    Send

    In the background, with a limit. If the tracker is down, drop and count.

  4. 4

    Group

    Make a fingerprint, so that 5,234 events become one issue.

  5. 5

    Alert

    Rules on shares, on new issues and on the budget.

Context

What to write on the card

AboutKeepLeave out
RequestRequest id, trace id, method, routeFull body, cookies, authorization header
UserInternal id, session as a hash, browserName, e-mail, full address
ErrorType, message, stack, cause, own error codeValues inside the message
PlaceService, release, host, environment, timeEnvironment variables
Hashing an internet address is weak protection: all IPv4 addresses can be tried. Shorten it instead.
Text
DatabaseError: Connection timeout after 30000ms  at PaymentService.processPayment (app/services/payment.ts:45)  at async OrderController.createOrder (app/controllers/order.ts:23)  at async Router.handle (node_modules/express/lib/router.js:234)
A stack trace. The first line of our own code matters most: payment.ts, line 45.
JSON
{  "type": "https://example.com/errors/unavailable",  "title": "Payment is not available right now",  "status": 503,  "request_id": "req-7f3a"}
What the user gets: problem details as in RFC 9457. No stack, no names of classes, but an id to quote.

The trace id joins the error with the lines of other services. How it travels is told in inside a logging service.

Group

Fingerprints

A fingerprint is built from what stays the same each time: the type of the error and the first frame of your own code. What changes each time must be removed first.

GoodBadWhy bad
Type and first own frameRequest idAlways different: one issue per event
Service and message without valuesTimeAlways different
Own key: database, tableFull message with valuesOne issue per order
Other service and its statusType aloneDifferent faults in one issue
Python
import redef normal(message):    message = re.sub(r"[0-9a-f]{8}-[0-9a-f-]{27}", "<id>", message)    return re.sub(r"\d+", "<n>", message)def fingerprint(kind, message, frame):    return (kind, frame or normal(message))a = fingerprint("Timeout", "order 41 took 30012 ms", "payment.ts:pay")b = fingerprint("Timeout", "order 97 took 30555 ms", "payment.ts:pay")print(a == b, normal("order 41 took 30012 ms"))
Remove the values, then build the key.
Edit and run it in your browser

Leave the line number out of the key, or each release makes new issues. Use file and function. Sentry groups by default by fingerprint, which it derives from stack trace, exception and message, and lets you set your own.

Too many

Sampling an error storm

WayRuleGood for
First onesThe first N of each issueNew faults: full detail at once
Rate limitAt most N per minute and issueStorms
Random10% of allSaving money on frequent ones
Combine them: the first 100 of an issue, then 10%, at most 60 a minute.

Promise

Error budgets

WordMeaningExample
SLIWhat is measured99.2% of requests succeed
SLOWhat we aim for99.9%
SLAWhat the contract says99.5%, or money back

The budget of a month

0.1%×30×24×60=43.2 minutes0.1\% \times 30 \times 24 \times 60 = 43.2\ \text{minutes}
For 99.9%. Counted in requests: of 10 million, 10,000 may fail.

Where are we?

43.2−1443.2≈68% left\frac{43.2 - 14}{43.2} \approx 68\%\ \text{left}
14 minutes used after 12 of 30 days. So far 14 of 17,280 minutes were bad: 99.92% success. At this speed 35 minutes will be used in the month.

While there is budget, the team may take risks and release often. When it is empty, work on reliability comes first until it fills again. The rule is agreed before, with the product owner, or it will be discussed at the worst time.

Alerts use the burn rate, the speed at which the budget goes. The rules with two windows are in load balancer monitoring. What nines mean for design is in high availability.

Call

Alerts people trust

Alert on

  • A rising share of errors.
  • Budget burning fast.
  • A new kind of error after a release.
  • Many users hit by one issue.

Do not alert on

  • Each single error.
  • Expected errors such as rate limits.
  • What nobody can act on.
  • Numbers without an owner.

Severity

LevelExampleReaction
P1Service is downPage at once
P2Main function broken, over 10% of usersPage, start within 15 minutes
P3Small function worse, under 1% of usersNext working day
P4Noise, warningsTicket
Between 1% and 10% the team decides. Write down which way.
promql
# more than 1% of requests failsum(rate(http_requests_total{status=~"5.."}[5m]))  / sum(rate(http_requests_total[5m])) > 0.01# less than a quarter of the budget left: a ticketslo:error_budget_remaining < 0.25# P99 over 2 secondshistogram_quantile(0.99,  sum by (le) (rate(http_duration_seconds_bucket[5m]))) > 2
Three rules. Sums first, so that labels on both sides match.

Should it ring now?

A share needs traffic. At night one failure of three requests is 33%. Require a minimum number of errors too.

Life of an issue

Regressed issues deserve an alert: the repair did not hold.

Silent

Failures without an error

Silent failureHow to see it
Answer 200 with an error insideCheck the content with a probe, count business results
An exception swallowed by an empty catchRule in code review, lint
A message that fails again and againLength and age of the dead letter queue
A job that did not runAlert when the last success is too old
Retries hide a sick serviceCount each attempt, not only the last

Errors users meet before they reach the server have a page of their own: client-side errors.

Summary

The whole topic in one minute.

Capture in one middleware, enrich with request, user, code and environment, send without blocking, group by a stable fingerprint, and alert on shares of requests.

5xx is ours, 4xx is usually the caller's, and silent failures have no status at all: check results, not only codes. Spend the error budget on purpose and slow down changes when it is gone.

  • Capture, enrich, send, group, alert.
  • Metrics count all; the tracker keeps examples.
  • 5xx is ours; a jump of 4xx may be too.
  • Fingerprint: type and own frame, no values.
  • Share of requests, with a minimum, against a promise.
  • Look for failures without an error.

Sources