Frontend System Design · Lesson 14 of 15 · 5 min
Observability, Monitoring, & Logging
This is how you prove you can own a feature in production, not just ship it.
In a system design interview, describing how you would observe a system after launch is as important as describing how you would build it. When an interviewer asks "how do you know it's working?", this is your playbook. It shows you think about reliability, performance, and the full lifecycle of a feature.
The Three Pillars: Logs, Metrics, and Traces
Everything you collect from a running application falls into one of three categories. Don't confuse them.
Logs are discrete, timestamped events. A log tells you what happened at a specific point in time. Think of a user logging in, an API call failing, or a component rendering. Raw console.log('User clicked button') is an unstructured log. It's for humans, not machines. In production, you need structured logs, usually JSON, that can be indexed and queried.
{
"timestamp": "2023-10-27T10:00:05.123Z",
"level": "INFO",
"message": "User login successful",
"userId": "u-123",
"traceId": "abc-456-def"
}
Metrics are numerical measurements over time. They are aggregated to give you a high-level view of system health. Is the site slow? Is it throwing errors? Metrics answer these questions. Key types include:
- Counter: A value that only goes up (e.g., total requests, errors logged).
- Gauge: A value that can go up or down (e.g., current active users).
- Histogram: Tracks the distribution of values, like request latency. This is how you calculate percentiles (p95, p99), which are far more useful than averages.
Traces (or Distributed Traces) show the lifecycle of a single request as it moves through multiple services. A trace is made of spans, where each span represents one unit of work (e.g., a frontend API call, a backend service handling that call, a database query). They are stitched together with a unique traceId. This is how you debug a slow request in a microservices architecture.
Instrumenting Your Frontend
You can't observe what you don't measure. "Instrumenting" is the work of adding code to your app to emit logs, metrics, and traces.
For logging, ditch console.log in production code. Create a simple, centralized logger that outputs structured JSON. This makes your logs searchable and allows you to attach consistent context to every message.
enum LogLevel {
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR',
}
// In a real app, this would send logs to a service (e.g., Datadog, Splunk)
// using navigator.sendBeacon() to avoid blocking the main thread.
function sendLog(level: LogLevel, message: string, context: object = {}) {
const logEntry = {
timestamp: new Date().toISOString(),
level,
message,
url: window.location.href,
...context,
};
// For demo, we log the JSON string.
console.log(JSON.stringify(logEntry));
}
// --- Usage ---
// Log informational events with context
sendLog(LogLevel.INFO, 'User opened checkout page', { cartSize: 3 });
// Log warnings for non-critical issues
sendLog(LogLevel.WARN, 'API response took longer than expected', { durationMs: 1500 });
// Log errors with stack traces and relevant IDs
try {
// ... some operation that might fail
throw new Error('Payment provider unavailable');
} catch (error: any) {
sendLog(LogLevel.ERROR, 'Payment submission failed', {
errorName: error.name,
errorMessage: error.message,
// stack: error.stack, // Be careful with PII in stack traces
});
}
For metrics, focus on what matters to the user. Start with the Core Web Vitals (LCP, CLS, INP) provided by the browser. For custom interactions, use the Performance API to create high-precision marks and measures (performance.mark, performance.measure). This is how you can answer "how long did it take from button click to the results rendering?".
For errors, you must capture unhandled exceptions. Use global handlers like window.onerror and window.addEventListener('unhandledrejection', ...). These are your safety nets. Send this data to an error tracking service (like Sentry or Bugsnag) with as much context as possible: user ID, browser version, app version, and the last few user actions (a "breadcrumb trail").
How to Answer "How Would You Debug This?"
This is the most common interview scenario for this topic. The interviewer will say, "Users are reporting the checkout page is slow. What do you do?"
Your answer should follow a "top-down" approach, moving from broad monitoring to specific logs.
First, I'd check our monitoring dashboards. I'd look at the key performance metrics for the checkout page: p95/p99 latency for API calls, the page's Core Web Vitals (LCP, INP), and the client-side error rate. This tells me the scale of the problem. Is it affecting all users or just those on a specific browser or in a certain region?
This shows you start with high-level data (metrics) to confirm and scope the problem.
If a specific API endpoint, like
/api/submit-payment, shows high latency, I'd move to our distributed tracing tool. I'd find a few example traces for slow requests to that endpoint. The trace will show a flame graph of all the downstream services it called and pinpoint which one is the bottleneck.
This demonstrates you know how to isolate the problem in a distributed system (traces).
Once the trace points to a specific backend service as the source of latency, I'd use the
traceIdfrom the slow request to find all the logs associated with it in our logging platform. This would give me the ground-level truth of what that service was doing—the exact database queries it ran, any errors it encountered, or any slow downstream calls it made.
This is where you find the root cause (logs).
This flow—from metrics to traces to logs—is the standard, professional way to debug a production issue.
The Traps and Trade-offs
The trap: Alert fatigue. Don't say you'll "alert on everything." An alert that isn't actionable is just noise. A good alert fires on a symptom that directly impacts users (e.g., "Checkout success rate dropped 10%") not an indirect cause (e.g., "CPU on server X is at 80%").
The trap: Forgetting the user's perspective. Server-side monitoring is only half the story. Real User Monitoring (RUM) captures metrics directly from your users' browsers. This is the only way to know if a user in a specific country on a specific mobile browser is having a bad experience. Contrast this with Synthetic Monitoring, which runs automated scripts to check if your site is up and key flows work. You need both.
The trade-off: Cost vs. Data. Observability is not free. Ingesting, indexing, and storing terabytes of logs and metrics is expensive. Acknowledge this. Show you're pragmatic by mentioning sampling. For example, you might only keep 100% of logs for errors, but sample 10% of successful requests for tracing. This gives you enough data to debug without bankrupting the company.
Try it
Instrument a small project with a basic structured logger like the one above. Add a global window.onerror handler that uses your logger to format and console.log a JSON object for any unhandled error. Trigger an error and see the structured output.
Next: We'll cover how to keep your app running when the network fails in Offline-First & Progressive Web Apps (PWAs).
Lock it in — apply this lesson under interview conditions.