Trunk-Based Development: Short-Lived Branches and Continuous Integration

When I joined a team that had fully embraced trunk-based development after years of wrestling with long-lived feature branches, the difference in daily friction was immediate. No more week-long merge marathons before a release, no more "it worked on my branch" surprises in staging. Instead, we were pushing small, reviewed changes to main several times a day, with automated checks telling us within minutes whether we had broken something. Trunk-based development is not just a branching strategy; it is a forcing function for the engineering discipline that makes continuous integration actually work. In this article, I will break down how it operates in practice for teams running real production systems, where keeping the pipeline fast and the main branch releasable is non-negotiable.

Why Trunk-Based Development Eliminates Integration Debt Before It Accumulates

In my experience, the most expensive bugs are not logic errors but integration errors that hide for weeks inside isolated branches. With classic GitFlow-style workflows, developers branch off develop or main, work for days or weeks, and then attempt to reconcile divergent histories. The longer a branch lives, the more the codebase moves underneath it. By the time you open a pull request, you are not just merging code, you are merging assumptions about APIs, database schemas, and configuration that may have already changed.

Trunk-based development inverts this model. There is a single source of truth, typically called main or trunk, and every developer integrates to it at least once per day. Branches, if they exist at all, live for hours, not weeks. The goal is to make integration a non-event because it happens so frequently. Google and Meta have documented this at scale, but I have seen the same benefits on teams of eight to ten engineers. Our average merge conflict rate dropped by over 80% after we moved from two-week feature branches to branches that lived less than a day.

The Cost of Deferred Integration

Deferred integration creates a snowball effect. A change that would take five minutes to resolve on day one can take half a day on day ten, especially if it touches shared libraries or infrastructure code. In one project, we had a Terraform module for VPC configuration living on a feature branch for three weeks. By the time the author tried to merge, the CIDR allocation strategy had changed in main, and the entire networking stack needed to be reworked. That rework was not caused by bad coding; it was caused by isolation. For infrastructure code, I always recommend referencing the Terraform Documentation on module composition and state management, as it reinforces why small, incremental changes to infrastructure are safer than large batch updates.

Trunk-based development does not mean everyone pushes directly to main without review. It means the path from idea to trunk is short, observable, and automated. Every commit to trunk triggers a pipeline that builds, tests, and validates the change in an environment that mirrors production. If the build is red, fixing it becomes the team's highest priority. That cultural rule is more important than any tooling.

Keeping Trunk Releasable: Branch Protection, Pre-merge Verification and Fast Reverts

A common misconception is that trunk-based development is risky because main is always moving. In practice, it is safer than long-lived branches precisely because main is always releasable. We enforce this with strict branch protection and pre-merge verification, not by slowing down merges. In my current setup, no one, including senior engineers, can push directly to main. Every change goes through a pull request, even if that pull request lives for only two hours.

The protection rules we apply are consistent across repositories:

# Example branch protection setup via GitHub CLI
gh api repos/:owner/:repo/branches/main/protection -X PUT \
  -f required_status_checks[strict]=true \
  -f required_status_checks[contexts][]="build" \
  -f required_status_checks[contexts][]="unit-tests" \
  -f required_status_checks[contexts][]="integration-tests" \
  -f enforce_admins=true \
  -f required_pull_request_reviews[required_approving_review_count]=1 \
  -f required_pull_request_reviews[dismiss_stale_reviews]=true \
  -f restrictions=null

This configuration requires branches to be up to date with main before merging, enforces at least one approving review, and blocks merges if any required check fails. The strict flag is critical; it prevents the "it passed on my old commit" problem by requiring a fresh run against the current tip of trunk.

Revert First, Fix Later

When main does break, the rule is simple: revert first, investigate after. Because changes are small, reverts are low-risk and restore green builds in minutes. I have found that teams new to this workflow struggle with the psychology of reverting. They want to push a fix-forward patch. That instinct is understandable but dangerous when other developers are blocked from merging. We tag every commit with a short, descriptive message and ensure git revert can be executed without manual conflict resolution in most cases. If you are building container images as part of this flow, the Docker Documentation on image tagging and layer caching is essential reading to make reverts and rebuilds deterministic.

For production services running on Kubernetes, keeping trunk releasable also means your deployment manifests in the same repository remain deployable. I keep application code and Kubernetes manifests in sync by running kubeval and kubeconform as required checks, so an invalid manifest never reaches trunk.

The 48-Hour Rule: Creating, Reviewing and Merging Short-Lived Branches

The operational definition I use for a short-lived branch is straightforward: it should be created, reviewed, and merged within 24 to 48 hours. If it lives longer, it is a sign the work was not sliced thinly enough. Slicing work is a skill. Instead of building an entire notification service behind a feature branch, we might merge in this order: first the database migration behind a feature flag disabled by default, then the API endpoint with no UI callers, then the background worker with dry-run mode, and finally the UI toggle. Each piece is independently reviewable and deployable, even if the feature is not yet visible to users.

