Skip to main content

Trunk Based Development Best Practices

Trunk Based Development is a development methodology where all developers frequently integrate changes into the trunk (main branch). The idea itself is simple, but running it continuously with multiple team members requires clear rules for branching, code review, CI/CD, feature flags, and how to manage multiple environments, along with the prerequisites that support them.

This article organizes the "conditions" and "concrete steps" for making trunk based development work smoothly in a team. For the comparison with GitLab Flow and the basic concepts, see Trunk Based Development vs GitLab Flow.

Core Principles for Team Development​

These are the principles every team member should share when running trunk based development with multiple people.

  1. Keep the trunk always green and releasable — Never leave the build or tests failing. If it breaks, restoring it is the top priority.
  2. Integrate into the trunk at least once a day — Do not allow changes to sit waiting for review for days. Keep changes small at all times.
  3. Keep branches short-lived (target: within 24 hours) — A long-lived branch effectively becomes a "mini trunk" and the pain of merging comes back.
  4. Hide unfinished features behind feature flags and integrate anyway — Instead of waiting for completion, integrate small pieces in a state that is safe to deploy.
  5. When something breaks, either revert or fix it immediately — Decide as a team which to prioritize, revert or fix forward (described later).

Prerequisites Checklist​

Trunk based development works more smoothly the more the following conditions are in place. Rather than waiting for everything to be ready, it is realistic to adopt it while improving the missing parts step by step.

ConditionGuidelineImpact if lacking
Fast CIPR CI completes within 10 minutesFeedback is delayed and branches live longer
Automated testsUnit tests exist for the core logicBroken changes land in the trunk and rework increases
Code review capacityFirst review within hours (or by the next business day at the latest)Waiting for review becomes a bottleneck and changes pile up
Feature flag infrastructureFlags can be added or toggled immediatelyUnfinished features cannot be hidden, leading to large branches
Automated deploymentMerging to the trunk deploys automaticallyIntegration and release cannot be separated, and releases become scary
Rollback capabilityCan roll back with one command or a few clicksRecovery from incidents is slow and changes are avoided
Monitoring and alertsAnomalies can be detected right after deploymentBroken changes go unnoticed and the impact spreads
tip

If CI is slow, start with parallelizing tests, caching, and test selection based on changed files (Test Impact Analysis). CI duration has the biggest influence on the feasibility of trunk based development.

Daily Workflow for Multiple Members​

A typical day looks like this. The key is for everyone to keep the cycle of "short-lived branch → small PR → merge the same day" going.

Steps​

  1. Update the trunk before starting work — Starting from an old trunk causes conflicts.
  2. Create a short-lived branch — Name it so the change is clear (e.g., feat/add-order-validation).
  3. Commit in small units — Aim for one logical change per commit, keeping the code in a working state.
  4. Push early and open a pull request — A draft PR is fine. The goal is to start CI and review early.
  5. Respond to CI and review feedback — Address comments with small additional commits.
  6. Bring in the latest trunk before merging — Resolve conflicts on the branch before merging.
  7. Merge into the trunk and delete the branch — Automatic deployment runs after the merge.

Example Commands​

# 1. Update the trunk
git switch main
git pull --rebase

# 2. Create a short-lived branch
git switch -c feat/add-order-validation

# 3. Make changes and commit in small steps
git add -p
git commit -m "Add order amount validation"

# 4. Push early and open a PR (a draft is fine)
git push -u origin feat/add-order-validation

# 5. Bring in the latest trunk before merging
git fetch origin
git rebase origin/main

# 6. Delete the branch after merging
git switch main
git pull
git branch -d feat/add-order-validation

Tips to Reduce Conflicts During Parallel Work​

  • Always pull the latest trunk when starting work and before pushing (git pull --rebase / git fetch + rebase)
  • For work touching the same file or function, coordinate who goes first, or merge one change before starting the other
  • Keep renames, formatting, and file moves in separate PRs, not mixed with functional changes
  • Do not leave PRs waiting for review. As a rule, review on the same day
  • If a PR looks like it will grow large, consider splitting it early

Delivering Larger Features with Trunk Based Development​

Even features that take days or weeks can be integrated into the trunk every day. There are three typical techniques.

1. Split into Vertical Slices and Merge Sequentially​

Instead of splitting a feature by layer (UI, API, DB), split it into small units that deliver user value (vertical slices) and merge them in the order they become usable.

2. Branch by Abstraction​

Rather than rewriting the existing implementation directly, first introduce an abstraction (interface) so that old and new implementations can be switched, then migrate gradually. This is a standard technique for combining large refactoring with trunk based development.

3. Hide Behind Feature Flags (Dark Launch)​

