CI/CD Pipeline Best Practices (Part 4): Make CI Fast Without Making It Weak
Build a CI pipeline that gives fast, trustworthy feedback. Learn test layering, flaky-test control, caching, parallelism, matrices, selective execution and pipeline performance tuning.

Slow CI has a predictable effect on engineering teams: people stop treating it as part of the development loop.
A developer pushes a change, sees that the pipeline will take 28 minutes, and moves on to something else. The failure arrives after the context has gone cold. They rerun the whole pipeline because the error looks flaky. Another developer queues behind them. Eventually the team starts merging with half an eye on the checks because everybody has learned that “red” does not always mean “broken”.
The pipeline still exists, but the feedback loop has failed.
The opposite extreme is just as dangerous. Teams under pressure sometimes make CI “fast” by moving meaningful tests out of the pull-request path, skipping integration coverage, disabling flaky suites without fixing them, or turning security checks into warnings that nobody reads.
The real target is not the shortest possible pipeline.
It is the shortest pipeline that gives trustworthy evidence about the change being made.
This fourth part of the series focuses on that balance: how to make CI materially faster without hollowing it out.
Start by measuring where the time actually goes
Before optimising, break the pipeline into stages and collect timings.
A typical application might look like this:
Checkout 12s
Dependency restore 2m 40s
Compile / type-check 1m 10s
Unit tests 2m 05s
Integration tests 7m 30s
E2E browser tests 11m 20s
Security scans 3m 10s
Packaging 1m 15s
----------------------------
Total ~29m
Now you have something useful to discuss.
Without timings, teams often optimise the most visible step rather than the expensive one. Saving eight seconds from checkout while browser tests consume eleven minutes is not optimisation; it is tidying.
Track at least:
- queue time before a runner starts;
- job duration;
- individual stage duration where practical;
- cache hit rate;
- test-suite duration;
- flaky retry frequency;
- failure frequency by stage.
The pipeline should be observable enough that you can tell whether a slowdown comes from your code, your test architecture, the runner fleet or an external dependency.
1. Put the cheapest, highest-signal checks first
A pipeline should fail as early as it reasonably can.
If formatting can reject the change in 15 seconds, do not wait for a 12-minute browser suite first.
A sensible ordering often looks like:
1. formatting / linting
2. compile / type-check
3. focused unit tests
4. dependency / policy checks
5. integration tests
6. deployed smoke tests
7. end-to-end / expensive non-functional tests
This does not mean every pipeline needs exactly those stages. It means cheap evidence should normally precede expensive evidence.
DORA’s guidance on test automation emphasises fast, reliable automated feedback throughout the delivery lifecycle. That is the goal: developers should find out quickly when a change is invalid, while more expensive checks run where their additional confidence is worth the cost.
2. Separate the PR loop from the release loop
A common mistake is forcing every pull request through every possible production-grade test.
Some checks belong on every change. Others may be more appropriate after merge, on a release candidate, on a schedule, or against a deployed staging environment.
Think in two loops.
The pull-request loop
Optimise for rapid developer feedback.
Typical checks:
- formatting;
- linting;
- compile/type-check;
- unit tests;
- focused component/integration tests;
- dependency review;
- fast static/security analysis.
The release loop
Optimise for broader release confidence.
Typical checks:
- full integration suite;
- browser/E2E coverage;
- migration checks;
- deployed smoke tests;
- performance checks;
- dynamic security tests where appropriate;
- release-specific policy validation.
The important thing is not “move slow tests out of PRs”. It is to decide which failures need to be discovered before merge and which can safely be discovered before release.
If an E2E test catches regressions developers introduce several times per day, it probably belongs in a fast pre-merge path or needs to be redesigned so that it can.
3. Build a test portfolio, not a test pyramid poster
The classic test pyramid is useful because it encourages many fast tests and fewer expensive end-to-end tests.
But real systems require more judgement than “unit good, E2E bad”.
Google’s more recent testing guidance uses the SMURF mnemonic to think about trade-offs such as speed, maintainability, utilisation, reliability and fidelity rather than relying on the pyramid alone.
A practical portfolio asks what each test is buying you.
Unit tests
Usually fast, isolated and precise.
Good for:
- business rules;
- pure functions;
- parsing/validation;
- edge cases;
- regression coverage around logic.
Weak at proving:
- service wiring;
- real database behaviour;
- network contracts;
- browser behaviour.
Integration/component tests
Slower but often extremely valuable.
Good for:
- database queries;
- API contracts;
- message handling;
- dependency configuration;
- authentication/authorisation boundaries.
End-to-end tests
High fidelity but expensive and more failure-prone.
Best reserved for critical journeys such as:
- sign-in;
- checkout/payment;
- account creation;
- a core workflow that crosses multiple services.
If your 25-minute suite contains 400 E2E tests that individually recreate an entire browser session to prove tiny validation rules, you probably have a test-architecture problem, not a runner-speed problem.
4. A flaky test is a pipeline defect
A test that passes and fails against the same code is not merely irritating. It damages the meaning of the pipeline.
Google’s testing guidance describes flaky tests as a major challenge because they make failures ambiguous. Once developers stop believing that red means broken, they start rerunning jobs rather than investigating them.
That is the moment CI becomes a slot machine.
Track flakiness explicitly.
A useful policy might be:
New flaky test detected
│
├── quarantine temporarily if blocking the team
├── create owner / defect
├── collect failure evidence
└── repair or remove test promptly
Do not let quarantine become a graveyard containing 140 tests that have been “temporarily” disabled for 18 months.
Common sources of flakiness include:
- dependence on wall-clock timing;
- shared mutable test data;
- test-order dependence;
- eventual consistency;
- asynchronous work not properly awaited;
- network calls to unstable external services;
- random data without deterministic seeds;
- insufficient environment resources;
- browser animation/timing assumptions;
- stale state on persistent runners.
The fix should target the source of nondeterminism, not merely add retry: 3 everywhere.
5. Retries can diagnose; they should not hide failure
Retries are sometimes useful.
If an integration test depends on an eventually consistent service, retrying a bounded assertion may accurately represent the system’s contract.
If a browser test randomly fails 8% of the time because the selector races the UI, rerunning the entire test until it turns green simply hides the defect.
Distinguish between:
expected transient behaviour
and
unexplained nondeterminism.
Retries around the former can be sensible. Retries around the latter should produce telemetry and a repair task rather than silently converting red to green.
6. Cache downloads, not trust
Dependency caching can remove minutes from clean CI jobs.
GitHub Actions, for example, supports dependency caches keyed using values such as the operating system and a hash of a lockfile:
- name: Cache npm downloads
uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ runner.os }}-
When the lockfile changes, the cache key changes.
That is a good fit because the cache speeds up dependency restoration while the lockfile remains the source of truth.
Avoid caching things merely because they are expensive to rebuild.
Do not turn a cache into an undocumented release artifact store.
Good cache candidates often include:
- package-manager download caches;
- compiler caches;
- safe intermediate build data.
Risky candidates include:
- credentials;
- opaque production artifacts;
- files whose integrity is not independently established;
- mutable state shared between trust domains.
GitHub explicitly warns against putting sensitive information in cache paths because cache contents may be accessible in workflow contexts you did not expect.
7. Measure cache effectiveness
A cache that exists is not necessarily useful.
Common problems include:
- the key changes on every run;
- the cache is enormous and takes longer to transfer than recomputation;
- restore keys are so broad that stale content causes odd behaviour;
- multiple jobs independently restore the same huge cache;
- the cache stores generated output that should instead be an artifact.
Track hit rate and transfer time.
If restoring a 4 GB cache takes four minutes and recomputing the files takes three, delete the cache.
CI optimisation should be empirical.
8. Parallelise independent work
This pipeline:
lint -> unit tests -> security scan -> integration tests
may contain artificial serialisation.
If linting, unit tests and dependency analysis do not depend on one another, run them concurrently:
┌─ lint
checkout ├─ unit tests
├─ dependency scan
└─ static analysis
│
▼
integration tests
The critical path is what determines elapsed time.
Parallelisation does not reduce total compute usage — it may increase it — but it can reduce developer waiting time substantially.
The right balance depends on runner cost and workflow urgency.
9. Split tests where the split is stable
A large test suite can often be sharded across workers.
For example:
strategy:
matrix:
shard: [1, 2, 3, 4]
Each shard receives a subset of tests.
A naive split by filename may become imbalanced:
Shard 1: 2 minutes
Shard 2: 3 minutes
Shard 3: 12 minutes
Shard 4: 2 minutes
You still wait 12 minutes.
Better systems use historical duration to balance shards more evenly.
Do not shard a five-minute suite into 20 runners just because you can. Runner startup overhead and cost can outweigh the benefit.
10. Use matrix testing for supported combinations, not every combination
Matrix jobs are ideal when software genuinely supports multiple configurations.
A library may need:
strategy:
matrix:
node: [20, 22, 24]
os: [ubuntu-latest, windows-latest]
That creates six combinations.
Add three database versions and two CPU architectures and you suddenly have 36.
Ask which combinations provide meaningful compatibility evidence.
A common approach is:
- test the primary supported environment on every PR;
- run the broader compatibility matrix on main or nightly;
- test important boundary versions explicitly.
The goal is confidence in supported configurations, not maximising the number of green boxes.
11. Selective execution can be powerful — and dangerous
In a monorepo, changing documentation for one frontend package should not necessarily rebuild 60 unrelated services.
Path-based or dependency-aware execution can dramatically improve CI performance.
For example:
Changed files
│
▼
Dependency graph
│
├── service-a affected -> test/build A
├── shared-lib affected -> test A/B/C
└── docs only -> skip application builds
The danger is a false negative: the change affects more of the system than your dependency graph understands.
Selective CI is only as trustworthy as its impact analysis.
If in doubt, run a broader validation after merge even if the PR path is focused.
12. Don’t restore dependencies five times if you can structure the workflow better
A workflow with five jobs often performs checkout and package restore five times.
Sometimes that is fine. Independent clean jobs improve isolation.
Sometimes the duplication dominates runtime and cost.
Look at actual timings before combining jobs. You may find it useful to:
- use package-manager caching;
- build once and upload an intermediate artifact;
- separate genuinely independent jobs;
- avoid rebuilding identical output in several stages.
Do not sacrifice job isolation just to save 30 seconds, but do not ignore five repeated four-minute restores either.
CI proves the release candidate; audit the public result too
Application tests cannot see every public-site regression. SiteTidy gives you an independent post-deployment check for performance, SEO, headers, TLS and technical issues.
13. Keep external services out of the fast path where possible
A unit test that calls a live third-party API is neither a good unit test nor a reliable CI dependency.
External calls introduce:
- network latency;
- rate limits;
- outages;
- credentials;
- nondeterministic data;
- vendor test-environment instability.
Use contract tests, fakes, recorded responses or local emulators where they accurately represent the behaviour you need.
Then run a smaller number of real integration checks against external systems where that evidence is genuinely valuable.
The question is not “mock everything”. It is “which layer needs the real dependency?”
14. Create test data deliberately
Shared test databases are a classic source of both slowness and flakiness.
One test creates a user. Another assumes the user does not exist. A cleanup job runs late. Parallel execution makes the race worse.
Prefer isolated, disposable test data where practical:
- unique test identifiers;
- transaction rollback;
- per-test/per-suite schemas;
- ephemeral databases/containers;
- deterministic fixtures.
Integration tests become easier to parallelise when they do not fight over global state.
15. Move expensive environment setup closer to code
If integration tests require somebody to maintain a shared staging database, message broker and cache manually, the pipeline inherits all of that environment drift.
Containers and ephemeral test environments can help by making dependencies repeatable:
CI job
│
├── start database container
├── start message broker
├── apply schema
├── run integration tests
└── destroy environment
This is not always appropriate — large distributed systems may be too expensive to recreate for every job — but disposable infrastructure can dramatically improve determinism for common dependencies.
16. Fail fast inside test jobs too
A 15-minute test job that discovers a compilation error at minute 14 is badly ordered.
Likewise, if one critical prerequisite fails, decide whether the remaining expensive checks still add value.
GitHub Actions matrix strategies, for example, support fail-fast behaviour. Whether to enable it depends on what you want from the run.
For a PR compatibility matrix:
- failing fast saves resources;
- continuing may reveal that only one environment is broken.
Choose deliberately.
17. Watch queue time separately from execution time
A ten-minute pipeline can still create a 40-minute feedback loop if it waits 30 minutes for a runner.
Queue time tells you about capacity rather than workflow design.
If queues are consistently high:
- increase runner capacity;
- autoscale self-hosted runners if appropriate;
- prioritise critical workflows;
- cancel obsolete PR runs;
- reduce unnecessary scheduled jobs at peak times;
- inspect concurrency limits.
Do not spend a week shaving 90 seconds from the workflow if the real problem is a 20-minute queue.
18. Cancel obsolete CI aggressively, but not state-changing deployments
If a developer pushes commit A, then B, then C to the same pull request, A and B may no longer matter.
GitHub Actions concurrency can cancel older verification runs:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
That prevents runners proving commits nobody intends to merge.
But do not copy the same policy blindly to deployment jobs. Cancelling an infrastructure or database deployment halfway through can be dangerous.
As covered in Part 2:
obsolete verification can usually be cancelled; state-changing release work should usually be serialised.
19. Keep the build output authoritative
Performance tuning sometimes creates an accidental anti-pattern: jobs rebuild the application independently because sharing an artifact seems inconvenient.
Do not trade away release identity for speed.
The CI build should produce an authoritative artifact, and downstream release processes should use that exact artifact.
DORA’s continuous integration guidance explicitly recommends numbered, repeatable builds whose output is authoritative for downstream processes.
Optimise the build, cache its inputs, parallelise its tests — but keep the relationship between source revision and release artifact unambiguous.
20. Track pipeline health like a product
A CI system has users: your developers.
Useful pipeline-health metrics include:
- median PR feedback time;
- p95 feedback time;
- queue time;
- cache hit rate;
- flaky failure rate;
- reruns per workflow;
- failure rate by stage;
- time spent waiting for CI per developer;
- infrastructure cost per successful build.
Do not obsess over a single number.
A pipeline that is six minutes faster but produces twice as many false failures is worse.
A pipeline that costs 20% more but returns trustworthy feedback ten minutes sooner may be a very good investment.
The best optimisation question
Ask: “What is the earliest point at which this failure could have been detected reliably?” Then move that signal toward the front of the pipeline. That usually improves developer experience more than indiscriminate caching or larger runners.
Browse SiteTidy's developer toolsA practical optimisation order
If your CI pipeline is painfully slow today, resist rewriting the whole thing first.
Work through the bottlenecks in order:
- Measure queue and stage duration.
- Move cheap, high-signal failures earlier.
- Fix or quarantine flaky tests with ownership.
- Cache dependency downloads using stable keys tied to lockfiles.
- Parallelise truly independent checks.
- Shard long, stable test suites if runner cost is justified.
- Remove unnecessary external network dependencies from the fast path.
- Improve test isolation so integration suites can run concurrently.
- Use selective execution where dependency analysis is trustworthy.
- Cancel obsolete PR runs.
- Keep the release artifact authoritative while optimising around it.
- Measure again.
The last step matters. If the pipeline went from 28 minutes to 14, find out what still dominates before adding more complexity.
Final thought
A fast pipeline is not one that does less useful work.
It is one that organises evidence intelligently.
Cheap failures happen early. Independent work runs concurrently. Expensive tests are used where they buy meaningful confidence. Caches accelerate reproducible inputs instead of hiding state. Flaky tests are treated as defects. Obsolete work is cancelled. Release artifacts remain trustworthy.
When CI works this way, developers stop waiting for the pipeline and start using it as intended: as a near-continuous source of reliable feedback about whether the change in front of them is safe to keep moving.
