Chain of responsibility
medium 45 minA 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
| Chain | Worst case per request | Verdict |
|---|---|---|
| 8 checks in memory, assumed 1 microsecond each | 8 microseconds | irrelevant |
| 5 remote calls, assumed 20 milliseconds each | 100 milliseconds | start independent ones together |
| 10,000 rules, assumed 1 microsecond each | 10 milliseconds | index first |
| 10,000 linked handlers in Python | recursion error | use a loop |
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)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