Naming and hygiene matter at this velocity. We use a convention of initials/short-description-issue-id, for example ak/add-redis-cache-1428, and we delete the branch immediately after merge. Stale branches are an anti-pattern in this model; they signal work that was abandoned or superseded. Most hosting platforms can auto-delete branches on merge, and I recommend enabling it.

# Typical short-lived branch lifecycle
git checkout main
git pull origin main
git checkout -b ak/add-redis-cache-1428

# make small, atomic commits
git add app/cache.py tests/test_cache.py
git commit -m "feat(cache): add redis client with local fallback"

git push -u origin ak/add-redis-cache-1428
# Open PR, get review, ensure CI is green, squash and merge
# Branch is auto-deleted after merge

Code review changes significantly under this model. Reviews are smaller, often under 200 lines, and reviewers can respond within an hour instead of batching reviews for a Friday afternoon. I have found that review quality actually improves because the cognitive load is lower. You are reviewing a single, focused change rather than a 1,500-line feature dump that mixes refactoring, new logic, and test updates.

What If a Feature Cannot Be Sliced Small Enough?

Occasionally you will encounter work that genuinely cannot be released incrementally, such as a breaking schema change or a major framework upgrade. In those cases, we use techniques like branch by abstraction or feature flags rather than extending branch lifetime. Create an abstraction layer in trunk first, migrate callers incrementally behind it, then remove the old implementation. The branch that introduces the abstraction is small and short-lived, and all subsequent work also stays small.

Wiring Continuous Integration to Trunk: Pipeline Design for Sub-Ten-Minute Feedback

Trunk-based development lives or dies on pipeline speed. If developers have to wait 40 minutes for a build, they will stop pulling main frequently and start batching changes locally, which defeats the purpose. My target for a pre-merge pipeline is under 10 minutes, with faster feedback for earlier stages. We achieve this by parallelizing jobs, caching dependencies aggressively, and separating fast checks from slow ones.

A typical pipeline is split into three stages. Stage one runs in under two minutes and includes linting, formatting, unit tests, and static analysis. Stage two runs integration tests against ephemeral dependencies. Stage three builds artifacts and runs contract or end-to-end tests. Failures in stage one block the merge immediately and are cheap to fix. This is where workflow optimization techniques become critical. If you are using GitHub Actions, learning how to structure GitHub Actions Advanced Workflows: Matrix Builds, Reusable Actions and OIDC can reduce duplication and make these staged pipelines far easier to maintain. The same principles apply to GitLab users working with GitLab CI Pipeline Optimization: DAG, Cache and Parallel Jobs to cut feedback time with directed acyclic graphs and proper caching.

# .github/workflows/ci.yml - trunk CI focused on speed
name: ci
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

jobs:
  fast-checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12', cache: 'pip' }
      - run: pip install -r requirements.txt
      - run: ruff check .
      - run: pytest tests/unit -q --maxfail=1

  integration:
    needs: fast-checks
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        ports: ["5432:5432"]
        env: { POSTGRES_PASSWORD: postgres }
    steps:
      - uses: actions/checkout@v4
      - run: pytest tests/integration -q

  build:
    needs: integration
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t app:${{ github.sha }} .
      - run: docker run --rm app:${{ github.sha }} pytest tests/smoke -q

For trunk builds triggered on push to main, we add deployment to a development or staging environment automatically. This gives developers confidence that their change works when integrated with the rest of the system, not just in isolation on their branch. Observability is key here: we push pipeline metrics to our monitoring stack and alert if the main pipeline is red for more than 15 minutes.

Branching Model Branch Lifespan Integration Frequency Typical Release Cadence Best Use Case
Trunk-Based Development < 2 days, often hours Multiple times per day per developer Continuous / daily Teams practicing CI/CD, microservices
GitHub Flow 1-3 days Daily Continuous to weekly Web apps with PR-based deploys
GitFlow Days to weeks (feature, release, hotfix) Weekly or per release Scheduled (weekly/monthly) Versioned releases, slower cadence
GitLab Flow 1-7 days with environment branches Daily to weekly Continuous to weekly Teams needing environment promotion

The table above is not about declaring one model superior, but about showing the trade-off between isolation and integration frequency. In my experience, as deployment frequency goals increase, the overhead of GitFlow becomes difficult to justify.

Decoupling Deployment From Release: Feature Flags Instead of Feature Branches

The most common objection I hear is: "How do we work on incomplete features without a long-lived branch?" The answer is feature flags. A feature flag allows code to be merged to trunk and deployed to production while remaining dormant for users. This decouples deployment, which is a technical activity, from release, which is a product decision. I have used this pattern to merge database migrations weeks before the application code that uses them was enabled, with zero customer impact.

