📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You need to refactor the payment allocation module that every invoice flows through, while two other teams keep shipping features in it. Walk me through how you would do it: the plan, the safety nets, how you keep PRs small and how you know it's safe to switch over.

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.

Senior RealWorldScenario Advanced branch-by-abstraction code-quality feature-flags parallel-run refactoring trunk-based-development

🎯 Key points

  • Start with a goal and exit criteria (what change gets easier, measured how), and record the plan and key decisions (e.g. rounding rules) in an ADR
  • Decide refactor in place (same code, better structure, automated refactorings) versus rebuild behind an interface (new implementation compared against the old)
  • Golden-master / characterisation tests from synthetic, production-shaped inputs
  • Branch by abstraction: interface in front of the module, old and new implementations side by side on main, small PRs merged daily
  • Shadow run: execute new allocator alongside old, return old result, count mismatches
  • Monitor the shadow run's own cost: added latency (p95/p99), CPU and errors, with timeouts and sampling
  • Cut over by feature flag in percentages, with instant rollback; delete the old path and flag by an agreed date
  • Coordinate with other teams: CODEOWNERS, a shared mismatch dashboard, pairing on overlapping changes

⏱ 30-second answer

I wouldn't stop the other teams or run a long-lived branch. The plan:

  • Pin behaviour with characterisation (golden-master) tests over thousands of production-shaped, synthetic allocations.
  • Branch by abstraction: put an 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.
  • Shadow run: in production, run the new allocator alongside the old one, return the old result, and count mismatches.
  • Cut over by flag, 1% → 100%, with instant rollback, then delete the old code.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IPaymentAllocator interface 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."


The plan on one page

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

Working alongside other teams

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts with a measurable goal and exit criteria
  • Uses branch by abstraction and trunk-based small PRs
  • Uses golden-master tests and a production shadow comparison
  • Plans flag-based cut-over and old-code deletion
  • Talks about coordinating with the other teams

Red flags

  • Long-lived branch or 'freeze the module for a month'
  • Big-bang switch-over
  • No production comparison for money-handling code

📚 Learn in depth

1. Why not a refactoring branch

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.

2. Branch by abstraction

 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.

3. Golden-master testing

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.

4. Shadow (parallel) run

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).

5. Cut-over and clean-up

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.

Try it yourself

  1. Write a golden-master test for a calculator in your codebase using Verify and 500 generated inputs.
  2. Introduce an interface in front of a module and merge it with no behaviour change.
  3. Implement a shadow decorator that compares two implementations and records a Counter<long> for mismatches.
  4. Configure a percentage feature filter and test that a given customer id always gets the same path.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Starting without a measurable goal. Why it is wrong: the work can't be prioritised against features and never clearly ends. Instead: tie it to a change it enables and a metric (lead time for allocation rules, incident count).
  • Mistake: A long-lived refactoring branch. Why it is wrong: other teams' changes cause constant conflicts and a final big-bang merge. Instead: branch by abstraction on main with small daily PRs.
  • Mistake: Relying on unit tests alone for a critical calculation. Why it is wrong: they encode what developers thought the rules were, not every quirk production depends on. Instead: golden-master tests over a large, varied synthetic set plus a shadow run in production.
  • Mistake: Letting the shadow path write data or publish events. Why it is wrong: duplicate allocations or emails in production. Instead: keep the compared code pure, or point its side effects at a no-op.
  • Mistake: Letting the shadow path fail or slow the request. Why it is wrong: the refactor causes an incident before it's even live. Instead: catch exceptions, apply a timeout and sample under load.
  • Mistake: Logging full payloads on mismatch. Why it is wrong: customer and payment data in logs breaches APP 11 and PCI DSS scope. Instead: log identifiers and store mismatch details in a secured location if needed.
  • Mistake: Never deleting the old implementation. Why it is wrong: two paths to maintain forever, and the next team doesn't know which is real. Instead: agree a deletion date before cut-over.
  • Mistake: Not telling the teams working in the module. Why it is wrong: their changes land in one implementation only and the versions drift. Instead: CODEOWNERS, a shared mismatch dashboard and pairing on overlapping work.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate generalises to planning any large refactoring Why: Checks their general strategy for large refactors without stopping delivery
    How to answer

    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.

  2. When: Candidate mentions golden-master or characterisation tests Why: Checks how they know the tests are good enough to start changing code
    How to answer

    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.

  3. When: Candidate describes a percentage rollout Why: Checks they can decide with data when to go to the next step or roll back
    How to answer

    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.

🛠 Real-world problems: how you handle them

Shadow run catches one-cent split-payment drift before cut-over
Situation
A payment allocation module processed about [40,000] payments a day for [n] business customers. Two other teams added features to it every sprint, and allocation rule changes took [two weeks] and had caused [three] incidents in [year].
Signals
Shadow mismatch counter at [0.4]% of payments in the first week; finance reconciliation dashboard unchanged (old results still used); mismatch logs clustered on payments split across three or more invoices.
Investigation
Grouped mismatches by pattern from the logs and Application Insights custom metrics, replayed sampled cases through both allocators in a test with the golden-master harness, and found the legacy code rounded each split with `MidpointRounding.AwayFromZero` while the new code used banker's rounding.
Resolution
Matched the legacy rounding in the new allocator (agreed with finance as the intended behaviour), added the failing patterns to the golden master, and continued shadowing until mismatches were zero for [a full billing cycle]. Then cut over 1% → 100% over [a week] and deleted the legacy allocator [two weeks] later.
Prevention
Golden-master suite kept as a regression test, an ADR recording the rounding rule, CODEOWNERS on the allocation folder, and the mismatch-dashboard pattern reused for later risky changes.

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].

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me