Error Handling and Defensive Programming Questions
Making code robust against bad input and failure: exceptions versus error returns, input validation, guard clauses, graceful degradation, and designing for the unhappy path. Covers where to handle versus propagate errors and how to fail safely without hiding bugs. A recurring probe of production maturity.
Explain optimistic locking versus pessimistic locking for concurrent updates in a backend service (for example, updating a user profile, or safely incrementing an account balance under retries to avoid double-spends). For each approach, describe how conflicts are detected, typical implementation (version columns/CAS versus row locks), and which scenarios favor one over the other. Mention idempotency tokens and compensating transactions as complementary techniques under high contention.
A batch/ETL job exits with status zero but silently produces missing or empty output (or, in a case you're handed: a nightly job's logs show it stopped processing halfway through but still reported success). Investigate the root cause and propose detection heuristics that would have caught it earlier: checksums, output-row-count versus a watermark, heartbeats, manifest files, and an idempotent re-run strategy. Explain the immediate mitigation and the long-term observability and test changes to prevent recurrence.
Design an SLO-based alerting strategy that minimizes pager/alert fatigue: what metrics feed the SLO, symptom alerts versus cause alerts, using an error budget to gate alerting, minimum sample sizes, and grouping/sampling strategies for a noisy downstream integration that would otherwise drown out real signals. Sketch a PromQL-like expression for 'error ratio exceeds 1% over 5 minutes with at least 1000 requests'.
Write a helper function format_error_log(exc, context) that returns a structured log record (a dict) suitable for ingestion into a logging pipeline: timestamp, level, service, correlation_id, error_type, message, and a short stack trace, using only the standard library. Describe how you would limit sensitive data and ensure the record stays machine-parsable.
Design a layered test strategy specifically for ERROR PATHS: unit tests that simulate a dependency failure, integration tests using test doubles, contract tests for downstream behavior, and failure-injection/chaos tests for real dependencies (for example testing retry/fallback logic against a flaky external API, or fallback behavior when a cache tier fails). Give concrete test cases for each layer and describe how you'd automate this in CI (gating versus non-gating) without introducing flakiness.
Unlock Full Question Bank
Get access to all Error Handling and Defensive Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.