惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
S
Schneier on Security
博客园 - 聂微东
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
美团技术团队
Last Week in AI
Last Week in AI
罗磊的独立博客
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
V
V2EX
博客园_首页
博客园 - 司徒正美
IT之家
IT之家
S
SegmentFault 最新的问题
宝玉的分享
宝玉的分享
雷峰网
雷峰网
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
J
Java Code Geeks
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
P
Privacy International News Feed
C
CERT Recently Published Vulnerability Notes
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
AWS News Blog
AWS News Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threat Research - Cisco Blogs
Jina AI
Jina AI
V
Vulnerabilities – Threatpost
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
H
Hacker News: Front Page
腾讯CDC
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
爱范儿
爱范儿
T
Tor Project blog
博客园 - 【当耐特】
T
The Exploit Database - CXSecurity.com
K
Kaspersky official blog
Latest news
Latest news
博客园 - 叶小钗
Know Your Adversary
Know Your Adversary
有赞技术团队
有赞技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
CI/CD Pipeline Optimization: From 20-Minute to 3-Minute Builds
Yash Pritwan · 2026-04-28 · via DEV Community

Originally published on TechSaaS Cloud


Originally published on TechSaaS Cloud


CI/CD Pipeline Optimization: From 20-Minute to 3-Minute Builds

Real numbers from a startup that cut build times by 85% — every step with code.

The Problem: 20 Minutes of Watching Spinners

Our CI pipeline was 20 minutes. On a busy day with 30+ PRs, that meant 10 hours of cumulative CI time. Developers context-switched while waiting. Reviews stalled. Deployments backed up.

We're a 12-person team running 84 Docker containers on self-hosted infrastructure. Our stack: Python + TypeScript + Go microservices, GitHub Actions CI, Docker-based deploys, PostgreSQL + Redis.

Every optimization below is free. No paid CI tools. No enterprise cache services. Just configuration changes and architectural decisions.

The 6 Changes That Got Us to 3 Minutes

1. Docker Layer Caching (Saved: 6 minutes)

Before: Every build pulled fresh base images and reinstalled all dependencies.

# BAD: invalidates cache on every code change
FROM python:3.12-slim
COPY . /app
RUN pip install -r requirements.txt

Enter fullscreen mode Exit fullscreen mode

After: Separate dependency installation from code changes.

# GOOD: dependencies cached until requirements.txt changes
FROM python:3.12-slim
COPY requirements.txt /app/
RUN pip install -r requirements.txt
COPY . /app

Enter fullscreen mode Exit fullscreen mode

In GitHub Actions, enable BuildKit cache:

- name: Build
  uses: docker/build-push-action@v5
  with:
    context: .
    cache-from: type=gha
    cache-to: type=gha,mode=max
    push: true

Enter fullscreen mode Exit fullscreen mode

Impact: First build unchanged. Subsequent builds skip the 6-minute dependency installation step entirely. Cache hit rate: ~92%.

2. Parallel Test Sharding (Saved: 5 minutes)

Before: 847 tests running sequentially: 8 minutes.

After: Split across 4 parallel runners using pytest-split:

strategy:
  matrix:
    shard: [1, 2, 3, 4]
steps:
  - name: Run tests
    run: |
      pytest --splits 4 --group ${{ matrix.shard }} \
        --splitting-algorithm least_duration

Enter fullscreen mode Exit fullscreen mode

The least_duration algorithm uses historical test timing data to balance shards evenly. We store timing data in .test_durations committed to the repo.

Impact: 8 minutes → 2.5 minutes (longest shard). The parallelism costs 4x the runner minutes, but wall-clock time dropped 68%.

For Indian startups on GitHub's free tier (2,000 minutes/month), this is a trade-off. We self-host our runners on the same server that runs production — more on that in step 6.

3. Dependency Pre-Build with Docker Compose (Saved: 3 minutes)

Before: Every microservice built its own node_modules or venv from scratch.

After: A shared base image with pre-installed dependencies, rebuilt only when lockfiles change.

# docker-compose.ci.yml
services:
  deps-python:
    build:
      context: .
      dockerfile: Dockerfile.deps-python
    image: registry.local/deps-python:latest

  service-api:
    build:
      context: ./services/api
      args:
        BASE_IMAGE: registry.local/deps-python:latest

Enter fullscreen mode Exit fullscreen mode

