Prompt
How do I reduce flaky tests in my CI pipeline?
Latest observation
Flaky tests usually come from a mix of timing, shared state, environment differences, and test-order dependence. The fastest way to reduce them is to combine better isolation, better diagnostics, and targeted stabilization.
1. Find the source of flakiness
Start by categorizing failures:
- Intermittent timing issues: race conditions, async waits, slow external services
- State leakage: tests sharing files, DB rows, caches, env vars, singletons
- Environment drift: different OS, browser, timezone, locale, CPU load
- Order dependence: tests only fail when run after others
- Network/external dependency issues: APIs, queues, third-party services
Track:
- test name
- branch/commit
- runner
- retry count
- elapsed time
- logs/screenshots/artifacts
A simple “flaky test dashboard” helps a lot.
2. Make tests deterministic
Remove randomness
- Seed random generators
- Don’t use current time directly; inject a clock or freeze time
- Avoid relying on unordered collections unless you sort them
Control async behavior
- Prefer explicit synchronization over sleeps
- Wait for specific conditions, not arbitrary delays
- Mock or fake timers where possible
Bad:
await wait(5000)
Better:
await waitFor(() => expect(button).toBeEnabled())
3. Isolate test state
Reset between tests
- Clear DB tables or use transactions/fixtures
- Reset caches, queues, local storage, temp files
- Reinitialize singletons and global config
Use unique test data
- Unique names/IDs per test run
- Avoid shared user accounts or shared records
Run tests in isolated environments
- Use ephemeral DBs or containers per job
- Separate test namespaces for parallel runs
4. Reduce external dependencies
- Mock external APIs in unit/integration tests
- Use contract tests for service boundaries
- For end-to-end tests, stand up controlled test doubles when possible
- If you must hit real services, make those tests a smaller, quarantined suite
5. Improve CI execution strategy
Retry carefully
Retries can hide real bugs, so use them as a diagnostic tool, not a permanent fix.
Good use:
- one retry to confirm flake vs real regression
- automatically tag failing tests as flaky for triage
Avoid:
- unlimited retries
- marking unstable tests as passing without visibility
Separate suites
- Fast unit tests on every push
- Integration tests on merge or nightly
- End-to-end tests in a dedicated pipeline stage
Limit concurrency where needed
If tests share resources, parallelism can create flakiness.
- Run resource-heavy tests serially
- Use per-worker isolated resources
6. Make failures easier to debug
Add artifacts on failure:
- logs
- screenshots
- DOM dumps
- network traces
- server traces
- database snapshots
- test seed and environment info
Also useful:
- log test start/end times
- include worker ID
- capture retry reason
7. Quarantine and fix, don’t ignore
For persistently flaky tests:
- quarantine them into a separate job
- keep them visible in reporting
- assign an owner and SLA to fix
Don’t let flaky tests accumulate; they erode trust in CI.
8. Common causes by test type
Unit tests
- global/static state
- time/randomness
- improper mocks
- parallel test interference
Integration tests
- DB contention
- eventually consistent systems
- external service latency
- migration/setup ordering
E2E/UI tests
- brittle selectors
- animations/transitions
- waiting on the wrong signal
- cross-browser differences
- headless/headful discrepancies
9. A practical plan
If you want the highest ROI, do this first:
- Add retries + flake logging to identify top offenders
- Stabilize time/async tests by removing sleeps
- Reset shared state between tests
- Isolate external dependencies
- Quarantine the worst flaky tests
- Track flake rate over time
10. Rule of thumb
If a test is flaky:
- first assume it is revealing nondeterminism
- not that CI is “bad”
The goal is to make the test:
- deterministic
- isolated
- diagnosable
If you want, I can also give you a checklist for flaky tests, or tailor advice to pytest, Jest, Cypress, Playwright, or GitHub Actions.