Sub topic 14
Rolling Out Gradually and Removing Old Code
A refactoring or migration is not finished when the tests pass on your branch. It is finished when the new code serves all traffic and the old code is gone. This chapter covers the last stretch: shipping a change in stages, watching for problems, and then deleting what is no longer needed. It also covers how to direct a coding agent through each stage.
This chapter assumes you have read the earlier chapters on scoping, characterization tests, small commits, and diff review. You should be comfortable with Git branches, a CI pipeline, and feature flags (a configuration value that switches code paths at runtime).
Why merging is not the end
Passing tests show that the new code matches the behavior you thought to check. Production traffic contains inputs you did not think of: odd currencies, empty lists, old database rows, concurrent requests. A gradual rollout limits the damage from those cases. It does this by exposing the new code to a small share of traffic first, and by keeping a fast way back.
Rollout has costs. Two code paths exist at the same time, every flag adds a branch to reason about, and old code that stays too long becomes an unowned liability. The goal is a short, planned overlap that ends in deletion.
Choosing a rollout strategy
The right strategy depends on what you changed and how costly a mistake is.
| Strategy | How it works | Best for | Main risk |
|---|---|---|---|
| Feature flag | A runtime switch selects old or new code | Behavior-sensitive refactors in a single service | Flags that are never removed |
| Shadow run | Old code answers; new code runs too and results are compared | Pure computations such as pricing or parsing | Doubled cost, and side effects running twice |
| Percentage rollout | A stable hash of a user or request ID decides who gets the new path | Changes where live behavior matters | Uneven sampling if the hash key is poorly chosen |
| Module by module | Migrate one module or endpoint per release | Library or framework upgrades | Long period with two styles in the codebase |
| Branch by abstraction | Put an interface in front of old and new implementations, then swap behind it | Replacing a dependency | The extra layer must be removed afterward |
These strategies combine. A common pattern is to migrate module by module, and to use a flag with shadow and percentage stages inside each module.
A flag with shadow mode and percentage rollout
This example continues the invoice refactoring from earlier chapters. The legacy function and the extracted-function version coexist, and a wrapper decides which one answers.
import hashlib
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("rollout")
TAX_RATE = 0.2
ROLLOUT_PERCENT = 25 # share of customers served by the new code
SHADOW_MODE = True # compare old and new for the remaining customers
def legacy_format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = round(subtotal * 0.2, 2)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}
def calculate_tax(subtotal):
return round(subtotal * TAX_RATE, 2)
def new_format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = calculate_tax(subtotal)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}
def in_rollout(customer_id, percent):
# A hash gives each customer a stable bucket from 0 to 99,
# so the same customer always gets the same code path.
digest = hashlib.sha256(customer_id.encode()).hexdigest()
return int(digest, 16) % 100 < percent
def format_invoice(customer_id, items):
if in_rollout(customer_id, ROLLOUT_PERCENT):
return new_format_invoice(items)
result = legacy_format_invoice(items)
if SHADOW_MODE:
try:
candidate = new_format_invoice(items)
except Exception:
log.exception("shadow: new code raised for %s", customer_id)
else:
if candidate != result:
log.warning("shadow mismatch for %s: %r != %r",
customer_id, result, candidate)
return result
if __name__ == "__main__":
items = [{"price": 10.0, "qty": 3}]
for cid in ("alice", "bob", "carol"):
print(cid, format_invoice(cid, items))Three details matter here:
- Stable bucketing. Using a random number per request would flip a customer between paths. A hash of the customer ID keeps each customer on one path, which makes bug reports reproducible.
- Shadow mode never changes the answer. The legacy result is always returned in the shadow branch. The new code's exceptions are caught and logged, so a bug in it cannot break a request.
- Side effects. This works because both functions are pure. If the code writes to a database or sends email, running both paths would do it twice. Shadow only the read-only part, or skip shadow mode.
Directing the agent through the rollout
Ask the agent to add the flag as its own step, separate from the refactoring. You can then review and revert the rollout mechanics independently. A scoped request might read:
Add a rollout wrapper around format_invoice in pricing.py.
Constraints:
- Keep legacy_format_invoice unchanged. Do not edit it.
- Add ROLLOUT_PERCENT and SHADOW_MODE as module constants, defaulting to 0 and True.
- Bucket customers with a hash of customer_id, not random().
- Log mismatches at WARNING level. Never let the new code's exceptions reach the caller.
- Add tests for: percent 0, percent 100, a stable bucket for a repeated ID, and a logged mismatch.
Show me the plan first. Run pytest before and after and report both results.Defaulting the percentage to 0 means the merge itself changes nothing in production. That makes the merge safe, and the change is switched on in a separate, deliberate step.
Deciding when to advance
Each stage needs an exit criterion that you write down before you start. Examples:
- Shadow mode: zero mismatches and zero exceptions over a full business cycle (for invoices, a month-end).
- Five percent: error rate and latency within agreed bounds of the baseline for a set time.
- One hundred percent: a stable period, for example two weeks, with no rollbacks.
The agent can help prepare for this step. For example, it can write a script that summarizes mismatch logs by input shape. It cannot judge from the code alone whether production is healthy. That judgment needs your metrics and your domain knowledge.
Removing the old code
Removal is the step teams skip, and the old path then becomes dead weight that confuses later readers. Plan it as a separate change, after the stable period, in this order:
- Set the flag to 100 percent and confirm nothing reads the legacy path.
- Delete the legacy function and the wrapper's branches.
- Delete the flag, its configuration, and any tests that exist only to compare old and new.
- Delete helper code that only the legacy path used.
- Run the full verification loop (tests, type checker, linter) and review the diff.
Start by finding every reference. A text search catches names in strings, config files, and docs that a structural tool may skip:
grep -rn "legacy_format_invoice\|ROLLOUT_PERCENT\|SHADOW_MODE" src tests docs configThen ask the agent to make the deletion, with the search results as its checklist:
Remove the legacy invoice path.
- Delete legacy_format_invoice, in_rollout, ROLLOUT_PERCENT, and SHADOW_MODE from pricing.py.
- Make format_invoice(customer_id, items) delegate directly to the new logic. Keep its signature unchanged.
- Delete the shadow-mode and rollout-percentage tests. Keep the characterization tests.
- Report any remaining match of the names above, including in config and docs.
- Run pytest, the type checker, and the linter before and after.Keep the characterization tests. They no longer compare two implementations, but they still protect the behavior you spent the whole migration preserving.
Cleanup mistakes to watch for
- Deleting too early. Removing the legacy code while the flag is still below 100 percent removes your rollback. Check the live flag value, not only the default in the code.
- Dynamic references. Code called through a string name, a plugin registry, a scheduled job, or another repository is invisible to a search of one project. Ask the agent to list what it could not verify, and check those places yourself.
- Over-broad cleanup. An agent asked to "remove dead code" may delete things that merely look unused. Name the targets explicitly, and read the diff for deletions outside them.
- Orphaned configuration. Environment variables, dashboards, and alerts for the old path often outlive the code. Include them in your checklist.
- Flag debt. A flag with no owner and no removal date tends to stay. Record the removal task when you create the flag.
Putting it together
A complete rollout for one step of a larger migration looks like this:
- Merge the new code behind a flag at 0 percent.
- Enable shadow mode and review mismatches.
- Raise the percentage in stages, checking the exit criteria at each one.
- Reach 100 percent and wait out the stable period.
- Remove the old code and the flag in a separate commit, with the agent's diff reviewed like any other pull request.
For a large migration, repeat these steps per module. Track each module's stage in the migration plan so that you can see which modules still carry both paths.
Exercise
Your wrapper uses random.random() < 0.25 on every request to choose the new code path. A customer reports that their invoice total changed between two page loads. What is the cause, and how do you fix it?
Show answer
The random choice puts the same customer on the old path for one request and the new path for the next, so any difference between the two implementations shows up as a changing result. Fix it by bucketing on a stable key, such as a hash of the customer ID modulo 100, so each customer always gets the same path.
Exercise
A teammate wants the agent to delete the legacy function in the same pull request that raises the rollout from 50 to 100 percent. Give two reasons to split these into separate changes.
Show answer
First, the flag at 100 percent needs a stable period before you can trust it, and deleting the legacy code removes your fast rollback during that period. Second, separate changes keep each diff small and reviewable, and a problem in the rollout can be reverted without also restoring deleted code.
Exercise
Shadow mode is safe for format_invoice. Why might it not be safe for a function that charges a payment card, and what would you do instead?
Show answer
Shadow mode runs both implementations, so the charge would happen twice. Instead, shadow only the read-only computation (for example the amount calculation) and compare those results, or use a percentage rollout with the old path left untouched for the remaining customers.