At 10:30 you deploy v2.3.1. A minute later the team chat is full of messages: checkout is failing, and the error rate (the percentage of requests that fail) has jumped from 5% to 50%. The temptation is to open the code right away and look for the broken line. But while you read, half the buyers keep failing to pay.
That's a production incident: trouble in the app real users are using right now, such as a failing checkout, error pages, or a slow API. Debugging it is different from debugging on your laptop, because every minute that passes, more users get hit. The order is: stop the damage first, find the cause next, then write the cause down so it doesn't happen again. It's like a leaking gas stove hose: you shut the regulator first, then look for the cracked part of the hose. Shutting the regulator is stopping the damage, and looking for the cracked part is looking for the cause of the bug.
Why production is different
- No breakpoints. A debugger stopped at a breakpoint freezes the process (the program running on the server). In Node.js, every request is served by the same single thread (line of work). So once the process stops, every user's request hangs with it.
- Hard to reproduce. The data is real, there are thousands of users, and the bug often only appears for a combination that staging (a copy of the app for testing) doesn't have.
- Different tools. What you rely on is logs, error monitoring (the previous lesson), metrics (numbers that are measured all the time) such as the error rate, and tracing (a record of one request's journey).
Steps in an incident
- Detect: an alert (an automatic warning) fires, or a user reports it.
- Triage: decide how bad it is, which feature, and how many users are hit.
- Mitigate: stop the damage. Roll back, turn off a feature flag, or pull the canary (all three are explained below).
- Investigate: find the root cause (the real cause) through logs, traces and error monitoring.
- Fix: repair it, test it in staging, then deploy.
- Postmortem: write down what happened and what changes so it doesn't happen again.
Mitigation comes before investigation. If the last deploy pushed the error rate to 50%, go back to the previous version or turn the feature off first. Only after that, look for the broken line calmly.
Detect: error rate and anomalies
The error rate is the percentage of requests that failed in a time window, for example the last 60 seconds. In the exercise, the window is measured back from the newest event (the most recent recorded request), not from the clock right now, so data that has already passed can still be analysed. This way is for analysing stored data. An alert that watches production right now measures from the current clock instead. For example, if the five events below happened 2 hours ago, the function below still returns 40, although no request is failing now. These are the five events from the exercise (times in milliseconds, now = the current time):
| Event | type | timestamp | In the 60,000 ms window? |
|---|---|---|---|
| 1 | success | now - 5000 | yes |
| 2 | success | now - 4000 | yes |
| 3 | error | now - 3000 | yes |
| 4 | error | now - 2000 | yes |
| 5 | success | now - 1000 | yes, this is the newest |
Total 5, errors 2, so the error rate is 2 / 5 = 40%.
Then, which minute looks wrong? An anomaly here means a minute's error rate above twice the average of all the minutes. The per-minute error rates [5, 4, 6, 50, 5] average 70 / 5 = 14, so the limit is 28. Only 50 goes over that limit, in minute 4 (index 3). This code calculates the error rate and the anomalies:
function analyzeErrorRate(events, windowMs = 60000) {
if (events.length === 0) return { errorRate: 0, total: 0, errors: 0 };
const newest = Math.max(...events.map((e) => e.timestamp));
const inWindow = events.filter((e) => newest - e.timestamp <= windowMs);
const errors = inWindow.filter((e) => e.type === 'error').length;
return {
errorRate: Math.round((errors / inWindow.length) * 100), // percent, whole number
total: inWindow.length,
errors: errors,
};
}
function detectAnomalies(rates) {
const average = rates.reduce((a, b) => a + b, 0) / rates.length;
return rates.map((rate, index) => ({ index, rate, isAnomaly: rate > 2 * average }));
}
const now = Date.now();
const events = [
{ type: 'success', timestamp: now - 5000 },
{ type: 'success', timestamp: now - 4000 },
{ type: 'error', timestamp: now - 3000 },
{ type: 'error', timestamp: now - 2000 },
{ type: 'success', timestamp: now - 1000 },
];
const analysis = analyzeErrorRate(events, 60000);
console.log(analysis.total); // 5
console.log(analysis.errors); // 2
console.log(analysis.errorRate); // 40
const anomalies = detectAnomalies([5, 4, 6, 50, 5]);
console.log(anomalies.filter((a) => a.isAnomaly).length); // 1
console.log(anomalies[3].isAnomaly); // true
Math.max(...events.map(...))finds the newest timestamp. The window is counted back from there.newest - e.timestamp <= windowMsdrops events older than the window. With events at 1,000, 2,000 and 90,000 ms and a 5,000 ms window, only the 90,000 event is in: total 1.Math.round(... * 100)turns 0.4 into 40, a whole number.rate > 2 * averageuses>, so a rate of exactly twice the average is not an anomaly yet. For[1, 1, 10], the average is 4, and only index 2 goes over 8.
Mitigate: rollback, feature flag, canary
- Rollback: deploy the previous version again. This is the fastest when the last deploy is clearly the cause, but everything in that release is pulled with it.
- Feature flag: the new feature sits behind a switch you can turn off from a dashboard, with no deploy. For example
if (flags.isEnabled('new-checkout')) { ... }: once the flag is off, every user goes back to the old checkout. - Canary deployment: the new version goes to a small share of users first, say 5%. Suppose v2.3.1 makes 45 out of every 100 requests fail. With a 5% canary, only 5 requests a minute (out of 100 a minute in total) reach v2.3.1, and 2 of them fail. The overall error rate only goes from 5% to 7%, while the canary group on its own is at 40%. That's why the canary group's error rate is watched on its own. You just pull that 5%, or turn the feature flag off, with no redeploy.
Investigate without disturbing users
- More detailed logging around the suspicious part, with a request ID (correlation ID): the frontend sends an
X-Request-IDheader, and every service writes the same ID in its logs. So one search finds the whole journey of one request. - Distributed tracing (OpenTelemetry, Jaeger, Zipkin) records one request from the frontend to the API to the database, with how long each step took. A bug that only appears in production is usually found through these logs and traces.
- Session replay (for example Session Replay in Sentry, LogRocket, or PostHog) records what a user does on the page, then plays it back like a video: clicks, typing, and the errors that appear. It suits bugs you cannot reproduce yourself. Check its masking settings (what it hides), so that input such as passwords and personal data is not recorded.
- Avoid setting the minimum log level to debug everywhere at once: the volume floods the system, costs money, and can end up recording personal data.
📌 Postmortem
Once the service is back to normal, write a short postmortem. It holds the impact (for example 150 users unable to check out for 30 minutes), a minute-by-minute timeline, the root cause, and action items (tasks to fix things, such as testing migrations in staging and faster alerts). It focuses on the system and the process, not on who is to blame.
⚠️ Wrong moves during an incident
- Investigating first, mitigating later. While you read code, users keep failing to pay. Stabilise first.
- A window from
Date.now(). In the exercise, the window is measured from the newest timestamp in the data. Measured from the current clock, old data is all thrown away. For an alert that watches production right now, it is the opposite: measure fromDate.now(). - Forgetting to multiply by 100 or round.
errorRatemust be40, not0.4or40.0001. - The average rises too. If the incident lasts a while, for example
[5, 4, 6, 50, 50, 50], the average is 27.5 and nothing goes over 55. Compare with the average from before the incident as well.
TL;DR: In an incident (trouble in the app real users are using), first detect, triage (decide how bad it is) and mitigate (roll back to the previous version, switch the feature off with its feature flag, or pull the canary). Only then investigate, fix and write a postmortem (a record so it doesn't happen again). Don't attach a debugger in production: a breakpoint freezes the process (the program running on the server) and every user's request. Error rate = the number of failed requests divided by the total requests in a time window, times 100 and rounded (5 requests, 2 errors, so 40). In the exercise, the window is measured back from the newest request. Anomaly = a rate above twice the average ([5, 4, 6, 50, 5]: average 14, only 50 goes over 28). A bug that only appears in production is investigated with detailed logging, request IDs (the same ID in every log of one request) and distributed tracing (a record of one request's journey across many services). A canary (a new version sent to a small share of users first) means a new bug only hits a small share of users.
⚡ No debugger in production
Guess first: why is a breakpoint on a production server dangerous?
A breakpoint freezes the process (the program running on the server). In Node.js, every request is served by the same single thread (line of work). So once the process stops, every user's request hangs with it.
Meaning: In production, what you rely on is logs, error monitoring, metrics such as the error rate (the percentage of requests that fail), and tracing (a record of one request's journey).
⚡ Stop the damage first
Meaning: The order: detect, triage (decide how bad it is), mitigate (stop the damage), then investigate, fix and write a postmortem (a record so it doesn't happen again). If the last deploy pushed the error rate to 50%, roll back (deploy the previous version again) or turn off the feature flag (a switch for the feature) first. Only after that, look for the broken line calmly.
⚡ Error rate and anomalies
Write:
function detectAnomalies(rates) {
const average = rates.reduce((a, b) => a + b, 0) / rates.length;
return rates.map((rate, index) => ({ index, rate, isAnomaly: rate > 2 * average }));
}
Guess first: in this code, average is the average of all the rates. The per-minute error rates are [5, 4, 6, 50, 5]. Which one is an anomaly?
Only 50. The average is 70 / 5 = 14, and the limit is twice that: 28.
Meaning: The error rate is the number of errors divided by the total requests in a time window (for example the last 60 seconds), times 100. An anomaly here means a rate above twice the average.
⚡ A canary: a new bug only hits a few users
Meaning: A canary deployment sends the new version to a small share of users first, say 5%. If it turns out to be broken, pull the canary or turn off the feature flag, with no redeploy.