Chapter 12 / 15 · Webster International
Debugging, Testing, Logs & Diagnostics
A repeatable diagnosis method for browsers, APIs, databases, memory, networking, performance, tests and production logs that do not fill disks.
Debugging is scientific reasoning: observe the symptom, reproduce it, narrow the boundary, form a hypothesis, test the hypothesis and capture evidence.
01 / FIELD NOTE
The systematic debugging loop
Write down actual versus expected behaviour. Establish reproducible steps, inputs, environment and first known failure. Change one variable at a time and use a small test to prove the root cause.
Random edits create new bugs and obscure the original failure.
A form fails only for large payloads: inspect request status, server validation, reverse proxy body limits and database constraints in that order.
02 / FIELD NOTE
Browser debugging: DOM, Network and performance
Use browser DevTools Elements to inspect layout/semantics, Console for runtime errors, Network for HTTP/timing/cookies, Sources for breakpoints, Performance for long tasks and Accessibility inspection for roles and names.
The browser can fail before a request is sent or after a successful API response is received.
If an Events Calendar link does nothing, check hit target, event handler, console exception, destination URL and whether an overlay blocks clicks.
03 / FIELD NOTE
Backend breakpoints and stack traces
Use an IDE/debugger to pause code, inspect locals and stack frames, and step over/into async calls. Preserve request IDs and structured error types; use exceptions for exceptional cases rather than hiding failures.
The server often knows why a 500 occurred even when the browser sees only a generic error.
A POST returns 409. Trace the transaction's constraint violation and return a conflict the UI can recover from.
04 / FIELD NOTE
SQL query plans and slow requests
Measure where time is spent, check query plans and index use, inspect lock waits, and compare actual row counts with expectations. Slow endpoints can be caused by N+1 queries rather than a slow language.
Adding app replicas will not fix a missing index or a table lock.
An artist grid executes one query per artist for albums; batch the lookup or JOIN appropriately; confirm improvement with measurements.
05 / FIELD NOTE
Network failures and distributed tracing
Use request IDs across browser/API/worker, record upstream call durations, and add tracing spans across services. Distinguish DNS errors, TLS failures, timeouts, connection resets, 429s and upstream 5xx responses.
A delay in one service can look like a database or frontend bug from another vantage point.
Trace checkout request → inventory span → payment provider span, then inspect exactly where retry or timeout happened.
06 / FIELD NOTE
Structured logs and sensible levels
Emit machine-readable entries with timestamp, severity, service, environment, action, request ID and safe identifiers. Use DEBUG for local detail, INFO for milestones, WARN for recoverable anomalies and ERROR for failed operations.
Searchable fields beat gigabytes of unstructured console strings.
Log {event:'checkout_failed',order_id:'o42',request_id:'r17',code:'PAYMENT_TIMEOUT'} without a full payment payload.
const log = (level, event, extra={}) => {
process.stdout.write(JSON.stringify({
ts: new Date().toISOString(), level, event, ...extra
})+'\n');
};
log('warn', 'payment_timeout', {request_id:'r17'});07 / FIELD NOTE
Prevent logs from filling the hard drive
Prefer stdout/stderr streams to a managed log collector with configured retention. For local files or containers, rotate by size/time, cap file counts, compress as appropriate, set quotas, filter repetitive noise, and monitor disk remaining. Audit logs need separate durability/retention choices.
Debug logging in an infinite loop can consume the volume hosting your application's actual data.
Docker json-file logging with max-size 10m and max-file 3 limits per-container JSON log files to roughly 30 MB before overhead; or use Docker local driver with rotation.
// Docker daemon.json — local example, not an app file
{
"log-driver": "json-file",
"log-opts": {"max-size":"10m","max-file":"3"}
}
// Restart daemon / recreate containers as documented.08 / FIELD NOTE
Unit, integration, E2E and accessibility tests
Test pure rules quickly, then exercise real infrastructure at boundaries and user journeys in a browser. Cover success, invalid input, missing data, concurrent edits, network failure, permissions, keyboard navigation and mobile widths.
Mocks cannot prove that a database persists or a link remains clickable after a CSS redesign.
Run a payment idempotency test against a real test database and a full keyboard-only checkout flow against a staging build.
09 / FIELD NOTE
Production incidents: triage and learning
Prioritise user impact, contain the failure, preserve evidence, revert when safe, compare healthy/unhealthy deploys and document a blameless root-cause analysis with specific prevention tasks.
A clear rollback is often safer than diagnosing every aspect of an outage while customers are blocked.
If an event importer exhausts disk, stop writes, preserve volume, rotate logs safely, restore health and add bounded retention and disk alerts.
RESEARCH EXPANSION · APPLIED ENGINEERING
A first-15-minutes diagnostic checklist
Start by confirming scope, first failure time, expected versus actual, affected environment and last change. Reproduce safely, inspect one correlated request path and preserve logs before altering the system.
Random changes erase evidence, obscure the first meaningful failure, and delay the point where a testable root-cause hypothesis emerges.
The guide loads as HTML 200 but lessons are blank: inspect the Network tab; identify fifteen data JS 404s before rewriting components.
Hands-on exercise · reveal the verification check
Write a short incident timeline with one confirming observation.
The timeline identifies first known bad release and relevant request.
Log volume budgeting and disk rotation
Use structured stdout logs and bounded retention in the host. Docker local driver rotates and compresses files; documented defaults are 20 MB × 5 files, about 100 MB of retained content per container before overhead. Alert on disk usage and collector failures.
Runaway debug output can consume the same volume as customer data.
Switch debug noise off in normal runtime, cap size/count and monitor the persistent disk separately from log partitions.
Hands-on exercise · reveal the verification check
Estimate log bytes/day at 100 events/sec of 250 bytes.
Define retention and verify log storage stays inside budget.
Instrument RED and USE signals
For services measure request Rate, Errors and Duration (RED); for resources monitor Utilisation, Saturation and Errors (USE). Tie metrics, traces and structured logs with consistent service/version/request identifiers.
A single error count lacks denominator and cannot distinguish overload from isolated user failures.
Chart p95 API latency, 5xx ratio and job backlog together; tag the release SHA but avoid unbounded user-ID metric labels.
Hands-on exercise · reveal the verification check
Choose 5 metrics and one alert tied to actual user impact.
An injected outage appears in the dashboard before a user complaint.
Database query and lock triage
Distinguish missing index, large scans, blocked transactions, deadlocks and N+1 patterns. Sample representative query plans; log query fingerprints and latency rather than entire user data.
Different database bottlenecks demand different fixes: indexes address scans, shorter transactions address locks, and batching addresses N+1 calls.
A calendar request issues 200 album queries; batch records and inspect EXPLAIN before adding replicas.
Hands-on exercise · reveal the verification check
Compare plans for a filtered and unfiltered event query.
Observed plan and latency support the proposed index or rewrite.
Browser performance profiling and long tasks
Use browser Performance panel to inspect main-thread tasks, layout/reflow, expensive handlers and JavaScript execution; pair with field measurements of INP and LCP. Reproduce with realistic device and network conditions.
A visually fast page can freeze interaction after loading hundreds of widgets.
Throttle to mobile CPU, filter 5000 cards and measure whether synchronous work blocks painting; virtualise if needed.
Hands-on exercise · reveal the verification check
Record a trace for one slow filter interaction.
Fix reduces the actual long task and real interaction delay.
Regression tests that distinguish layers
Write a failing test at the layer where evidence points: a static asset route test for 404s, an integration test for database writes, a unit test for a rule, and an end-to-end test for real navigation.
Testing only a mock response can preserve a broken live system.
Guide check asserts 15 source modules present in Docker output, every chapter has anchored static text, and staging HTTP returns 200.
Hands-on exercise · reveal the verification check
Intentionally remove one module file from a disposable build.
The new regression check fails with a clear missing asset.
Investigation discipline
Scientific debugging: reproducer, hypothesis, instrumentation, falsification
Reduce a failure to a repeatable case with known input, version, state and observed behavior. Make one hypothesis at a time, collect evidence from logs or tracing, change one variable and preserve a regression test. Record disproved guesses so teammates do not repeat them.
Random fixes are expensive because they can mask the symptom without resolving the cause.
Reproduce a date-off-by-one booking bug across server and browser time zones before altering formatting.
# Make the defect repeatable before changing code
npm test -- --runInBand
# Then isolate one failing assertion.Hands-on exercise · reveal the verification check
Write an exact reproduction for one bug and two hypotheses.
A regression test fails before the fix and passes after.
Browser Network and Performance panels for complex UI failures
Inspect request status, redirects, response payloads, caching headers, preflight requests and slow tasks. Use DOM breakpoints, CPU profiles and network throttling to identify whether a card is missing because of CSS, state, request errors or asset delivery.
A successful server log may coexist with a broken browser because rendering and caching form another layer.
Diagnose a guide that returns HTML 200 but lesson module scripts 404; verify the static fallback still displays content.
# Inspect the response and headers
curl -i 'https://example.org/api/events'Hands-on exercise · reveal the verification check
Block a module request and capture console and network evidence.
Static chapter links remain usable and the failure is visible.
Structured logging, bounded retention and privacy-safe diagnostics
Emit machine-readable logs with timestamp, severity, service, request ID and sanitized context. Set maximum file or transport retention, sample repetitive low-value messages and alert on storage growth. Never record access tokens, raw passwords or sensitive user records.
Excessive logs can fill a disk or expose customer information while still failing to explain an incident.
Correlate a booking API error with the job that sent its confirmation using a stable request or correlation identifier.
{"severity":"error","service":"booking-api","request_id":"abc123","message":"validation_failed"}Hands-on exercise · reveal the verification check
Generate a high-frequency error burst under test.
Log volume remains bounded and useful fields remain searchable.
Distributed traces, metrics and correlation IDs
Metrics show the size and frequency of a problem, logs capture specific events and traces link work across API, database and worker boundaries. Propagate correlation IDs and context safely across queues, and measure p95 latency and error rates by meaningful operation.
An intermittent slow request is hard to diagnose from isolated timestamps.
Trace browser submit through booking API, transaction, outbox and reminder worker without including personal details in span attributes.
# Propagate a trace ID through API -> worker -> database
# Inspect individual span duration and error tags.Hands-on exercise · reveal the verification check
Inject 400, 503 and timeout responses into a request flow.
The trace identifies the failing dependency and retry count.
Test doubles versus real integration and contract testing
Unit tests isolate deterministic rules, integration tests exercise real persistence and transport, contract tests check compatibility and end-to-end tests verify user journeys. Mocks are useful for rare failures but can create false confidence if they merely restate implementation assumptions.
A UI button working against a fake API is not proof bookings persist correctly.
Keep a fast price calculation unit test, real database constraint test and browser booking test in CI.
// Critical invariant should be tested at a real DB boundary.
expect(res.status).toBe(409);Hands-on exercise · reveal the verification check
Map five failure modes to the cheapest reliable test type.
At least one test crosses each critical integration boundary.
Incident triage, rollback and blameless postmortems
During an incident, prioritize user impact and containment: identify affected operations, examine recent changes, apply a safe rollback or feature disablement and preserve an evidence timeline. Afterwards document contributing factors, detection gaps and actionable prevention checks.
Restoring service is more urgent than finding someone to blame.
A calendar deployment loses source links; roll back the frontend artifact and preserve evidence of which release introduced the regression.
# Incident record
# Impact: bookings failed for 3 minutes
# Mitigation: reverted release
# Follow-up: add HTTP route smoke testHands-on exercise · reveal the verification check
Write a five-step incident runbook for a broken booking API.
It includes communications, mitigation, verification and follow-up.