Courses / System Design Interview / Chapter 14
Module 3 · Building Blocks II: Monitoring, Caching and Messaging · Chapter 14 of 49
Monitoring Client-Side Errors
Builds on Building Blocks: The Parts Every Design Reuses, Distributed Monitoring: Metrics, Logs and Traces and Monitoring Server-Side Errors. Next up: Distributed Caches.
Part 1 · What servers cannot see
The blind spot
Your server logs show every request that reached your server, and none that did not. A customer in Nagpur whose phone could not resolve your domain name, or whose connection died halfway through the TLS handshake, never appears in them.
This is the case for client-side monitoring: collecting failures from the browser or the app on the user's device and sending them to you. The server errors chapter watched the server from inside and from outside. Both leave a gap, because the last stretch of the journey is the user's network, browser and device, and a lot of things go wrong there.
| What went wrong | Does the server see it? |
|---|---|
| The domain name did not resolve | No. The request never left the device |
| The TLS certificate was rejected | No. The handshake ended before any request |
| The connection timed out on a weak signal | No, or only as a half-open connection |
| The page loaded (status 200) and then a script crashed | Only the 200. The crash happens on the device |
| The app was killed by the phone for using too much memory | No |
| A slow device took eight seconds to draw the page | No. The server sent its reply quickly |
The fourth row is the one that surprises teams. A request that returns 200 is a success on the server's dashboard even when the user sees a blank screen, because the page's own code failed after it arrived. That is a failure the error-rate chart from the server errors chapter cannot show.
Apps add a twist. When a phone app crashes, the process is gone and cannot send anything. The usual design writes a small crash record to local storage as the app dies, and sends it the next time the app starts. The report arrives late, perhaps after a day, and it comes only from users who opened the app again. A user who gave up after the crash is the one you never hear from.
Real users, real devices
The difference in kind is variety. Your servers run a few known configurations. Your users run thousands of combinations of device, operating system, browser version, extension, language and network. A bug that appears on one budget phone with an old browser and an ad blocker is invisible in your tests and common in your users' hands.
Collecting from real users is called real user monitoring (RUM). The alternative, scripted checks from known places, is synthetic monitoring, which is the prober from the server errors chapter applied to the page. The last lesson of this chapter compares them. For now the aim is to see how errors are captured, sent, grouped and kept safe.
Slowness is a failure too, and the browser measures it. The Performance API gives each page a navigation entry, read with performance.getEntriesByType("navigation"). Its timestamps include domainLookupStart and domainLookupEnd for the DNS lookup, connectStart and connectEnd for the connection, responseStart for the first byte of the reply and loadEventEnd for the end of the page's load event. Sending a few of these differences with each report shows where the eight seconds in the table went: in the network, at the server, or on the device.
A browser also hides some detail on purpose. If a script served from another origin throws, the page's error handler gets a muted report with no useful message or location, because the details could reveal private information about the other site. The HTML standard calls these muted errors, and it applies them to scripts fetched cross-origin without CORS. To get full details from a script on a CDN, you load it with the crossorigin attribute and the CDN replies with the right CORS headers.
Which of these can your server logs show: a DNS failure on the user's phone, or a script crash after a 200 response?
- Neither shows up as a failure. In the second case the log has the 200, and the crash happens later on the device.
Why do client errors need data from real users and not just tests?
- Real users have many device, browser and network combinations that tests do not cover.
Part 2 · Capturing errors in the browser
Two events
A browser tells your code about uncaught problems through events on the window object. Two matter most for monitoring. The error event fires when a script throws an exception that nothing catches. Its event object carries a message, the address of the script, a line number and a column number, and the error itself. MDN notes that this event is only generated for errors thrown synchronously, such as during loading or inside an event handler.
The unhandledrejection event covers the other case. A promise that is rejected and has no handler attached does not raise an error event. It fires unhandledrejection instead. The same applies to an uncaught throw inside an async function, which is a rejected promise in disguise. A monitor that listens only for error will miss the failed fetch calls and async code that make up much of a modern page.
A third source is easy to miss. When an image or a script file fails to load, an error event fires on that element and does not bubble, so a normal listener on window never hears of it. A listener registered for the capture phase, addEventListener("error", handler, true), does. In a headless Chrome check made for this page, a missing image reached only the capture-phase listener. Errors that your own code catches with try and catch raise no event at all, so report them yourself where you catch them.
The pattern is the same for both. Listen, build a small report object with the facts you need, and put it in a queue. Sending is a separate step with its own rules, covered in the next lesson. Keeping the two apart matters because the moment of an error is a bad time to start network calls. The page may be in a broken state, the network may be what failed, and you may have many errors in a burst.
The page and the collector
The next run uses real code in a real browser. The page has two buttons. One handler reads a property of a missing cart and throws a TypeError. The other rejects a promise that nobody handles. A small script listens for both events, queues a report for each and sends the queue with navigator.sendBeacon when the page becomes hidden.
<!doctype html> <meta charset="utf-8"> <title>Order page</title> <button id="boom">Place order</button> <button id="reject">Save address</button> <script src="/app.js"></script>
index.html: the page, two buttons and one script
const queue = []; function report(type, detail) { queue.push({ type, page: location.pathname, ...detail }); } window.addEventListener("error", (e) => { report("error", { message: e.message, source: e.filename, line: e.lineno, col: e.colno }); }); window.addEventListener("unhandledrejection", (e) => { report("unhandledrejection", { message: String(e.reason) }); }); document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden" && queue.length) { navigator.sendBeacon("/collect", JSON.stringify(queue.splice(0))); } }); document.getElementById("boom").onclick = () => { const cart = null; console.log(cart.items.length); }; document.getElementById("reject").onclick = () => { Promise.reject(new Error("address service timed out")); };
app.js: capture both events, send the queue when the page is hidden
The collector is a Python server on port 55466. It serves the page and the script on GET, and on POST it prints what it received. Printing is the only thing it does with the reports, to make the run readable.
import json import textwrap from http.server import BaseHTTPRequestHandler, HTTPServer FILES = {"/": ("index.html", "text/html"), "/app.js": ("app.js", "text/javascript")} class H(BaseHTTPRequestHandler): def log_message(self, *args): pass def do_GET(self): name, ctype = FILES.get(self.path, (None, None)) if not name: self.send_response(404) self.end_headers() return body = open(name, "rb").read() self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
collector.py, part 1: serve the page and the script
def do_POST(self): size = int(self.headers["Content-Length"]) reports = json.loads(self.rfile.read(size)) print("POST", self.path, self.headers["Content-Type"], len(reports), "reports", flush=True) for r in reports: for k, v in r.items(): text = textwrap.fill(f"{k}: {v}", 64, subsequent_indent=" ") print(textwrap.indent(text, " "), flush=True) print(flush=True) self.send_response(204) self.end_headers() HTTPServer(("127.0.0.1", 55466), H).serve_forever()
collector.py, part 2: print each POSTed report
Running it in headless Chrome
The driver is a Node script. It starts the collector, launches the installed Chrome without a window through playwright-core, the browser-automation library, loads the page, clicks both buttons and then navigates the tab to about:blank. Leaving the page makes it hidden, which fires the visibilitychange event and triggers the send.
import { spawn } from "node:child_process"; import { chromium } from "playwright-core"; const wait = (ms) => new Promise((r) => setTimeout(r, ms)); const collector = spawn("python", ["collector.py"], { stdio: "inherit", }); await wait(800); const chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe"; const browser = await chromium.launch({ executablePath: chrome, headless: true, }); console.log("Chrome", browser.version()); const page = await browser.newPage(); await page.goto("http://127.0.0.1:55466/"); await page.click("#boom"); await page.click("#reject"); await wait(200); await page.goto("about:blank"); // the page goes away and turns hidden await wait(500); await browser.close(); collector.kill();
drive.mjs: start the collector, drive Chrome, stop the collector
Chrome 157.0.8103.80 POST /collect text/plain;charset=UTF-8 2 reports type: error page: / message: Uncaught TypeError: Cannot read properties of null (reading 'items') source: http://127.0.0.1:55466/app.js line: 24 col: 20 type: unhandledrejection page: / message: Error: address service timed out
Chrome 157.0.8103.80, playwright-core 1.65.0, Node 24.18.0 and Python 3.12.10. The same output came back on each run made here.
One POST arrived with both reports. The first is the TypeError: Chrome gives the message, the address of the script, line 24 and column 20, which point at cart.items in app.js. The second is the rejected promise, with the text of the error that was thrown. This is what the team would see in place of silence.
The body went out as text/plain;charset=UTF-8, not as JSON, because sendBeacon with a string sends a plain-text body. The collector parsed the body as JSON itself and ignored the declared type, which a real collector must do as well. Sending a Blob with a JSON type is another way, but for a collector on another origin it may trigger an extra preflight request, so a plain string is the simple choice.
Why listen for unhandledrejection as well as error?
Part 3 · Getting reports out safely
Sending when the page is going away
The hardest moment to send is when the user leaves. A normal fetch or XHR started as a page unloads may not complete. navigator.sendBeacon(url, data) was built for this: it asks the browser to queue a POST and returns at once with true if the data was queued and false if it was not. It is POST only, and MDN gives 64 KiB as the limit on the total queued data. If you need another HTTP method, custom headers or the response, use fetch with keepalive: true, which also outlives the page. MDN gives the same 64 KiB limit for the body of a keepalive request, so neither call can carry a large upload at exit. Send big payloads earlier, while the page is still open.
When to call it also matters. The old choices, unload and beforeunload, are unreliable, especially on phones where the browser may be closed from the app switcher without either event firing. MDN also notes that unload is incompatible with the back/forward cache, the browser feature that keeps recent pages ready to reopen at once. MDN recommends visibilitychange, and sending when document.visibilityState becomes hidden, which is what app.js did.
A buffered design follows from this. Keep reports in a queue. Send the queue when it grows past a limit, on a timer, and on hidden. Cap the queue, so a loop that throws a thousand times a second cannot grow memory or flood the collector. Dropping extra errors from the same place is better than sending them all.
The Reporting API and NEL
Some failures can never be caught by your page's code: the page never loaded. Browsers have a built-in way to report some of them. The Reporting API lets a server declare where the browser should send reports, using the Reporting-Endpoints response header, a list of names and URLs. The browser then sends reports as a POST with the content type application/reports+json. Each report is a JSON object with a type, an age in milliseconds since it was generated, the page url, the user_agent and a body. Delivery is best effort.
Network Error Logging (NEL) uses that mechanism to report network failures. The server sends a NEL header with a JSON policy. report_to names the endpoint group, max_age is how long to keep the policy in seconds, and a max_age of 0 removes it. failure_fraction is the share of failed requests to report, and if absent every failure is reported. success_fraction is the share of successful requests to report, and if absent none are. Reports say in which phase the failure happened, dns, connection or application, and give a type such as dns.name_not_resolved, tcp.timed_out, tls.cert.invalid or http.error.
This answers the first rows of the table at the start of the chapter. The browser remembers the policy from an earlier visit and reports a DNS failure, later, from a device that could not reach your server at all, as long as the report endpoint is on a host it can still reach. Both specifications are W3C Working Drafts at the time of writing, dated 11 June 2025 for Reporting and 5 May 2025 for NEL. Both require a potentially trustworthy origin: Reporting ignores endpoints that are not, and NEL only processes a policy from such an origin. On the public web that means HTTPS.
The headers in practice
The program starts a server that sets both headers and calls itself with curl -i, which prints the response headers. The endpoint URL is a placeholder on example.com.
import json import subprocess import threading from http.server import BaseHTTPRequestHandler, HTTPServer NEL = {"report_to": "default", "max_age": 86400, "failure_fraction": 0.5} class H(BaseHTTPRequestHandler): def log_message(self, *args): pass def do_GET(self): self.send_response(200) self.send_header("Reporting-Endpoints", 'default="https://example.com/reports"') self.send_header("NEL", json.dumps(NEL, separators=(",", ":"))) self.send_header("Content-Length", "0") self.end_headers() srv = HTTPServer(("127.0.0.1", 55467), H) threading.Thread(target=srv.serve_forever, daemon=True).start() subprocess.run(["curl", "-s", "-i", "http://127.0.0.1:55467/"]) srv.shutdown()
headers_server.py: send Reporting-Endpoints and NEL, then show them with curl
HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.12.10 Date: Sun, 22 Nov 2026 13:54:10 GMT Reporting-Endpoints: default="https://example.com/reports" NEL: {"report_to":"default","max_age":86400,"failure_fraction":0.5} Content-Length: 0
Python 3.12.10 and curl 8.21.0. The Date line changes on every run.
The Reporting-Endpoints line names one endpoint, default. The NEL line points at it with report_to and asks to keep the policy for a day, 86,400 seconds, and to report half of all failures. A busy site that sets failure_fraction below 1 trades completeness for volume, the same trade as the sampling in the next lesson.
What this run does not show is a report being delivered. A separate attempt asked headless Chrome to deliver a Reporting API report, a report-only content security policy violation on a page at 127.0.0.1 with a same-origin endpoint, and no report arrived within 75 seconds. The cause was not found. The trustworthy-origin rule does not explain it, because the specifications count a loopback address such as 127.0.0.1 as potentially trustworthy. NEL delivery needs a real network failure on a site that set the policy earlier, and it was not attempted. So this lesson shows the headers only, and what happens after them rests on the specifications.
Why is visibilitychange a better moment to send than unload?
Part 4 · Aggregation, fingerprints and sampling
One bug, ten thousand reports
A bug in a checkout page can send a report from every affected user. If you store and show each one, the team sees a wall of near-identical lines. Aggregation merges reports that mean the same thing into one group with a count, and shows the groups instead.
The rule for deciding that two reports are the same is a fingerprint: a short hash computed from the parts of a report that identify the bug and nothing else. Good ingredients are the error type, the message with its variable parts removed, and the function at the top of the stack. Bad ingredients are anything that changes from one occurrence to the next: order numbers inside messages, timestamps, user ids, and the line number, which shifts every time the code changes. The program below applies two of these ideas: it replaces digits in messages and ignores the line number.
Production code is usually minified into one long line with short names, so a raw frame reads like a (app.min.js:1:48213). A source map is a file made by the build that maps each position in the transformed code back to the original file, line and name. The collector keeps the map for each release and translates frames before fingerprinting, so the group shows placeOrder in checkout.js. Tag every report with its release version so the right map is used, and keep the maps off the public site if you do not want to publish your source.
Two reports are the same bug if their fingerprints match. The count per fingerprint is the metric you chart and alert on, the share of users affected is what you prioritise by, and one sample report in each group is what the developer reads.
Grouping 500 reports
The program invents 500 reports from four made-up bugs, with weights 60, 25, 10 and 5. One message contains an order number, and the line number of the stack frame varies between two values to imitate different builds. It first prints how many distinct raw messages there are. It then fingerprints each report by replacing digits in the message and dropping the line from the frame.
import hashlib import random import re from collections import Counter random.seed(3) BUGS = [(60, "placeOrder", "Cannot read properties of null"), (25, "loadAddress", "Order {n} not found"), (10, "renderCart", "x is not a function"), (5, "applyCoupon", "Unexpected token < in JSON")] def make_report(): _, fn, msg = random.choices(BUGS, [b[0] for b in BUGS])[0] line = random.choice([24, 24, 25]) # shifts between builds return {"message": msg.format(n=random.randint(1000, 9999)), "frame": f"{fn} (app.js:{line})"} def fingerprint(r): text = re.sub(r"\d+", "N", r["message"]) # drop ids func = r["frame"].split(" ")[0] # drop line numbers return hashlib.sha1(f"{text}|{func}".encode()).hexdigest()[:8], func reports = [make_report() for _ in range(500)] full = Counter(fingerprint(r) for r in reports) sampled = Counter(fingerprint(r) for r in reports if random.random() < 0.10) print("distinct raw messages:", len({r["message"] for r in reports})) print("group all 10% sample x10 function") for (fp, fn), n in full.most_common(): print(f"{fp} {n:>5} {sampled[(fp, fn)] * 10:>12} {fn}")
group.py: fingerprint 500 reports and compare with a 10% sample
distinct raw messages: 103 group all 10% sample x10 function 885cecb0 308 320 placeOrder 727ed475 101 70 loadAddress 256882ce 65 90 renderCart a6f91d46 26 20 applyCoupon
Python 3.12.10. The random seed is fixed, so this output repeats.
There are 103 distinct raw messages, because the order id makes almost every Order N not found report unique. Grouping by raw text would show over a hundred lines. The fingerprint reduces them to four groups, one per bug, and the biggest, placeOrder, accounts for 308 of 500 reports.
The last column shows what happens when you keep only 10% of reports and multiply by ten. The big group comes out at 320 against 308, close. The small groups are rougher: 20 against 26 for applyCoupon, and 70 against 101 for loadAddress. Sampling keeps the biggest group clearly on top but loses precision on small ones, and can even swap two close groups: here the sample ranks renderCart (90) above loadAddress (70), the reverse of the full counts (65 against 101), so it suits dashboards and trends better than exact counts.
Sampling and the collector's scene
A site with crores of page views cannot afford to store every report, and often does not need to. Sampling keeps a fraction. The choice of what to sample matters. Sample per session, the visit of one user, and not per report, so that you get whole stories. Make the choice from a hash of the session id, so that a session is either in or out from the start. Never drop a report for a new fingerprint, so that a new bug always shows up, and sample the common ones.
Each sampled report should carry its sampling rate, so that the counts can be scaled back up. This is the same idea as the sampling fraction that NEL reports carry in their body, which tells the receiver how to scale counts back up.
The scene follows reports through the system. Clients queue their errors and send beacons. The collector accepts them and hands them to an aggregator that groups by fingerprint. When one group's count jumps, an alert fires.
Watch for the beacons: each client queues errors and sends them later
Read it as steps
Clients send error beacons to a collector, an aggregator groups them, and a rising group fires an alert.
Part 5 · Privacy, and real-user versus synthetic monitoring
Reports contain more than you intend
An error report is written by a program that does not know what the data means. A message can include the address of the page, with a token in its query string. It can hold the text a user typed into a field. The report has the user agent and, once it reaches a server, the IP address, so a pile of reports is a pile of personal data.
The OWASP cheat sheet on logging lists what should never be recorded directly: access tokens and session ids, passwords, connection strings, keys and other secrets, payment card data, and sensitive personal data, which includes government identifiers. If it must be recorded, it is removed, masked, hashed or encrypted first. Client reports fall under the same rule. Personal data collected from users usually also falls under privacy law and under your own privacy notice, so the safe habit is to collect the least that lets you fix the bug.
- Redact on the device, before sending, so that secrets never travel.
- Redact again on the collector, in case a client is old or wrong.
- Do not collect field contents, cookies or whole URLs with query strings unless a rule says to.
- Keep reports for a short, stated time and delete them after.
A redaction pass
The program applies four rules to four made-up messages: an email address, a ten-digit phone number starting with 0 to 5 (a made-up range), a run of 13 to 16 digits that looks like a card, and the value of a token, key or session parameter in a URL.
import re RULES = [ (re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"), "[email]"), (re.compile(r"(?<!\d)[0-5]\d{9}(?!\d)"), "[phone]"), (re.compile(r"(?<!\d)(?:\d[ -]?){12,15}\d(?!\d)"), "[card]"), (re.compile(r"([?&](?:token|key|session)=)[^&\s]+"), r"\1[secret]"), ] def redact(text): for pattern, repl in RULES: text = pattern.sub(repl, text) return text reports = [ "Failed to fetch https://shop.example.com/cart?token=a1b2c3d4&v=2", "Invalid address for asha.rao@example.com, phone 5001234567", "Card 1234 5678 9012 3456 was rejected", "Cannot read properties of null (reading 'items')", ] for r in reports: print("before:", r) print("after: ", redact(r))
redact.py: replace emails, phones, card-like numbers and secrets
before: Failed to fetch https://shop.example.com/cart?token=a1b2c3d4&v=2 after: Failed to fetch https://shop.example.com/cart?token=[secret]&v=2 before: Invalid address for asha.rao@example.com, phone 5001234567 after: Invalid address for [email], phone [phone] before: Card 1234 5678 9012 3456 was rejected after: Card [card] was rejected before: Cannot read properties of null (reading 'items') after: Cannot read properties of null (reading 'items')
Python 3.12.10. Deterministic.
Each rule turned its match into a label. The URL kept its host and path, which helps debugging, and lost its token. The message with no personal data came through unchanged, which shows that redaction should be narrow. Rules like these are a net, not a guarantee: a number in an unusual format will slip through, which is why the first line of defence is to avoid collecting fields that might hold secrets.
A card-like pattern of 13 to 16 digits also matches other long numbers, such as an order number of that length. A rule that errs on the side of hiding is the right trade for secrets, and the cost is that some harmless numbers are hidden.
Real-user and synthetic monitoring
Last, the two ways of watching the client side. Real user monitoring gathers data from actual visits. Synthetic monitoring runs scripted visits from chosen places on a schedule. They answer different questions.
| Real user monitoring | Synthetic monitoring | |
|---|---|---|
| Source | Actual users' browsers and apps | Scripts run from known locations |
| Sees | Real devices, networks, behaviour | A controlled, repeatable journey |
| Traffic needed | Yes. No users means no data | No. Works at 3 am and before launch |
| Noise | High: every device and network differs | Low: the same steps every time |
| Best for | How the product feels to people, and long-tail bugs | Catching a broken page fast, and watching a steady baseline |
| Privacy | Collects from users, so needs care | No user data |
Use both. Synthetic checks tell you within a minute that the login page is broken, even at night with no traffic. Real-user data tells you that it is only broken on one browser version, and for what share of people. The synthetic probe from the server errors chapter is the first kind, and the beacons in this chapter are the second.
| Term | Meaning |
|---|---|
| Client-side monitoring |