AlgoViz

Chain of responsibility

medium 45 min

A 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

ChainConfig+ tenant: String+ version: int+ links: List<String>ChainFactory- known: Map<Name, Link>+ build(config): Chain

1/3Names, not classes

The configuration holds names and a version. It can be stored, shown and compared.

depends onuseshas (lives on)implements

Links without fields per request can be shared by all tenants.

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.

Python
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")
Run it. The new order was meant to be a refactoring. The shadow run shows two requests that changed.
Edit and run it in your browser

Trade-offs

DecisionGivesCosts
Chain per tenantEach customer their rulesSupport must know which chain ran: store the version
One chain with conditionsOne thing to testLinks fill up with tenant names
Rules as dataChanges without a releaseA second programming language with no tests
Links as code, order as dataTypes and tests for rules, freedom in orderOrder still needs validation

Remove

Deleting a handler safely

  1. 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. 2

    Shadow

    Run the chain without it beside the live one and read the differences.

  3. 3

    Switch by share

    Build both chains, choose by a hash of the customer, so that one customer sees one behaviour.

  4. 4

    Remove

    Take the name out of the configuration, then the class out of the code. The other way round stops the next start.