# Dockerfile.deps-python
FROM python:3.12-slim
COPY requirements/*.txt /deps/
RUN pip install -r /deps/base.txt -r /deps/test.txt

Enter fullscreen mode Exit fullscreen mode

A separate nightly CI job rebuilds the deps image. Feature branch builds pull it from our local registry.

Impact: Eliminated redundant dependency installation across 6 Python services. Saved ~3 minutes per build.

4. Smart Test Selection (Saved: 2 minutes)

Not every commit needs every test. We built a simple mapper:

# .github/scripts/test_selector.py
import subprocess, json, pathlib

changed = subprocess.check_output(
    ["git", "diff", "--name-only", "origin/main...HEAD"]
).decode().strip().split("\n")

test_map = {
    "services/api/": "tests/api/",
    "services/auth/": "tests/auth/",
    "services/billing/": "tests/billing/",
    "shared/": "tests/",  # shared code = run everything
}

tests_to_run = set()
for file in changed:
    for src, test_dir in test_map.items():
        if file.startswith(src):
            tests_to_run.add(test_dir)

# If nothing matched, run everything (safety net)
if not tests_to_run:
    tests_to_run.add("tests/")

print(" ".join(tests_to_run))

Enter fullscreen mode Exit fullscreen mode

- name: Select tests
  id: tests
  run: echo "dirs=$(python .github/scripts/test_selector.py)" >> $GITHUB_OUTPUT

- name: Run tests
  run: pytest ${{ steps.tests.outputs.dirs }}

Enter fullscreen mode Exit fullscreen mode

Impact: Most PRs touch 1-2 services. Running only relevant tests: 2.5 minutes → 45 seconds. Full suite still runs on merge to main.

5. Artifact Caching for Lint and Type Checks (Saved: 2 minutes)

ESLint, mypy, and tsc have incremental modes. Use them:

- name: Cache mypy
  uses: actions/cache@v4
  with:
    path: .mypy_cache
    key: mypy-${{ hashFiles('**/*.py') }}
    restore-keys: mypy-

- name: Type check
  run: mypy --incremental src/

Enter fullscreen mode Exit fullscreen mode

For ESLint:

- name: Cache ESLint
  uses: actions/cache@v4
  with:
    path: .eslintcache
    key: eslint-${{ hashFiles('**/*.ts', '**/*.tsx') }}

- name: Lint
  run: eslint --cache --cache-location .eslintcache src/

Enter fullscreen mode Exit fullscreen mode

Impact: Incremental lint/type-check: 2 minutes → 15 seconds on most PRs.

6. Self-Hosted Runners (Saved: 2 minutes of queue time)

GitHub-hosted runners have 30-90 second startup times plus queue time during peak hours. We run our CI on the same bare metal server as our staging environment.

runs-on: self-hosted

# In our runner setup (systemd service)
# Runner installed at /opt/actions-runner
# Runs as dedicated ci-runner user with Docker socket access

Enter fullscreen mode Exit fullscreen mode

Setup (one-time, 15 minutes):

  1. Download GitHub Actions runner binary
  2. Create systemd service
  3. Give the runner user Docker socket access
  4. Configure labels for routing

Self-hosted runners start instantly — no cloud VM boot, no image pull. Queue time went from 30-90 seconds to 0.

For teams in India or Southeast Asia, this also eliminates the latency penalty of GitHub's US-based runners pulling from your APAC Docker registry.

Impact: 2 minutes of queue/startup time eliminated. Free. Forever.

The Result

Step Before After
Queue + startup 1.5 min 0 min
Dependency install 6 min 0 min (cached)
Lint + type check 2 min 0.25 min
Build 3 min 0.5 min
Tests 8 min 2.5 min
Total 20.5 min 3.25 min

85% reduction. Zero additional cost.

Common Mistakes That Negate These Gains

We've seen teams implement all six optimizations and still have slow pipelines. Here's why.

Mistake 1: Flaky tests that force re-runs. If 5% of your test suite is flaky, you'll re-run CI on average once every 3-4 PRs. That re-run costs the full pipeline time. We quarantine flaky tests into a separate non-blocking job: they run, their results are logged, but they don't block the PR. A weekly "flaky test cleanup" ticket keeps the quarantine from growing forever.

Mistake 2: Not pinning dependency versions. If your requirements.txt has unpinned ranges (requests>=2.28), the dependency resolution step runs every time — even with caching — because pip needs to check if a newer version satisfies the constraint. Pin exact versions (requests==2.31.0) and use Dependabot or Renovate for updates. This alone can save 30-60 seconds per build.

