Video in progress

You need to switch the pricing algorithm at runtime with a feature flag. How do you design the Strategy and roll it out safely?

Both algorithms implement one interface, and a selector returns the strategy based on the flag on each request. First I run the new algorithm in shadow mode and compare results, then I turn it on by percentage.

📖 Answer

The design part is simple:

public interface PricingStrategy {
    Price calculate(Cart cart);
}

@Component
class PricingSelector {
    private final PricingStrategy legacy;
    private final PricingStrategy v2;
    private final FeatureFlags flags;

    Price calculate(Cart cart) {
        return flags.isOn("pricing-v2", cart.customerId()) ? v2.calculate(cart) : legacy.calculate(cart);
    }
}

The important part is choosing by customerId. If you pick by random percentage, the price jumps when the same shopper refreshes the page. It has to be stable, based on a hash.

A safe rollout is usually three stages:

  1. Shadow. The response comes from legacy, and v2 calculates in parallel beside it, with the difference written to a log or metric. At this stage, if v2 throws, the user must not notice, so wrap it in its own try/catch with a timeout.
  2. Canary. Internal staff first, then 1%, 10%, 50%.
  3. Cleanup. Once you reach 100%, remove legacy and the flag. Forgetting this stage is the most common mistake; three years later the code carries ten dead flags.

Testing: each strategy gets its own unit tests, plus one "golden" test that compares the results of both algorithms on a set of real carts. You agree with the business there on whether the differences are expected.

If a strategy holds state (a cache, a connection), both are created at startup. That costs memory, but it is much safer than creating a bean at runtime.