Integrate an unfinished or unreleased feature into the trunk with the flag disabled, then enable the flag and release it gradually once it is ready.

Feature Flag Operating Rules​

Feature flags are the key to trunk based development, but leaving them unattended turns them into technical debt. Decide on the following rules as a team.

Flag Types and Lifespans​

TypePurposeExpected Lifespan
Release flagHiding unfinished features, gradual rolloutDelete soon after release (days to 2 weeks)
Experiment flagA/B testing and experimentsDelete right after the experiment ends
Ops flagPausing features, kill switchPermanent (required for operations)
Permission flagExposing features to specific users or plansPermanent

Example Operating Rules​

  • Decide on a naming convention: Use a prefix that shows the purpose, such as release_<feature-name>
  • Assign an owner: Make the person responsible for deleting each flag explicit
  • Set a deletion deadline: Give release flags a deadline such as "2 weeks after release" and detect overdue flags
  • Default to disabled: New flags should default to disabled (OFF); enabling them should be explicit
  • Make deletion a task: Include flag deletion in the release checklist
warning

If you keep adding flags without deleting them, conditional branches in the code explode, the number of test combinations grows, and maintenance costs skyrocket. Treat flags as debt: always pay them back by deleting them.

Handling Multiple Environments (Dev / Staging / Prod)​

Trunk based development does not use the idea of "separating Dev, Staging, and Prod with branches." Environments are stages of the deployment pipeline, not branches, and the differences between environments are expressed by "which stage the same artifact is promoted to" and by per-environment configuration and feature flags.

Principle: Environments Are Deployment Targets, Not Branches​

  • The only branch is main. Do not create environment branches such as develop, staging, or production
  • Build only once, and promote the resulting artifact (e.g., a container image) through the environments in order (Build Once, Promote Everywhere)
  • The "state of the Staging environment" is not the state of a branch; it is represented by the deployment record of which artifact (which commit) is in which environment
  • Rollbacks are done by "redeploying the previous artifact" or "turning the feature flag back OFF"; no branch operations are needed

Example Promotion Flow​

The key is to use the same artifact (the same image digest) in every environment. Rebuilding per environment creates a situation where "what was tested differs from what runs in production."

How to Use Branches​

BranchPurposeNotes
mainThe single integration point for all developmentKeep it always releasable
Short-lived work branchesTemporary work before reviewMerge within 24 hours and delete
Release branchesMaintenance of versioned productsOnly when needed (mobile apps, packaged software, on-premises products, etc.)
Environment branchesDo not useNever create develop, staging, or production

Even for products that need release branches (app store reviews, long-term support, and so on), deployment to environments is done by promoting artifacts, not by branches. Bug fixes are made on main and then cherry-picked into the release branch, following "upstream first."

Which commit is in which environment is tracked not with branches but with deployment records or release tags (e.g., v1.2.3 at production deployment).

How to Express Per-Environment Differences​

What differs between environments is not the "code" but the "configuration." Express the differences with the following mechanisms.

  • Externalize configuration: Inject per-environment values through environment variables, secrets, and IaC (Terraform, Helm values files, etc.)
  • Feature flags: Keep the code identical and toggle features per environment (e.g., enabled in Staging, disabled in Prod)
  • Configuration management: Absorb infrastructure and middleware differences in configuration management, not in code branches
  • Backward-compatible database migrations: During a rollout, old and new code versions coexist, so keep compatibility with the Expand / Contract pattern

Where to Put the Approval Process​

Teams that used to approve "merging to the production branch" move the approval into the deployment pipeline.

  • Put an approval gate on production promotion using CI/CD environment protection (e.g., GitHub Environments required reviewers)
  • Keep a deployment record of who promoted which artifact to production and when (for audits)
  • When separation of duties (SoD) is required, achieve it with pipeline permissions, not with branch separation

From "Branches Represent Environments" to "Artifacts, Config, and Flags Represent Environments"​

Whereas GitLab Flow says "the state of a branch represents the state of an environment," the fundamental difference in trunk based development is thinking that "the state of the artifact + configuration + flags represents the state of the environment."

AspectSeparating environments with branchesTrunk based development
Representing an environmentEnvironment branchesPipeline stages and deployment records
Syncing between environmentsMerges and cherry-picksPromote the same artifact (no syncing needed)
Per-environment differencesCode differences between branchesConfiguration, secrets, feature flags
RollbackRevert on the branch and redeployRedeploy the previous artifact, turn flags OFF
ApprovalApproval to merge into the production branchApproval gate in the pipeline

This shift brings advantages: "what was verified in Staging is always the same as what runs in production," "code does not drift between environments," and "rollbacks are simple." On the other hand, it requires deployment pipelines, configuration management, and feature flags, so it should be adopted together with the prerequisites checklist.