Mistake 3: Running security scans synchronously. SAST/DAST tools (Snyk, Trivy, Bandit) are important but slow. Run them in a parallel job that doesn't block the main build. Your pipeline reports results, but developers can merge without waiting for a 3-minute vulnerability scan. Critical findings trigger a separate alert. This principle extends to secret scanning too — we cover the full secret management pipeline in our dedicated guide.

Mistake 4: Over-building in CI. Some teams build Docker images for every microservice on every PR, even when the service code didn't change. Use the same path-based filtering from Step 4 to skip builds for unchanged services. Our docker-compose.ci.yml has a --profile flag per service — CI only activates profiles for services with code changes.

Mistake 5: Ignoring the feedback loop. After optimizing, most teams stop measuring. We track CI build times in Prometheus and alert if the p95 build time exceeds 5 minutes. Performance degrades slowly — a new dependency here, an extra test there — and without monitoring, you're back to 15 minutes within 6 months.

Security Considerations in Fast Pipelines

Fast pipelines are only valuable if they're secure. Skipping security checks for speed is a false economy.

Our approach: security scans run in parallel, never blocking the main build path, but their results are mandatory before deploy. The build completes in 3 minutes, the security scan completes in 5, and the deploy job waits for both.

jobs:
  build-and-test:  # 3 minutes
    runs-on: self-hosted
    steps: [...]

  security-scan:  # 5 minutes, runs in parallel
    runs-on: self-hosted
    steps:
      - uses: aquasecurity/trivy-action@master
      - run: bandit -r src/ -f json -o bandit-report.json

  deploy:  # waits for BOTH
    needs: [build-and-test, security-scan]
    if: github.ref == 'refs/heads/main'
    steps: [...]

Enter fullscreen mode Exit fullscreen mode

This means the critical path is still 5 minutes (the slower security scan), but the developer feedback loop (did my tests pass?) is 3 minutes. Developers get fast feedback; deploys get security guarantees.

For teams handling sensitive credentials in their pipelines, the secret management best practices we published today covers how to avoid leaking secrets through CI logs — a common issue with fast, parallelized builds.

What We'd Add Next

  • Bazel or Nx for true incremental builds across a monorepo. We're not there yet — our repo isn't big enough to justify the complexity.
  • Test impact analysis using coverage data to be even more surgical about test selection.
  • Merge queues (GitHub's native feature) to batch CI runs and reduce total runner time.
  • Remote build caching (Turborepo, Gradle remote cache) for teams with larger monorepos — we've seen this shave another 40% off already-optimized builds.

The ROI Math

The ROI on CI optimization is absurd. A 12-person team saving 17 minutes per build across 30 daily builds reclaims 8.5 engineering hours per day. That's a full-time engineer's worth of productivity — recovered by spending 2 days on pipeline optimization.

But the real ROI isn't time saved — it's behavior change. When CI takes 3 minutes, developers wait for results before context-switching. When it takes 20 minutes, they start another task and the PR review sits for hours. Fast CI changes how your entire team works. The same build vs buy analysis applies here: investing 2 days in pipeline optimization is always better than buying an expensive CI SaaS tool.

Frequently Asked Questions

Q: Does this work for monorepos?

Yes, with adjustments. Steps 4 (smart test selection) and the Docker profile trick become even more valuable in monorepos because the ratio of "code changed" to "total code" is smaller. For monorepos over 50 services, consider Bazel, Nx, or Turborepo for incremental build tracking — they maintain a dependency graph that makes test selection automatic rather than manual.

Q: What about Windows or macOS builds?

Self-hosted runners (Step 6) work on all platforms, but the Docker caching strategy (Steps 1 and 3) is Linux-specific. For macOS CI (common in mobile development), focus on dependency caching (Cocoapods, Carthage) and parallel test sharding (XCTest supports this natively). The ROI is even higher for macOS builds because GitHub-hosted macOS runners are 10x more expensive than Linux runners.

Q: We use GitLab CI / Jenkins / CircleCI — does this still apply?

Every optimization except the GitHub-specific YAML applies to any CI system. Docker layer caching works everywhere Docker runs. Parallel test sharding works with any test framework. Dependency pre-builds work with any registry. Self-hosted runners exist for GitLab (gitlab-runner), Jenkins (agents), and CircleCI (self-hosted runner). The concepts transfer; only the config syntax changes.

Related Reading


We help teams audit and optimize their CI/CD pipelines. If your builds take longer than 5 minutes, there's almost certainly low-hanging fruit.

Get a free pipeline audit →

Subscribe to our newsletter for weekly deep-dives into developer productivity and infrastructure optimization.