Feature flags and trunk-based development: merging unfinished work safely
How feature flags make trunk-based development work: what DORA, Martin Fowler's site and Google's engineering book say, when to use a flag vs a keystone interface or branch by abstraction, a tested branch-by-abstraction example, and how to keep flags from piling up.
Short answer: In trunk-based development everyone merges small changes into the main branch at least once a day, so unfinished features end up in code that gets released. A feature flag keeps that code switched off until it's ready. It isn't the only way to hide unfinished work: building the UI last or branch by abstraction often need no runtime flag at all.
What is trunk-based development?
DORA, the research program behind the State of DevOps reports, defines it as each developer dividing work into small batches and merging into trunk "at least once (and potentially several times) a day", with branches that "typically last no more than a few hours". Its capability page lists the practices its analysis of 2016 and 2017 data associated with higher delivery performance (DORA):
| Practice | DORA's goal |
|---|---|
| Active branches | Three or fewer |
| Merging to trunk | At least once a day |
| Code freezes and integration phases | None |
DORA calls trunk-based development "a required practice for continuous integration", together with fast automated tests after each commit, a build that stays green (fix or revert within minutes) and builds of a few minutes. Martin Fowler's branching patterns article treats trunk-based development as largely another name for continuous integration: everyone commits to the mainline every day, and the real question "isn't whether or not there's a feature branch, but when developers integrate with mainline". Short-lived branches with pull requests fit: DORA's branches last a few hours, and Fowler mentions larger teams using feature branches of no more than a couple of days. Google's engineering book describes trunk-based development (one repository, no development branches) as "a particularly scalable policy approach", used across a monorepo shared by roughly 50,000 engineers (Software Engineering at Google, chapter 16).
Why does trunk-based development need feature flags?
A feature that takes two weeks can't stay on a branch for two weeks under these rules, so its first pieces reach the main branch long before it's finished, and from there the next release (teams release from trunk or cut short-lived release branches from it). Something has to keep users from seeing it. Google's book puts the policy as relying on testing and CI, keeping the build green, and disabling incomplete features at runtime. Feature flags do that:
- Merged but off. Code that's turned off can go to production, with unit tests even for the paths that are off; the site recommends choosing the implementation at startup through an abstraction rather than scattering if/else checks (trunkbaseddevelopment.com: feature flags).
- Released separately from deploys. Google's book notes that "the flag value can be updated independently from the binary release".
- Gradual rollout. Google's book says to make sure engineers "flag guard" all changes, so new code "lives in the binary alongside the old codepath", and warns that turning a flag on for everyone at once "is not a great idea" (chapter 24). It also cautions that not every feature can be hidden behind a flag without a lot of complexity, and that flagged code isn't a safety net for truly sensitive features, since it's in the shipped binary.
With long-lived feature branches, a feature waits by not being merged; with continuous integration, Fowler notes, it waits by holding back the keystone or keeping a flag off.
When should I use a flag, and when something else?
Fowler's site describes several ways to keep unfinished work hidden on trunk; a runtime flag is only one of them:
| Technique | How it hides the work | Runtime flag needed? | Good for |
|---|---|---|---|
| Keystone interface | Build and integrate the back end first; add the UI (the "keystone") last | No | Features with one obvious entry point |
| Branch by abstraction | Put an interface in front of the old code, build the new implementation behind it, switch, then delete the old one | Optional (a flag can do the switch) | Replacing a component gradually |
| Feature flag | A condition chooses the old or new path at runtime | Yes | Features with many entry points, gradual rollouts, kill switches |
| Dark launch (a variation of the keystone approach) | The new feature is called once it's built, but its results aren't shown to users | Depends on how calls are switched on | Measuring the impact on back-end systems |
Sources: Keystone Interface (including dark launching), Branch By Abstraction, trunkbaseddevelopment.com: branch by abstraction. Fowler's keystone article suggests a flag when the UI can't be packaged into a simple keystone, keeping the toggle in the UI, and warns that building the UI last works best with thin vertical slices; otherwise the back end may not fit the UI it eventually gets. Each release flag is code that must be removed later, so where a keystone or an abstraction hides the work just as well, it saves that cleanup.
What does branch by abstraction with a flag look like?
trunkbaseddevelopment.com lists five steps: add an abstraction, build the second implementation (switched off), switch it on for everyone, remove the old implementation, remove the abstraction. Its rule is that no commit "should jeopardize the ability to go live". Here, a tax calculation moves from a flat rate to per-country rates, with both implementations on trunk:
// tax.js
// Branch by abstraction: callers use getTaxCalculator(); both implementations live on trunk.
// Amounts are integer cents and rates are basis points, so rounding is exact (half up).
const taxCents = (subtotalCents, rateBasisPoints) => Math.round((subtotalCents * rateBasisPoints) / 10000)
export const legacyTax = {
// Old code path: flat 21%
calculate: (order) => taxCents(order.subtotalCents, 2100),
}
export const newTax = {
// New code path, merged to trunk while still switched off: per-country rates
rates: { ES: 2100, DE: 1900, FR: 2000 },
calculate(order) {
const rate = this.rates[order.country]
if (rate === undefined) throw new Error(`No tax rate for ${order.country}`)
return taxCents(order.subtotalCents, rate)
},
}
export async function getTaxCalculator(client, context) {
const useNew = await client.getBooleanValue('release_per_country_tax', false, context)
return useNew ? newTax : legacyTax
}
The same contract tests run against both implementations while both are on trunk, plus tests for the switch:
// Contract tests: both implementations must pass them while both are on trunk.
for (const [name, impl] of [['legacy', legacyTax], ['new', newTax]]) {
describe(`${name} implementation`, () => {
test('Spanish order pays 21%', () => assert.equal(impl.calculate({ subtotalCents: 10000, country: 'ES' }), 2100))
test('zero subtotal pays nothing', () => assert.equal(impl.calculate({ subtotalCents: 0, country: 'ES' }), 0))
test('half a cent rounds up', () => assert.equal(impl.calculate({ subtotalCents: 2150, country: 'ES' }), 452))
})
}
We ran the full test file with Node.js and @openfeature/server-sdk 1.23.0: eleven tests passed, covering both implementations, the new path rejecting a country it has no rate for, the switch in both positions, and the old path when the flag is missing (results, code). Amounts are integer cents and rates basis points, because rounding floating-point money (Math.round(21.5 * 0.21 * 100) / 100) gives 4.51 instead of 4.52; the integer version matched exact half-up rounding for every amount from 0.01 to 1,000.00 at all three rates. It's an illustration of the pattern, not tax code. Once release_per_country_tax is on everywhere and stable, the last two steps are to delete legacyTax and the flag check, then the abstraction if it no longer earns its keep. The same pattern applies to data: see database migrations behind feature flags.
How do I keep flags from piling up in trunk-based development?
Merging daily behind flags creates many short-lived flags; the risk is that they stop being short-lived. trunkbaseddevelopment.com notes that flags "often get forgotten as development teams pivot":
- Give every release flag an owner and a removal date when it's created, and make removing it part of finishing the feature (stale feature flags).
- Put the flag type in the key, so release flags are easy to list and age (naming conventions).
- Test the combinations you expect to ship, not every combination; trunkbaseddevelopment.com says CI should guard "your reasonable expected permutations of flags" (testing code that uses flags).
- Use the keystone approach when one entry point is enough and the work comes in thin slices: no flag, nothing to remove.
Do I need a flag service for trunk-based development?
Not at first. A flag that only hides unfinished work can be a configuration value or environment variable read at startup. A flag service becomes worth it when you want to change flags without a deploy, roll out to a percentage of users, target specific users, or have an audit log of who turned what on; see self-hosted vs SaaS feature flags and the best feature flag tools. All tools are in the directory.