Explore
WEBSTER / SOFTWARE ENGINEERING← Senior DeveloperEducational reference · continually evolving

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.

← Complete index

The big idea

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.

Why it matters

Random edits create new bugs and obscure the original failure.

In practice

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.

Why it matters

The browser can fail before a request is sent or after a successful API response is received.

In practice

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.

Why it matters

The server often knows why a 500 occurred even when the browser sees only a generic error.

In practice

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.

Why it matters

Adding app replicas will not fix a missing index or a table lock.

In practice

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.

Why it matters

A delay in one service can look like a database or frontend bug from another vantage point.

In practice

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.

Why it matters

Searchable fields beat gigabytes of unstructured console strings.

In practice

Log {event:'checkout_failed',order_id:'o42',request_id:'r17',code:'PAYMENT_TIMEOUT'} without a full payment payload.

Node.js
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.

Why it matters

Debug logging in an infinite loop can consume the volume hosting your application's actual data.

In practice

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 JSON
// 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.

Why it matters

Mocks cannot prove that a database persists or a link remains clickable after a CSS redesign.

In practice

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.

Why it matters

A clear rollback is often safer than diagnosing every aspect of an outage while customers are blocked.

In practice

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

10 / APPLIED RESEARCH

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.

Why it matters

Random changes erase evidence, obscure the first meaningful failure, and delay the point where a testable root-cause hypothesis emerges.

In practice

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
Try it

Write a short incident timeline with one confirming observation.

Check your result

The timeline identifies first known bad release and relevant request.

11 / APPLIED RESEARCH

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.

Why it matters

Runaway debug output can consume the same volume as customer data.

In practice

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
Try it

Estimate log bytes/day at 100 events/sec of 250 bytes.

Check your result

Define retention and verify log storage stays inside budget.

12 / APPLIED RESEARCH

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.

Why it matters

A single error count lacks denominator and cannot distinguish overload from isolated user failures.

In practice

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
Try it

Choose 5 metrics and one alert tied to actual user impact.

Check your result

An injected outage appears in the dashboard before a user complaint.

13 / APPLIED RESEARCH

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.

Why it matters

Different database bottlenecks demand different fixes: indexes address scans, shorter transactions address locks, and batching addresses N+1 calls.

In practice

A calendar request issues 200 album queries; batch records and inspect EXPLAIN before adding replicas.

Hands-on exercise · reveal the verification check
Try it

Compare plans for a filtered and unfiltered event query.

Check your result

Observed plan and latency support the proposed index or rewrite.

14 / APPLIED RESEARCH

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.

Why it matters

A visually fast page can freeze interaction after loading hundreds of widgets.

In practice

Throttle to mobile CPU, filter 5000 cards and measure whether synchronous work blocks painting; virtualise if needed.

Hands-on exercise · reveal the verification check
Try it

Record a trace for one slow filter interaction.

Check your result

Fix reduces the actual long task and real interaction delay.

15 / APPLIED RESEARCH

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.

Why it matters

Testing only a mock response can preserve a broken live system.

In practice

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
Try it

Intentionally remove one module file from a disposable build.

Check your result

The new regression check fails with a clear missing asset.

Investigation discipline

16 / FIELD NOTE

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.

Why it matters

Random fixes are expensive because they can mask the symptom without resolving the cause.

In practice

Reproduce a date-off-by-one booking bug across server and browser time zones before altering formatting.

Shell · illustrative
# Make the defect repeatable before changing code
npm test -- --runInBand
# Then isolate one failing assertion.
Hands-on exercise · reveal the verification check
Try it

Write an exact reproduction for one bug and two hypotheses.

Check your result

A regression test fails before the fix and passes after.

17 / FIELD NOTE

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.

Why it matters

A successful server log may coexist with a broken browser because rendering and caching form another layer.

In practice

Diagnose a guide that returns HTML 200 but lesson module scripts 404; verify the static fallback still displays content.

Shell
# Inspect the response and headers
curl -i 'https://example.org/api/events'
Hands-on exercise · reveal the verification check
Try it

Block a module request and capture console and network evidence.

Check your result

Static chapter links remain usable and the failure is visible.

18 / FIELD NOTE

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.

Why it matters

Excessive logs can fill a disk or expose customer information while still failing to explain an incident.

In practice

Correlate a booking API error with the job that sent its confirmation using a stable request or correlation identifier.

JSON log
{"severity":"error","service":"booking-api","request_id":"abc123","message":"validation_failed"}
Hands-on exercise · reveal the verification check
Try it

Generate a high-frequency error burst under test.

Check your result

Log volume remains bounded and useful fields remain searchable.

19 / FIELD NOTE

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.

Why it matters

An intermittent slow request is hard to diagnose from isolated timestamps.

In practice

Trace browser submit through booking API, transaction, outbox and reminder worker without including personal details in span attributes.

Trace checklist
# Propagate a trace ID through API -> worker -> database
# Inspect individual span duration and error tags.
Hands-on exercise · reveal the verification check
Try it

Inject 400, 503 and timeout responses into a request flow.

Check your result

The trace identifies the failing dependency and retry count.

20 / FIELD NOTE

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.

Why it matters

A UI button working against a fake API is not proof bookings persist correctly.

In practice

Keep a fast price calculation unit test, real database constraint test and browser booking test in CI.

JavaScript test
// Critical invariant should be tested at a real DB boundary.
expect(res.status).toBe(409);
Hands-on exercise · reveal the verification check
Try it

Map five failure modes to the cheapest reliable test type.

Check your result

At least one test crosses each critical integration boundary.

21 / FIELD NOTE

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.

Why it matters

Restoring service is more urgent than finding someone to blame.

In practice

A calendar deployment loses source links; roll back the frontend artifact and preserve evidence of which release introduced the regression.

Incident template
# Incident record
# Impact: bookings failed for 3 minutes
# Mitigation: reverted release
# Follow-up: add HTTP route smoke test
Hands-on exercise · reveal the verification check
Try it

Write a five-step incident runbook for a broken booking API.

Check your result

It includes communications, mitigation, verification and follow-up.