Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Evolving a rule set
New links, per customer chains, versions and safe rollout.
The point: in a big system the chain is configuration that people change. Treat it like code: typed, checked, versioned, compared before release.
Build
From names to handlers
A chain built from configuration
1/3Names, not classes
The configuration holds names and a version. It can be stored, shown and compared.
depends onuseshas (lives on)implements
Release
Shadow before you switch
Run the new chain next to the old one on real requests, use only the old answer, and count the differences. A difference is either the purpose of the change or a bug. Shadow links must have no effects.
def vip(r): return "fast lane" if r["vip"] else Nonedef blocked(r): return "refused" if r["blocked"] else Nonedef normal(r): return "queue"def run(chain, r): for link in chain: answer = link(r) if answer is not None: return answer, link.__name__old = [blocked, vip, normal]new = [vip, blocked, normal] # "only a reorder"requests = [{"vip": v, "blocked": b, "id": i} for i, (v, b) in enumerate([(0, 0), (1, 0), (0, 1), (1, 1), (0, 0), (1, 1)])]differences = []for r in requests: live, shadow = run(old, r), run(new, r) if live != shadow: differences.append((r["id"], live, shadow))for d in differences: print(d)print(len(differences), "of", len(requests), "would change")Trade-offs
| Decision | Gives | Costs |
|---|---|---|
| Chain per tenant | Each customer their rules | Support must know which chain ran: store the version |
| One chain with conditions | One thing to test | Links fill up with tenant names |
| Rules as data | Changes without a release | A second programming language with no tests |
| Links as code, order as data | Types and tests for rules, freedom in order | Order still needs validation |
Remove
Deleting a handler safely
- 1
Measure
How many requests did it take in the last month? A count of zero may mean dead, or shadowed by a wide handler in front.
- 2
Shadow
Run the chain without it beside the live one and read the differences.
- 3
Switch by share
Build both chains, choose by a hash of the customer, so that one customer sees one behaviour.
- 4
Remove
Take the name out of the configuration, then the class out of the code. The other way round stops the next start.