A real-world plan for refactoring a critical payment allocation module during ongoing feature work: characterisation and golden-master tests, branch by abstraction, small trunk-based PRs, shadow (parallel) runs comparing old and new results, flag-controlled cut-over and coordination with other teams.
I wouldn't stop the other teams or run a long-lived branch. The plan:
IPaymentAllocator interface in front of the module, so old and new implementations live side by side on main, and refactor or rebuild behind it in small daily PRs.Coordination matters as much as code: CODEOWNERS, agreed seams and pairing with the teams whose features touch it. The trade-off: the shadow run costs extra compute and a few weeks, which is cheap next to a misallocated payment.
"The first thing I'd do is define why we're refactoring and what done looks like. 'Payment allocation is messy' isn't a goal. 'Partial payments across multiple invoices take two weeks to change and caused three incidents this year; afterwards a new allocation rule should take two days' is a goal, and it tells me which parts to touch.
For example, at [company] the allocation module decided how each incoming payment was split across a customer's open invoices, and [two] other teams were adding features to it every sprint. I couldn't freeze it, and a long-lived branch would have been merge hell. So I started with safety nets: a golden-master test that ran [10,000] synthetic, production-shaped payment scenarios through the current code and snapshotted every allocation. That took [days] and found [n] existing quirks we agreed to preserve.
Then I used branch by abstraction. I introduced an
IPaymentAllocatorinterface in front of the module with the old code as the only implementation, merged that, and built the new structure behind it in small PRs, each under [300] lines and merged to main daily. The other teams kept working on the old implementation; when they changed a rule, the golden master told us both versions needed it, and I paired with them on the overlap. Before switching, we ran a shadow mode for [a full billing cycle]: production ran both allocators, returned the old result and logged any difference. We fixed [n] mismatches, mostly rounding on split cents, until the mismatch counter stayed at zero. Then a feature flag moved traffic from 1% to 100% over [a week], and we deleted the old code [two weeks] later.The result was [no customer-facing allocation errors], and the next allocation rule took [two days] instead of [two weeks].
The mistake I see is treating a critical refactor as a code problem only. The safety comes from comparison in production and from talking to the teams in the same code every day."
| Phase | What happens | Exit criteria |
|---|---|---|
| 0. Goal | Agree the change it enables and how you'll measure it | Product owner and other team leads agree |
| 1. Pin behaviour | Golden-master tests over synthetic production-shaped data | Suite green, quirks documented |
| 2. Abstraction | IPaymentAllocator in front, old implementation only |
Merged; no behaviour change |
| 3. Build behind it | New implementation in small PRs on main | Golden master passes for new implementation |
| 4. Shadow run | Both run in production; old result returned; mismatches counted | Zero mismatches over a full billing cycle |
| 5. Cut-over | Flag 1% → 10% → 50% → 100% | Error rate and latency flat at each step |
| 6. Clean-up | Delete old implementation and flag | Old code gone within an agreed window |
| Risk | Mitigation |
|---|---|
| Their change lands in old code only | Golden master fails for new implementation; CODEOWNERS adds a reviewer from the refactoring stream |
| Merge conflicts | Trunk-based, small PRs, daily merges; agree which files move when |
| Two versions drift | Shadow mismatch metric is shared on the team dashboard |
| Priority clash | Refactoring is tied to a product outcome, visible on the board, not a side project |
For a module handling about [40,000] payments a day, the shadow run cost roughly 8% extra CPU on the allocation workers for four weeks. It surfaced 23 mismatch patterns, 19 of them one-cent rounding differences on split payments, all fixed before any customer saw the new code; cut-over had zero rollbacks.
Checks that the candidate can run a risky refactor of critical code in a live, shared codebase with real safety nets and real coordination, not just describe refactoring techniques.
Green flags
Red flags
A long-lived branch diverges from main as other teams keep shipping. Merge cost grows with time and with the number of people touching the same files, and the final merge is one huge, unreviewable change. Trunk-based work with an abstraction keeps the divergence at zero: both implementations are on main, compiled and tested on every build.
step 1 step 2 step 3 step 4
callers callers callers callers
| | | |
v v v v
OldAllocator IPaymentAllocator IPaymentAllocator IPaymentAllocator
| / \ |
OldAllocator OldAllocator NewAllocator NewAllocator
(flag / shadow decides) (old deleted)
Every step is a mergeable, deployable state. The abstraction is also the seam for the shadow comparison and the flag.
Generate a large, varied input set (property-based generators or rules over synthetic customers: overpayments, partial payments, credit notes, multiple currencies, cent rounding), run it through the current code, and store the outputs as approved snapshots (Verify). The new implementation must produce identical snapshots. Use synthetic or properly anonymised data: real payment data in test fixtures is a Privacy Act (APP 11) risk.
A decorator calls both implementations, returns the old result, and compares. The new path must be side-effect free in shadow mode (no writes, no events) and must not slow or break the request: run it with a timeout, catch its exceptions, and sample if load is high.
request -> ShadowAllocator -> old.Allocate() -> result returned
\-> new.Allocate() -> compare -> metric + log (no PII)
The mismatch rate is the release gate. Look at mismatches by category; some will be bugs in the old code that the business decides to keep or fix (a separate, explicit behaviour change).
With Microsoft.FeatureManagement's percentage filter, or a custom filter keyed by customer id so a customer gets a consistent allocator, increase gradually and watch allocation errors, latency and finance reconciliation. Put a date on deleting the old implementation and the flag: an abandoned dual path is the worst outcome, two implementations to maintain.
Counter<long> for mismatches.A shadow decorator behind the abstraction: production keeps the old result while the new allocator is compared.
namespace Payments;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
public sealed record Allocation(Guid InvoiceId, decimal Amount);
public sealed record Payment(Guid Id, Guid CustomerId, decimal Amount);
public interface IPaymentAllocator
{
// Pure calculation: no writes, so it is safe to run twice in shadow mode.
IReadOnlyList<Allocation> Allocate(Payment payment, IReadOnlyList<(Guid InvoiceId, decimal Owing)> openInvoices);
}
public sealed class ShadowAllocator(
LegacyAllocator legacy,
NewAllocator candidate,
IMeterFactory meters,
ILogger<ShadowAllocator> logger) : IPaymentAllocator
{
private readonly Counter<long> _compared = meters.Create("Payments.Allocation").CreateCounter<long>("allocation.shadow.compared");
private readonly Counter<long> _mismatched = meters.Create("Payments.Allocation").CreateCounter<long>("allocation.shadow.mismatched");
public IReadOnlyList<Allocation> Allocate(Payment payment, IReadOnlyList<(Guid InvoiceId, decimal Owing)> open)
{
var result = legacy.Allocate(payment, open); // the answer production uses
try
{
var shadow = candidate.Allocate(payment, open);
_compared.Add(1);
if (!result.SequenceEqual(shadow))
{
_mismatched.Add(1);
// Ids only: no customer names or card data in logs.
logger.LogWarning("Allocation mismatch for payment {PaymentId}", payment.Id);
}
}
catch (Exception ex)
{
// The candidate must never break production while in shadow mode.
_mismatched.Add(1);
logger.LogError(ex, "Candidate allocator failed for payment {PaymentId}", payment.Id);
}
return result;
}
}
public sealed class LegacyAllocator : IPaymentAllocator
{
public IReadOnlyList<Allocation> Allocate(Payment p, IReadOnlyList<(Guid InvoiceId, decimal Owing)> open) => throw new NotImplementedException("existing code");
}
public sealed class NewAllocator : IPaymentAllocator
{
// Oldest invoice first, never allocating more than is owing.
public IReadOnlyList<Allocation> Allocate(Payment p, IReadOnlyList<(Guid InvoiceId, decimal Owing)> open)
{
var remaining = p.Amount;
var result = new List<Allocation>();
foreach (var (invoiceId, owing) in open)
{
if (remaining <= 0) break;
var amount = Math.Min(remaining, owing);
result.Add(new Allocation(invoiceId, amount));
remaining -= amount;
}
return result;
}
}
// Program.cs: the phase is a deployment decision, not a code change.
builder.Services.AddSingleton<LegacyAllocator>();
builder.Services.AddSingleton<NewAllocator>();
var phase = builder.Configuration["Allocation:Phase"]; // "Legacy" | "Shadow" | "New"
switch (phase)
{
case "Shadow": builder.Services.AddSingleton<IPaymentAllocator, ShadowAllocator>(); break;
case "New": builder.Services.AddSingleton<IPaymentAllocator>(sp => sp.GetRequiredService<NewAllocator>()); break;
default: builder.Services.AddSingleton<IPaymentAllocator>(sp => sp.GetRequiredService<LegacyAllocator>()); break;
}
// For gradual cut-over, swap the switch for a Microsoft.FeatureManagement percentage or
// customer-id targeting filter evaluated per request.
The technical tools (golden masters, branch by abstraction, shadow runs, flags) are well known; what makes this senior is matching the safety net to the blast radius and running it as a team effort. Payment allocation errors are customer-visible and hard to unwind, so a few weeks of shadow running is cheap insurance. For an internal report, characterisation tests and a flag would be enough.
The other judgement call is refactor versus rebuild behind the abstraction. If the old code can be untangled in place with automated refactorings, do that; the abstraction and shadow run are for when the new structure is different enough that you're effectively writing a second implementation.
| Safety net | When it fits | Cost | When not to |
|---|---|---|---|
| Characterisation tests | Any refactor of untested code | Hours to days | Never skip |
| Golden master over generated data | Calculations with many input combinations | Days | Simple CRUD |
| Shadow run in production | High-impact, hard-to-reverse outputs (money, allocations) | Extra compute, weeks of elapsed time | Code with side effects you can't isolate |
| Flagged percentage cut-over | Any risky switch | Flag management | Changes that must be atomic across all users |
I treat a large refactoring as a series of small, behaviour-preserving steps merged to main continuously, not a big-bang branch. First I pin current behaviour with characterisation tests. Then I pick a technique: strangler fig to route traffic piece by piece to a new implementation, branch by abstraction to put an interface in front of the old code and swap implementations behind it, or parallel change (expand, migrate, contract) for APIs and database schemas. Feature flags and shadow comparisons let old and new paths run side by side. I prioritise hotspots (code that changes often and hurts), keep refactoring commits separate from feature commits, and define an end state so it does not drag on forever.
Good enough means the tests would notice if your change broke something. Check three things. Coverage of the change area (not the codebase): every branch you'll touch is executed, including the input grid of any golden master, the set of input combinations whose outputs you snapshot, which should include boundary values. Sensitivity: run Stryker.NET on the changed files only (--since) and explain or kill surviving mutants, or break a line by hand and confirm a test fails. Reliability and speed: run the new tests repeatedly to prove they are deterministic, and keep them fast enough to run in the PR pipeline on every commit, because a safety net that is flaky or only runs nightly won't protect the change.
Treat each step as a controlled experiment. Before starting, agree the promotion and rollback criteria: the SLIs for the affected endpoints (error ratio, p95 latency, one business metric such as checkout conversion), the thresholds and the minimum sample size. Use a targeting filter (hashed user id) so users stay in their cohort, and tag telemetry with the flag variant (an Application Insights custom dimension or OpenTelemetry attribute) so a KQL query or dashboard compares the new cohort against the control cohort in the same time window. Step 1% → 10% → 50% → 100%, holding each step through a peak period. If the treatment cohort is worse beyond the threshold, turn the flag off, automatically from an alert or by runbook. The trade-off: small steps are safe but need longer holds to gather enough traffic to be significant.
How to tell it (STAR)
**S:** Our payment allocation module handled about [40,000] payments a day, two other teams were shipping features in it, and every rule change was slow and risky. **T:** I led a refactor to make allocation rules cheap to change without stopping anyone or misallocating a cent. **A:** I built a golden-master test over [10,000] synthetic scenarios, put an interface in front of the module and built the new allocator behind it in small daily PRs on main, pairing with the other teams when their changes overlapped. We shadow-ran both allocators in production; the mismatch metric caught a one-cent rounding difference on split payments, which we fixed before any customer saw it. Then we cut over by flag over [a week]. **R:** Zero allocation incidents during and after cut-over, the legacy code was deleted [two weeks] later, and the next allocation rule took [two days] instead of [two weeks].
Last updated 23 Nov 2026.