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

Long chains

When linear is too slow, and how to keep the rules.

The point: ten links are free. Ten thousand rules need an index in front, and the chain inside each bucket.

Numbers

What a link costs

ChainWorst case per requestVerdict
8 checks in memory, assumed 1 microsecond each8 microsecondsirrelevant
5 remote calls, assumed 20 milliseconds each100 millisecondsstart independent ones together
10,000 rules, assumed 1 microsecond each10 millisecondsindex first
10,000 linked handlers in Pythonrecursion erroruse a loop
The last row is not a guess. Python's default recursion limit is 1,000 frames.
Python
from collections import defaultdictclass Rule:    def __init__(self, kind, limit):        self.kind, self.limit = kind, limit    def takes(self, req):        return req["kind"] == self.kind and req["amount"] <= self.limitrules = [Rule(f"k{i % 100}", (i // 100 + 1) * 10) for i in range(10_000)]def linear(req):    for asked, r in enumerate(rules, 1):        if r.takes(req):            return r, asked    return None, len(rules)index = defaultdict(list)for r in rules:                    # keeps the order inside each bucket    index[r.kind].append(r)def indexed(req):    bucket = index.get(req["kind"], [])    for asked, r in enumerate(bucket, 1):        if r.takes(req):            return r, asked    return None, len(bucket)req = {"kind": "k42", "amount": 995}a, n = linear(req)b, m = indexed(req)assert a is bprint("linear asked", n, "indexed asked", m)
Run it. The same 10,000 rules: in a row, and behind an index by kind. The number of rules asked is counted.
Edit and run it in your browser

The index is correct only because kind is a condition of every rule, and because the order inside a bucket is the old order. A rule for any kind has to be in every bucket, at its old position.

A firewall has 5,000 rules, first match wins. Lookups are too slow.

BreaksSort the rules by how often they match
How
Popular rules to the front.
Limit
First match wins: if two rules overlap, the answer changes. A block rule may now come after an allow rule.
Choose when
Only for rules that exclude each other.
WorksCache answers by request
How
A map from the exact request to the result.
Limit
Useful only if requests repeat, and every rule change must clear it.
Choose when
Few different requests.
StrongIndex by one field, keep the order inside
How
Buckets by port or kind, rules for any in every bucket.
Limit
More memory, rebuilt on change.
Choose when
Many rules share a condition.

Together

Independent filters at the same time

Filters that only refuse and have no effects can start together. The answer must stay the same as in order: if two refuse, report the first in the list, not the first to answer. Otherwise the message changes from run to run.

Start together, decide in order

50 ms instead of 70 ms, and the same message every time. If A had passed, the refusal of F would count.