A simple implementation does not require an external service at first. You can start with a configuration file or environment variable, but for any serious use you will want a management system that supports targeting, gradual rollouts, and audit trails. When evaluating options, my review of Feature Flags for Progressive Delivery: LaunchDarkly, Unleash and OpenFeature covers the trade-offs between hosted and self-hosted solutions and the OpenFeature standard that helps avoid vendor lock-in.

Flag Hygiene Is Mandatory

Feature flags are powerful but they create tech debt if left unchecked. Every flag added is a conditional branch in your codebase that increases testing permutations. We enforce a lifecycle: flags are created with an owner, an expiration date, and a ticket to remove them. Short-lived release flags should be removed within two to four weeks after the feature is fully rolled out. Long-lived operational flags, such as kill switches or entitlement flags, are treated differently and documented as permanent configuration.

Here is a minimal pattern we use to keep flag usage explicit and testable:

# flags.py - simple wrapper around OpenFeature/Unleash
from openfeature import api

client = api.get_client()

def is_new_checkout_enabled(user_id: str) -> bool:
    return client.get_boolean_value(
        "new-checkout-flow",
        default=False,
        evaluation_context={"targetingKey": user_id}
    )

# usage in application code
from flags import is_new_checkout_enabled

def handle_checkout(request):
    if is_new_checkout_enabled(request.user.id):
        return new_checkout_flow(request)
    return legacy_checkout_flow(request)

Coupled with trunk-based development, this approach also improves security posture. Because all code is integrated daily, you are scanning and testing the actual code that will go to production, not a divergent branch. Hardening this flow with signed commits, short-lived OIDC tokens for deployments, and provenance is covered in detail in CI/CD Security: Pipeline Hardening, SLSA and Software Supply Chain, which I recommend reading once your trunk pipeline is stable.

Coordinating Trunk-Based Development Across Distributed Teams and Microservices

Scaling trunk-based development beyond a single team requires coordination, not lockstep. Each service or repository should have its own trunk. The principle is the same: small changes, frequent integration, always releasable. What changes is how you manage dependencies between services. We avoid cross-repository branching where a single feature branch spans multiple microservices. Instead, we make backward-compatible changes and use consumer-driven contracts to verify integration.

For example, when evolving an API, we do not break existing clients. We add a new field or a new endpoint version to trunk, deploy it, migrate clients independently, and then remove the deprecated field in a follow-up change. This is where Kubernetes Documentation on rollout strategies and readiness probes is relevant; even if your code change is safe, a bad rollout can cause an outage. Using rolling updates with proper health checks ensures that each small change to trunk can be deployed progressively without downtime. If you need more control over production exposure, pair this with the patterns described in Deployment Strategies: Blue-Green, Canary and Rolling Updates Compared.

In my experience, the hardest part of scaling is not tooling but communication. We use a lightweight RFC process for any change that affects more than one team, and we broadcast breaking infrastructure changes in a shared channel before they merge. The trunk is the integration point, but shared ownership of the pipeline is what makes it work. Every team can see the build status of every other team, and fixing a broken trunk is everyone's responsibility. On-call rotations include pipeline health as a service-level indicator, and we track metrics like mean time to green and change failure rate as leading indicators of delivery health.

Adopting trunk-based development is less about Git commands and more about discipline. Start by shortening your current branches. Enforce a rule that no branch lives longer than two days, requireCI to be green before merge, and make reverts painless. Add feature flags for work that needs more time. Over two to three sprints, you will notice merges become boring, and boring merges are exactly what you want in a high-performing delivery organization.

Frequently Asked Questions

How does trunk-based development work for a solo developer or a two-person team?

It works even better at small scale because the overhead is minimal. You can push directly to trunk for trivial changes like documentation or use ultra-short branches for anything else. The key practices remain: keep branches under a day, run automated tests on every push, and keep trunk deployable. You still get the benefit of fast feedback without the coordination cost of larger teams.

Do we need feature flags to adopt trunk-based development?

Not strictly, but they make it much more practical for user-facing features. Without flags, you need alternative techniques like branch by abstraction, dark launches, or small incremental changes that are invisible to users until the final piece merges. For teams just starting, combine trunk-based development with a simple flag system or even environment variables, and formalize flag management as you grow.

What if our CI pipeline is too slow for trunk-based development?

Fix the pipeline before forcing the workflow. Start by measuring where time is spent, then parallelize tests, cache dependencies, and split fast unit tests from slower integration tests as shown in the pipeline example above. In my experience, most teams can get a meaningful pre-merge signal in under five minutes with caching and proper job parallelization. A slow pipeline will push developers back toward long-lived branches.

How do we handle code review quality when merges happen so quickly?

Quality often improves because reviews are smaller and more focused. Enforce a single required reviewer, keep pull requests under 300 lines where possible, and use CODEOWNERS to route changes to the right experts. For high-risk areas like security or infrastructure, require two reviewers or add automated checks for static analysis and policy enforcement.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation