Flaky Test Management and Test Reliability Questions
Detecting, isolating, and eliminating non-deterministic tests. Covers root-causing flakiness, quarantine and remediation systems, distinguishing product bugs from test bugs, and maintaining suite health over time. Emphasizes keeping automated suites trustworthy so failures mean something.
Describe a concrete instrumentation plan to collect runtime telemetry for flaky test diagnosis. Specify which signals you would collect (e.g., CPU, memory, thread counts, network latency, container restarts), sampling rates, correlation keys (run-id, test-id, commit), and storage/retention guidelines suitable for millions of runs.
Sample Answer
Direct answer: Sample continuously but cheaply (low-overhead system metrics at a modest fixed interval) rather than only at failure time, since a resource-contention pattern often needs to be seen building up BEFORE the failure to be diagnostic, and correlate everything through a shared (run_id, test_id, commit) key so any signal can be joined against any other without a separate reconciliation step.
Structured elaboration
Signals to collect: CPU utilization and load average (the primary resource-contention signal); memory usage and swap activity (disk-pressure-adjacent, and a common cause of unpredictable slowdowns); thread/process count (a proxy for how much concurrent work a runner is actually juggling, relevant for parallel-execution flakiness investigation); network latency to key dependencies (a lightweight, periodic probe, not a full packet capture, for the continuous-sampling case); and container/runner restart events (a strong, direct signal of infra instability that's easy to miss if you're only looking at test-level pass/fail data).
Sampling rates: continuous, lightweight system metrics (CPU/memory/thread-count) at a modest fixed interval (every few seconds) throughout a test run, cheap enough to not meaningfully perturb what's being measured; network latency probes at a similarly light interval; container-restart events captured as discrete EVENTS (not sampled, since a restart is a specific, immediate happening, not a continuous quantity) the moment they occur.
Correlation keys: run_id (ties all telemetry to one specific CI execution), test_id (which specific test was executing during a given sampled window, letting resource metrics be attributed to a specific test rather than just "somewhere during this build"), and commit (the code version, for correlating a resource-usage CHANGE with a specific code change, tying into the bisection sub-area's workflow). Every sampled metric row carries all three, so any later query can join resource data against test outcomes or against commit history without a separate reconciliation step.
Storage/retention guidelines at millions-of-runs scale: raw, full-resolution samples retained for a SHORT window (days), matching the tiered-retention pattern covered throughout this topic's telemetry discussions, since the diagnostic value of a specific sample drops sharply once the specific incident it might explain is well past; pre-aggregated summaries (per-run min/max/mean for each metric, computed at ingestion time rather than recomputed on every later query) retained much longer, supporting trend analysis (is a specific runner's typical resource profile drifting over months) without needing to keep full-resolution history indefinitely.
Worked example: investigating an intermittent timeout, the continuous CPU-utilization samples (not just a single failure-time snapshot) show utilization climbing steadily for roughly 90 seconds BEFORE the timeout occurred, then dropping back to baseline immediately after, a pattern consistent with a resource-contention BUILDUP (other concurrent work on the same runner gradually consuming capacity) rather than a sudden spike; a failure-time-only snapshot would have shown high CPU AT the moment of failure but missed the diagnostically important RAMP pattern leading up to it, which is what actually distinguishes "gradual contention" from "sudden, unrelated spike" as the underlying cause.
Trade-offs & pitfalls: continuous sampling at too fine a granularity (say, every 100ms) both costs more storage at millions-of-runs scale AND risks the measurement overhead itself perturbing the exact resource behavior you're trying to observe, particularly for CPU-sensitive investigations; choosing an interval that's frequent enough to see a meaningful trend (the ramp pattern in the worked example) without being so frequent it becomes its own confound is a real, deliberate calibration, not a default to set once, and should be validated against whether the chosen interval would actually have caught the specific patterns you care about diagnosing, like the worked example's 90-second ramp.
Design an automated quarantine system that integrates with CI and your issue tracker. Requirements: detect tests above a flakiness threshold, tag them as 'quarantined' in the test registry, open an issue with diagnostic artifacts, notify owner(s), and automatically re-evaluate removal after a configurable period or on improvement. Describe system components, data flows, APIs, failure modes, and how to avoid noisy or oscillating quarantines.
Sample Answer
Direct answer: The system needs four cooperating pieces: a scorer that continuously computes a flakiness metric per test from CI history, a state machine that moves a test between healthy, quarantined, and fixed states with an audit trail, an integration layer that talks to CI (to exclude a quarantined test from gating) and the issue tracker (to open and update a diagnostic ticket), and a re-evaluation loop that automatically proposes removing a test from quarantine, never leaving that decision to silently expire.
Structured elaboration
System components and data flow
flowchart LR
A[CI test-result stream] --> B[Flakiness scorer]
B -->|score > threshold| C[Quarantine state machine]
C -->|enter quarantine| D[Test registry: tag quarantined]
C -->|enter quarantine| E[Issue tracker: open ticket + attach artifacts]
D --> F[CI gate: excludes quarantined tests from blocking]
C -->|re-eval trigger: time elapsed or new runs| G[Re-evaluation job]
G -->|score improved| H[Propose un-quarantine, owner confirms]
G -->|no improvement, SLA breached| I[Escalate]
H --> C
- Detection: the scorer reads recent CI results (a rolling window of, say, the last 20 to 50 runs) and computes a flakiness threshold breach, the same computation the topic's detection sub-area covers; this system consumes that score rather than redefining it.
- Tagging: on breach, the registry marks the test
quarantinedwith a timestamp, the triggering score, and a reference to the CI run(s) that caused the breach, so the state is queryable and auditable, not a hidden flag. - Issue creation: an issue is opened automatically with diagnostic artifacts attached (recent failure logs, the flakiness score history, and links to the offending CI runs) and assigned to the test's registered owner, or to a default triage queue if no owner is on file.
- Owner notification: a notification (chat, email, or both depending on team norms) goes to the owner with a direct link to the ticket, not just a dashboard update, since a silent dashboard entry is easy to miss.
- CI gate integration: quarantined tests still RUN (so their signal is not lost entirely) but do not block merges; their results are recorded and rolled up into the flakiness dashboard so a genuinely fixed test's improving trend is visible before the formal re-evaluation.
- Automatic re-evaluation: on a configurable schedule (for example, weekly) or after N new runs, the re-evaluation job recomputes the score. If it has improved below a (slightly stricter, to avoid flapping) un-quarantine threshold, it proposes removal from quarantine, which an owner confirms rather than the system silently re-enabling gating. If the SLA (for example, 30 days in quarantine) is breached with no improvement, it escalates rather than extending indefinitely.
- APIs: a minimal contract is
POST /quarantine {test_id, score, evidence},GET /quarantine/{test_id}for status, andPOST /quarantine/{test_id}/reevaluate, plus a webhook the CI system calls after each run so the scorer stays current without polling.
Trade-offs & pitfalls: two failure modes need explicit design attention. First, noisy or oscillating quarantine: a test that hovers right at the threshold can flap in and out of quarantine every re-evaluation cycle, which is worse than either staying quarantined or staying gated, since it destabilizes the gate unpredictably. The fix is hysteresis: use a HIGHER score to enter quarantine than to exit it (for example, enter at a 15% failure rate, require dropping below 5% to exit), so a test sitting near the boundary does not flap. Second, metrics integrity: because quarantined tests keep running but stop blocking merges, it is tempting to let their reruns silently pad an "all green" dashboard; the design must keep quarantined-test results visible and clearly labeled so the team's headline pass rate is not artificially inflated by hiding the exact signal the system exists to surface.
Worked example: suppose a test has run 40 times in the last week with 6 failures (15% failure rate), crossing a 10%-enter threshold. It is auto-quarantined, a ticket is opened with the 6 failing run links attached, and the owner (from the test's registered CODEOWNERS-style metadata) is notified. Two weeks later, after the owner's fix, the test has run 25 more times with 0 failures; the re-evaluation job recomputes a rolling failure rate of roughly 0% over the most recent window, well under a 5%-exit threshold, and proposes un-quarantine, which the owner confirms in one click from the ticket.
Design a flaky-test dashboard and tracking system for a company running ~3,000 automated tests across distributed CI runners with ~1,000 builds/day. Describe: the event ingestion model, minimal data schema for test result events, flakiness metrics (per-test flakiness rate, pass-after-retry rate), alerting thresholds, UI views, and how to deduplicate and attribute failures to tests vs infrastructure.
Sample Answer
Direct answer: The system is an event-driven pipeline: every test result becomes an event ingested into an append-only store, a scheduled or streaming job rolls those events up into per-test metrics, and the dashboard reads from the rolled-up metrics, not from raw events, so it stays fast at ~1,000 builds/day scale. Two different UI views on the same underlying metrics serve two different audiences, rather than building two separate systems.
Structured elaboration
- Event ingestion model: each test's outcome, on every run, is published as an event (not batched per-build) so partial-build failures and retries are captured individually. A lightweight ingestion API or message queue absorbs bursts (many tests finishing near-simultaneously at the end of a build) without blocking the CI runner that's reporting them.
- Minimal data schema:
{test_id, build_id, commit_sha, run_id, timestamp, status (pass/fail/error), duration_ms, runner_id, retry_attempt, error_signature}.retry_attemptis what makes pass-after-retry computable later;runner_idis what makes infra-attribution possible;error_signature(a normalized hash of the failure message/stack) is what lets deduplication and infra-vs-test attribution work without re-parsing raw logs on every query. - Flakiness metrics: per-test flakiness rate is failures divided by total runs over a rolling window (for example, the last 20 or 50 runs, or the last 14 days, whichever gives enough samples); pass-after-retry rate is (runs that failed on attempt 1 but passed on a later attempt) divided by (runs that failed on attempt 1), which is the specific signal that flags a test being "rescued" by retries rather than genuinely fixed.
- Deduplication and infra-vs-test attribution: group failures by
error_signaturewithin a time window; if a SIGNATURE spikes across MANY DIFFERENT tests at once, correlated to a specificrunner_idor a narrow time window, that is strong evidence of an infrastructure issue (a bad runner image, a network blip) rather than many independent test bugs, and the dashboard should surface it as one infra incident rather than dozens of separate test alerts. - Alerting thresholds: a test crossing an agreed flakiness-rate threshold (for example, 10% over the last 20 runs, requiring a minimum sample size like 10 runs before alerting to avoid noisy small-sample alerts) triggers a notification to its owner; a SUITE-wide or infra-level alert fires separately when the deduplicated error-signature analysis above detects a cross-test infra spike, since that needs a different kind of response (fix the runner, not 20 individual tests).
- Two audience-specific UI views on the same rolled-up data: an engineering-manager view shows aggregate trends (suite-wide flakiness rate over time, top contributing teams or services, quarantine backlog size) suitable for a weekly health check; a test-owner view shows per-test detail (this specific test's recent run history, its error signatures, its current flakiness score, and direct links to failing CI runs) suitable for someone actively triaging. Building both from the SAME underlying metrics store, rather than as separate pipelines, is what keeps them consistent with each other.
Worked example: at 1,000 builds/day with roughly 3,000 tests each, that's on the order of 3 million test-result events per day. A daily (or hourly, for fresher dashboards) rollup job aggregates raw events into per-test daily summary rows, which is what the dashboard actually queries; the raw event table stays available for drill-down (a test owner clicking into "why did this test fail on March 3rd" reads the raw events for that day) but is never queried directly for the aggregate views, which keeps dashboard load times independent of the raw event volume.
Trade-offs & pitfalls: a common design mistake is having the dashboard query raw events directly for every view, which works at small scale and then falls over as build volume grows; separating ingestion, rollup, and query concerns from the start avoids a costly rewrite later. A second pitfall: choosing too small a minimum-sample-size floor for alerting produces noisy small-sample alerts (a test that failed once in its first 3 runs looks like 33% flaky but that's not statistically meaningful yet); require a minimum run count before a test's flakiness rate is trusted for alerting.
Discuss the tradeoffs between 'time-traveling' test doubles (record/replay mocks or deterministic replays of historical interactions) and deterministic fixtures (controlled test data and state) for reproducing intermittent failures in stateful systems. Propose a combined approach that helps reproduce failures reliably without making tests brittle, and describe tooling or processes to support it.
Sample Answer
Direct answer: Time-traveling test doubles (record real interactions once, then replay them deterministically) give high fidelity to real system behavior but can go stale as the real dependency evolves; deterministic fixtures (hand-constructed, controlled test data and state) stay stable indefinitely but require someone to keep them semantically accurate to reality; the strongest approach combines both, recorded interactions as the DEFAULT source of realistic behavior, periodically re-validated against the real system, with hand-built fixtures reserved for cases recording can't easily cover.
Structured elaboration
- Time-traveling test doubles (record/replay, e.g. VCR-style cassettes): capture a REAL interaction with a dependency once, then replay the recorded response deterministically on every subsequent test run. Pro: high fidelity, the exact shape of a real response, including quirks a hand-written fixture might miss. Con: the recording can silently drift out of sync with the real dependency's CURRENT behavior (a schema change, a new required field) and nothing forces a re-recording, so tests can pass against a stale, no-longer-accurate cassette while production quietly breaks.
- Deterministic fixtures (hand-constructed data and state): explicitly written, controlled test data. Pro: fully understood and stable by construction, no external drift possible. Con: someone has to keep the fixture semantically accurate to the real dependency's actual contract by hand, which is easy to let slip, especially for a dependency that changes often.
- A third comparator worth naming explicitly, since it sits between these two: a local sandbox/stub server that implements a lightweight, hand-maintained approximation of the real dependency's API, useful when you need MORE realistic request/response cycling than a static fixture but don't want the staleness risk of blind record/replay; it shares deterministic fixtures' maintenance burden but with somewhat higher fidelity for interaction PATTERNS (multiple calls, stateful sequences) than a single static response.
- Combined approach: use record/replay as the default source of realistic response DATA (capturing the real shape of responses), but pair it with a scheduled, automated re-validation job that periodically replays a SAMPLE of recordings against the real dependency (in a safe, sandboxed environment) and flags any recording whose real-world counterpart has drifted, converting record/replay's silent-staleness risk into a visible, actionable signal rather than eliminating the technique's fidelity advantage. Reserve hand-built deterministic fixtures for cases where recording is impractical (a dependency with side effects too risky to trigger repeatedly for recording, or a deliberately-constructed edge case the real system rarely produces naturally).
- Microservices-specific alternative: consumer-driven contract testing is a complementary, not competing, technique: instead of the consumer test recording or hand-constructing the PROVIDER's responses, the consumer publishes an explicit CONTRACT of what it expects, and the provider's own test suite verifies it satisfies that contract independently. This shifts the staleness-detection burden from the consumer side (re-validating a recording) to the provider side (breaking the provider's own build if it violates a published contract), which scales better across many consumer teams than each one separately maintaining its own recordings or fixtures against the same provider.
- Tooling/process to support the combined approach: a scheduled CI job that periodically re-runs recorded cassettes against the real dependency (in a non-production, low-risk environment) and opens an alert when a recording no longer matches; a lightweight contract-testing framework (e.g., a Pact-style broker) for internal microservice boundaries, so provider teams get direct, fast feedback when they'd break a consumer's expectations, rather than relying on the consumer's own drifted recordings to eventually notice.
Worked example: a payment-service integration test originally used a hand-built fixture representing a successful charge response. After the real payment provider added a new required field to their response six months prior, the fixture silently no longer reflected reality, and a real integration bug related to that new field went undetected in tests for weeks. Migrating to record/replay (re-recording a real successful charge periodically) would have caught the schema change automatically the next time the cassette was refreshed; adding the scheduled re-validation job on top closes the remaining gap, catching drift even between scheduled refreshes rather than only when someone remembers to re-record.
Trade-offs & pitfalls: consumer-driven contract testing requires organizational buy-in from BOTH sides (the provider team has to actually run consumer contract verification in their own CI), which is a coordination cost that doesn't apply to record/replay or fixtures, which a single team can adopt unilaterally; this makes contract testing the right long-term investment for a stable microservices boundary with many consumers, but not always the fastest thing to stand up for a one-off integration with an external, uncooperative third party, where record/replay with periodic re-validation is usually the more pragmatic starting point.
Explain key behavioral differences between mobile emulators/simulators and real devices that cause automated mobile tests to pass on emulators but fail on physical devices. List at least six differences (e.g., sensors, GPU, manufacturer OS customizations, WebView versions, network variability, hardware performance) and say how to mitigate them in a test strategy.
Sample Answer
Direct answer: Emulators approximate hardware in software and are internally consistent by construction, so tests pass reliably against that consistent approximation; real devices carry genuine hardware variability, real sensors, and manufacturer-specific OS customizations the emulator never models, so passing on an emulator establishes far less confidence than it appears to.
Structured elaboration
Six concrete differences, each with a mitigation:
- Sensors: emulators typically provide synthetic, perfectly-behaved sensor data (GPS, accelerometer) on demand; real devices have genuine sensor noise, latency, and permission-prompt timing that can affect app behavior. Mitigation: include a real-device test tier specifically for sensor-dependent flows, don't rely on emulator sensor simulation as sufficient coverage.
- GPU: emulators often use software rendering or a different GPU abstraction than the real device's actual GPU driver; rendering-timing-sensitive UI tests can pass reliably on emulator's consistent (if slower or different) rendering path and then flake on real hardware's actual GPU timing characteristics. Mitigation: for GPU-timing-sensitive assertions, prefer real-device testing or add generous, explicit tolerance for rendering completion rather than assuming emulator timing transfers.
- Manufacturer OS customizations: many Android manufacturers ship customized OS layers (different power-management/background-process-killing behavior, custom permission dialogs) that a stock emulator image doesn't replicate. Mitigation: maintain a real-device test matrix covering the manufacturer/OS-version combinations your actual user base concentrates in, informed by real usage analytics, not an arbitrary sample.
- WebView versions: an emulator's bundled WebView version can lag or differ from what's actually deployed on real devices in the field (WebView updates independently of the OS on many Android versions). Mitigation: explicitly pin and verify the WebView version in both emulator and real-device test environments, and treat a version mismatch as a known coverage gap rather than an unknown one.
- Network variability: emulators typically run on a stable, fast host-machine network path; real devices experience genuine cellular/WiFi variability (latency spikes, brief disconnects) that can expose real timeout and retry-handling bugs. Mitigation: use network-condition simulation tools (throttling, packet loss injection) in BOTH emulator and real-device testing rather than assuming the emulator's clean network is representative.
- Hardware performance: emulators often run on a powerful host machine and can be FASTER (or, under host contention, unpredictably slower) than the actual range of real devices in the field, especially lower-end devices. Mitigation: include a deliberately lower-spec real device (or a resource-throttled configuration) in the test matrix specifically to catch performance-dependent flakiness that a fast host-machine emulator would never surface.
How to mitigate them as a test strategy overall, not just per-difference: use emulators for the BULK of automated testing (fast, cheap, parallelizable, deterministic) as the first line of defense, and reserve a smaller, targeted real-device test tier (run less frequently, perhaps nightly rather than per-PR) specifically for the categories above where emulator behavior is known to diverge from reality. This tiered approach captures most of automation's speed and cost benefits from emulators while still catching the real-device-specific failure classes that would otherwise ship undetected.
Worked example: an app's push-notification handling passes reliably on emulator (which delivers a synthetic notification event instantly and consistently) but fails intermittently on real mid-range Android devices from a specific manufacturer, whose custom OS layer aggressively kills background processes to save battery, occasionally killing the app before the notification handler runs. This is invisible to emulator testing entirely (no such power-management behavior exists there) and was only caught by the manufacturer-specific real-device test tier, confirming why category 3 (manufacturer customizations) needs deliberate real-device coverage informed by actual field device distribution, not assumed away.
Trade-offs & pitfalls: a real-device test matrix is expensive to maintain and slower to run than emulator tests, so the temptation is to skip it or run it rarely; the mitigation is choosing WHICH real devices to include deliberately (informed by actual field usage data on device/manufacturer distribution) rather than either an arbitrary small sample or attempting comprehensive device coverage that isn't cost-effective.
Unlock Full Question Bank
Get access to all Flaky Test Management and Test Reliability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.