info

Environments remain "stages for verification and risk management." The reason to have Dev, Staging, and Prod is not to separate code but to verify the same artifact while raising risk gradually. The number of environments and the strictness of approvals can be adjusted to the product's requirements.

Review and Merge Rules​

  • Keep PRs small: Aim for 400 lines or less. Split anything larger than what can be reviewed well
  • Set a review SLA: For example, "first review within 4 hours, by the next business day at the latest." Review backlog is the biggest enemy of trunk based development
  • Configure required checks: Use branch protection to require CI success
  • Standardize the merge method: Use squash merge or rebase merge to keep a linear history
  • Consider a merge queue: Automate re-running tests when the trunk advances right before a merge

Example Trunk Protection Settings (GitHub)​

  • Require a pull request before merging
  • Require status checks to pass before merging
  • Require linear history
  • Require merge queue (depending on team size and update frequency)

When the Trunk Breaks​

Deciding the response policy in advance makes recovery faster when the trunk breaks.

The Principle: Recovery Comes First​

  1. Detect immediately: Check CI failure notifications and monitoring alerts
  2. Decide between revert and fix forward
    • Revert: If the cause is unknown or the impact is large, revert the change first and bring the trunk back to green (recommended)
    • Fix forward: If the cause is clear and fixable in minutes, fix it in place and move on
  3. Redo the reverted change in smaller steps

Stop the Line​

While the trunk is red, stop new merges and have the whole team prioritize recovery. A culture that does not tolerate "it is not my change, so I will leave it" is important.

Numbers the Team Should Agree On​

To reduce subjective judgment, make numbers like the following explicit as team rules.

ItemExample GuidelineReason
Branch lifespanWithin 24 hoursLong-lived branches increase merge conflicts
Integration frequencyAt least once per person per dayMaintains the rhythm of small integrations
PR size400 lines or lessBalances review quality and speed
First reviewWithin 4 hoursPrevents branches from living longer due to waiting
CI durationWithin 10 minutesKeeps the feedback loop short
Release flag lifespanWithin 2 weeks after releasePrevents technical debt

Anti-Patterns​

Anti-PatternWhat Goes WrongCountermeasure
Long-lived branches (weeks)Conflicts and big-bang integrations occurSplit with vertical slices, Branch by Abstraction, or flags
Leaving PRs waiting for reviewBranches live longer and CI fails repeatedlyDefine and follow a review SLA
PRs that are too largeReviews become superficial and bugs slip throughSplit with a 400-line guideline
Leaving flags unattendedConditional branches and test combinations explodeSet deletion deadlines and owners
Leaving a broken trunkEveryone's work stops and trust is lostEnforce recovery-first and Stop the Line
Speeding up with insufficient testsProduction incidents increase and changes are avoidedBuild CI and tests first, then increase speed
Creating a branch per environment (develop / staging / production)Code drifts between environments and cherry-picking repeats foreverTreat environments as pipeline stages and promote artifacts
Rebuilding or cherry-picking per environmentThe tested artifact no longer matches what runs in productionPromote the same artifact (Build Once, Promote Everywhere)

Gradual Adoption Roadmap​

Rather than jumping straight to full trunk based development, the following order makes it easier to establish.

  1. Set up CI — Get builds and tests running automatically on every PR
  2. Shorten branches — Reduce feature branch lifespan step by step: 1 week → 3 days → 1 day
  3. Introduce feature flags — Make it possible to integrate unfinished features while hidden
  4. Make daily merging a habit — Make at least one integration per person per day a team rule
  5. Improve with metrics — Measure deployment frequency, lead time, change failure rate, and time to restore (DORA metrics) and review them

Final Checklist​

Use this checklist to verify that your team's operation is functioning as trunk based development.

  • The trunk (main) is always in a state where the build and tests pass
  • Every member integrates into the trunk at least once a day
  • Branch lifespan stays within 24 hours
  • PRs are small (around 400 lines or less) and reviews are returned the same day
  • Unfinished features are integrated behind feature flags
  • Feature flags have deletion deadlines and owners
  • Merging to the trunk deploys automatically and a rollback method is available
  • Environments (Dev / Staging / Prod) are managed by promoting artifacts and by configuration and flags, not by branches
  • The revert / fix forward policy for a broken trunk is decided
  • Metrics such as deployment frequency and lead time are measured

Conclusion​

Trunk based development is not just about "reducing branches"; it is the sum of a team's discipline and mechanisms for continuing to integrate small changes. By starting with faster CI and then shortening branch lifespans, adding feature flags, and setting review SLAs, even teams with multiple members can establish it without overreach.