Strategy is the design pattern most engineers already use correctly by accident. Every time you pass key= to sorted, hand a Comparator to a Java collection, or register a Passport.js login method, you are using Strategy. The algorithm sits behind an interface, the caller picks one, and the code that runs it does not care which.
That is why the textbook version feels almost too simple to write about. A family of interchangeable algorithms, a context that holds one, a method that delegates. In Python it is a dictionary of functions. Nobody's production incident starts with "the dictionary lookup failed."
But plenty of incidents start with "we switched the strategy." A new sort order that reshuffled tied rows on a paginated page. A load-balancing change that invalidated every cache in the fleet. A config typo that quietly fell back to the default for three weeks. A pricing change that landed halfway through a checkout. My claim in this issue: the algorithms are the easy part of Strategy. The hard part is the swap, and the swap has four places it breaks. The interchangeability contract, the selector, the timing of the switch, and visibility into which strategy actually ran.
The pattern in one paragraph
Refactoring Guru defines Strategy as a pattern that "lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable." The context object holds a reference to one strategy and delegates to it. The point is that the context "isn't responsible for selecting an appropriate algorithm for the job". Someone else picks, and the context just runs whatever it was given. That is how you add a new algorithm without editing the code that uses it, which is the Open/Closed Principle in its most practical form.
The same page makes the point that matters for modern code: languages with functional support let you write each algorithm as an anonymous function and use them "exactly as you'd have used the strategy objects, but without bloating your code with extra classes and interfaces." So here is Strategy without a single class, in Python:
def flat_rate(order): return 5.00
def by_weight(order): return round(1.20 * order["kg"], 2)
def free_over_50(order): return 0.0 if order["total"] >= 50 else 5.00
SHIPPING = {"flat": flat_rate, "weight": by_weight, "free_over_50": free_over_50}
def shipping_cost(order, strategy_name):
return SHIPPING[strategy_name](order)
Every snippet in this issue was run locally on Python 3.12, and the outputs quoted are real. For an order of 3.5 kg totalling 42.00, the three strategies return 5.0, 4.2 and 5.0. Adding a fourth shipping rule is one function and one dictionary entry. shipping_cost never changes.
That is the pattern. It is also where most explanations stop, which is a shame, because nothing above can fail in an interesting way yet.
Where you already run Strategy in production
Before breaking it, it helps to see how big the pattern gets once it leaves the tutorial.
The AWS SDKs ship retry behavior as a strategy. The retry behavior reference lists three modes, standard, adaptive and legacy, selected with retry_mode in ~/.aws/config or the AWS_RETRY_MODE environment variable, and resolved in a fixed order: explicit client code, then the environment, then the shared config file, then the SDK default. Standard mode does exponential backoff with jitter plus a retry quota. Adaptive mode "includes everything in standard mode, plus a client-side rate limiter." Same interface for every API call, different algorithm behind it.
Envoy ships load balancing as a strategy. Its supported load balancers page lists weighted round robin, client-side weighted round robin, weighted least request, ring hash, Maglev and random. One cluster config field picks the algorithm. The proxy code that forwards the request does not change.
Passport.js is almost a textbook diagram of the pattern. Its strategies guide has you install a strategy package, register it with passport.use(strategy) (optionally under a name, as in passport.use('password', strategy)), and select it per route with passport.authenticate('local', ...). Each strategy wraps a verify function you write, with a strict contract: cb(null, user) for success, cb(null, false) for a failed login, and cb(err) only "when the server is operating abnormally."
Notice that in all three, the strategy objects themselves are not the interesting engineering. The interesting engineering is the contract (Passport's three outcomes), the selection rules (the AWS precedence chain), and the documented caveats about what changes when you switch. Those are the four breaks.
Break 1: same signature, different contract
The type checker can verify that two strategies take the same arguments and return the same type. It cannot verify that they are actually interchangeable. Interchangeable means the caller cannot tell them apart in any way it depends on, and callers depend on far more than the signature.
Sorting is the cleanest example. Python's sorting HOWTO promises that "sorts are guaranteed to be stable," meaning records with equal keys keep their original order. Now imagine someone adds a heap-based sort strategy for a large-data path. Same signature: (items, key) -> list. Same set of output elements. Here are four orders sorted by amount, where three tie at 30:
orders = [("o1", "2026-11-20", 30), ("o2", "2026-11-21", 30),
("o3", "2026-11-22", 10), ("o4", "2026-11-22", 30)]
stable(orders, key=lambda o: o[2]) # ['o3', 'o1', 'o2', 'o4']
heap_sort(orders, key=lambda o: o[2]) # ['o3', 'o4', 'o2', 'o1']
Both outputs are "correctly sorted by amount." Only one preserves the date order that the rows arrived in. If an upstream query sorted by date first and relied on stability to make amount the primary key and date the tiebreaker, the swap silently broke the report. If the result feeds a paginated API, ties can shuffle between pages, so a user sees o1 twice and o4 never.
The same thing happens at infrastructure scale. The AWS retry reference says adaptive mode "can delay or block the initial request, not just retries, when throttling is detected," and that its limiter "operates per SDK client instance," shared across every operation and resource that client touches. That is why the docs say adaptive "is not recommended as a general default" and to avoid it when "your client sends requests to multiple resources or serves multiple tenants." Standard and adaptive have the same interface. They do not have the same latency contract. Swap one for the other in a multi-tenant service and a single noisy tenant's throttling can start delaying first attempts for everyone sharing that client.
The fix is to write the contract down and test it against every strategy, not just the one you are adding. A shared test suite parameterized over the registry: stability, idempotence, error types, worst-case latency, side effects. If a new strategy cannot pass it, it is not a strategy in this family. It is a different feature wearing the same interface.
Break 2: the selector that guesses
In real code, the strategy name comes from somewhere outside the code: a config file, a feature flag, a tenant setting, a request header. That makes the lookup the one place where untrusted, typo-prone input meets your algorithm table. And the most common way to write it is the most dangerous:
strategy = SHIPPING.get(config["shipping"], flat_rate) # "safe" default
Someone deploys shipping: free-over-50 with hyphens instead of underscores. Nothing errors. Every order gets flat rate. The marketing team's free shipping promotion runs for three weeks without shipping anything for free, and the only signal is a conversion graph that never moved.
The selector should fail loudly at the earliest moment it can:
def shipping_cost(order, strategy_name):
try:
strategy = SHIPPING[strategy_name]
except KeyError:
raise ValueError(f"unknown shipping strategy {strategy_name!r}; "
f"known: {sorted(SHIPPING)}")
return strategy(order)
With the typo, this now says unknown shipping strategy 'free-over-50'; known: ['flat', 'free_over_50', 'weight']. Better still, validate the name when the configuration loads, not when the first order arrives. Startup is the cheapest time to crash.
Envoy's docs carry a subtler version of this problem. Ring hash and Maglev are both described as "only effective when protocol routing is used that specifies a value to hash on." In other words, the strategy has a precondition that lives somewhere else in the config (a hash policy on the route). Select ring hash without one and you have not selected the behavior you wanted, even though the config is valid. When a strategy has preconditions, the selector is the right place to check them, because it is the one piece of code that knows which strategy was chosen and can see the rest of the configuration.
The AWS precedence chain is the other half of selector design. When the same choice can come from code, the environment and a file, someone will eventually set it in two places and get the one they did not expect. Documenting the order, as the SDKs do, is the minimum. Logging the winning source is better.
Break 3: the swap that lands mid-operation
"Swapping algorithms at runtime" is in the title of every Strategy tutorial, and almost none of them ask the obvious question: what happens to the operation that is already running when the swap occurs?
Here is a pricing context that swaps from regular pricing to a 30 percent Black Friday discount while a ten-item cart is being totalled:
class Pricing:
def __init__(self, strategy): self.strategy = strategy
def swap(self, strategy): self.strategy = strategy
def total_racy(self, cart):
return sum(self.strategy(p) for p in cart) # re-reads per line
def total_snapshot(self, cart):
strategy = self.strategy # read once
return sum(strategy(p) for p in cart)
With ten items at 100.00 and the swap landing halfway through, total_racy returns 850.0. The correct answers were 1000.0 (regular) or 700.0 (discounted). 850 is a price that no strategy ever produced. Nothing crashed and the reference assignment was atomic, yet the result is wrong, because the operation observed two strategies. total_snapshot returns 1000.0: the swap applies to the next cart, not the current one.
The rule is simple. Bind the strategy once per unit of work (a request, a cart, a batch, a page of results) and pass it down. Never re-read the shared reference inside the loop.
There is a second, harder version of this break: strategies whose output is persisted or cached, so the old strategy's decisions are still out there after the swap. Changing a hashing strategy is the classic case. I routed 100,000 keys across four nodes, added a fifth, and counted how many keys changed owner:
modulo: 80.1% keys moved
ring: 22.1% keys moved
With hash(key) % len(nodes), going from four to five nodes moves about four out of five keys, so four out of five cache lookups miss right after the change. A consistent-hash ring with 100 virtual nodes per server moves about one in five, close to the ideal. That is the property Envoy documents for ring hash: adding or removing one host out of N "will affect only 1/N requests." Swapping from modulo to ring hash is also a strategy change, and the swap itself moves most keys. That is a one-time migration, and it needs a plan. Warm the new layout, or dual-read for a while, or accept the miss storm on purpose at a quiet hour. Treating it like a config tweak is how you take down the database behind the cache.
Break 4: the choice nobody can see
When behavior depends on a runtime choice, every bug report has a silent first question: which strategy was running? If your logs cannot answer that, debugging starts with guesswork.
Three habits fix this cheaply. Give every strategy a stable name (the registry key, not the function's repr) and attach it to the log line or trace span of every operation that used it. Emit a metric dimension for it, so a latency regression after a swap shows up as two lines on a graph instead of one wobbly one. And log the selection itself once at startup or on change, including where the choice came from: "retry_mode=adaptive (source: AWS_RETRY_MODE)". The AWS precedence chain is a good reason this matters, since the same name can come from four places.
This sounds like plumbing. It is the difference between "p99 went up last Tuesday" and "p99 went up for the 4 percent of tenants on the adaptive retry strategy since the flag flipped Tuesday at 14:02."
Yes, but: isn't this just an if statement?
The strongest objection to Strategy is that most code needs two branches, and two branches are an if. A ShippingStrategy interface with one implementation and a speculative second one is ceremony, and Refactoring Guru itself lists "overcomplicating the program" when you only have a couple of algorithms that rarely change.
That objection is right, and it is right more often than pattern enthusiasts admit. If the variants are few, stable, and chosen in code by the developer, write the conditional. You can extract the strategy later in ten minutes.
The line moves when the choice leaves the code. When the algorithm is picked by configuration, by tenant, by experiment, or by an operator during an incident, you need a registry, a validated selector, a binding point per unit of work, and a name in the logs, whether or not you call it Strategy. At that point the if statement has the same four breaks, just spread across the codebase where you cannot test them in one place. The pattern is worth it not because of the polymorphism, but because it gives the swap a single home.
Monday morning
Find the places in your code where behavior is chosen at runtime: a feature flag that changes an algorithm, a per-tenant setting, a config field like retry_mode or lb_policy, a plugin registry. For each one, ask four questions. Is there a written contract that every option passes in one shared test suite? Does an unknown or misconfigured choice fail at startup, or fall back silently? Is the choice bound once per request or batch, or re-read mid-operation? Can you tell from a single log line which option ran?
Each "no" is a small fix and a likely future incident. The function behind the interface is the easy part. Make the swap boring.

