Most people answer “design DDoS protection” with “put a rate limiter in front of it.” That is the wrong altitude by two orders of magnitude. A rate limiter decides whether one authenticated client is over its 100-requests-per-minute budget; it runs in application code after TLS termination, after the request is a parsed HTTP object. A volumetric DDoS never gets that far. It arrives as 2 Tbps of spoofed-source UDP packets that saturate your transit links before a single byte reaches your application. By the time you could run a rate limiter, the pipe is already full and your real users are getting connection timeouts. The fight happens at the packet, not at the request.
So this is really two systems stitched together. One lives at L3/L4 in the network fast path and absorbs volumetric floods at distributed scrubbing centers, classifying every packet as legitimate or attack in the time it takes to forward it. The other lives at L7 and inspects decrypted HTTP for application-layer attacks (SQL injection, slow-loris, credential stuffing) - that is the WAF. The hard part, the part the whole design bends around, is the first one: how do you keep accurate per-source-IP state across a fleet of scrubbing boxes, at line rate, without a cache miss or a lock, while keeping your false-positive block rate near zero so you do not blackhole your own customers.
Let me do it properly.
Functional Requirements (FR)
In scope:
- Absorb volumetric L3/L4 floods. SYN floods, UDP/DNS/NTP amplification, ACK floods, reflection attacks - up to multi-Tbps aggregate. The platform must soak the flood and forward only clean traffic to the origin.
- Classify per packet in the fast path. For every packet, decide forward / drop / challenge, using per-source-IP rate counters and behavioral anomaly signals, at line rate (tens of millions of packets per second per scrubbing box).
- L7 WAF inspection. On the HTTP traffic that survives scrubbing, run signature and rule-based inspection (OWASP top 10: SQLi, XSS, path traversal), plus application-layer rate rules and bot/credential-stuffing defense.
- Always-on and on-demand modes. Always-on: all customer traffic transits the scrubbing fleet continuously. On-demand: traffic flows direct to origin normally and is rerouted through scrubbing only when an attack is detected (via BGP route injection).
- Challenge, not just block. For ambiguous sources, issue a challenge (SYN cookie, TCP handshake validation, JS/CAPTCHA at L7) rather than a hard drop, so legitimate-but-suspicious clients can prove themselves.
- Negligible false positives. Blocking a real user is a worse outcome than letting some attack traffic leak, so the classifier is tuned to a very low false-positive rate.
Explicitly out of scope (state this to control scope):
- Origin application logic, TLS certificate issuance details, and CDN caching. We terminate and inspect; we do not build the app or the CDN.
- Fine-grained per-customer billing/quota accounting. That is a metering system fed by our logs, not the fast path.
- Full IDS/IPS for internal east-west traffic. We defend the north-south edge in front of customer origins.
- Email/anti-spam and DNS-authoritative hosting. Related products, separate systems.
The one decision that drives everything: classification runs in the forwarding fast path, per packet, at line rate. Every nanosecond and every byte of per-packet state is multiplied by tens of millions of packets per second per box. That single constraint is why we cannot use a hash map of IP to counter (cache misses kill us), cannot take a lock, and cannot ask a remote store. It forces the count-min sketch, the lock-free design, and the two-tier split between a cheap fast path and an expensive slow path.
Non-Functional Requirements (NFR)
- Scale: aggregate attack-absorption capacity in the multi-Tbps range (the largest observed floods are 3-5 Tbps and tens of billions of packets per second). Per scrubbing box: 100 Gbps NIC, ~148 Mpps theoretical line rate at 64-byte packets, realistically tens of Mpps of classification. Global fleet: dozens of scrubbing centers on an anycast network.
- Latency: the fast path adds single-digit microseconds per packet (it is a few memory accesses and arithmetic, nothing else). End-to-end added latency for clean traffic transiting a nearby scrubbing center should be a few milliseconds, dominated by the geographic detour, not by processing.
- Availability: 99.99%+ for the scrubbing service itself. The platform sits in front of customer origins, so if it goes down it takes the customer down. Anycast gives us automatic failover: if a scrubbing center dies, BGP reroutes its traffic to the next-nearest center.
- Consistency: per-IP counters are approximate and eventually-reconciled, not exact. Exact global per-IP counts would need synchronous coordination per packet, which is impossible at line rate. We accept bounded over-counting (count-min sketch only over-estimates, never under) and per-box local state reconciled asynchronously.
- Durability: near zero for counters - they are sub-second sliding state, rebuilt from live traffic in milliseconds after a crash. High durability for attack logs, rules, and customer config (these feed forensics, billing, and the control plane).
Back-of-the-Envelope Estimation (BoE)
Let me ground the fast-path numbers, because they are the whole reason the design looks the way it does.
Line-rate packet budget (the tightest constraint):
100 Gbps NIC, worst case 64-byte packets:
64 bytes = 512 bits, plus 20 bytes inter-packet gap/preamble = 84 bytes on wire
100e9 bits/sec / (84 * 8 bits) ≈ 148.8 Mpps (line rate)
Per-packet time budget at 148.8 Mpps:
1 / 148.8e6 ≈ 6.72 nanoseconds per packet.
A single DRAM access is ~100 ns. An L3 cache hit is ~10-20 ns.
That 6.72 ns per packet is the number that destroys the naive design. One DRAM access is ~100 ns - you cannot afford a single main-memory read per packet. A hash map of 100M source IPs to counters lives in DRAM and will miss cache constantly. The entire per-packet data structure must fit in L3 cache (tens of MB) and be accessed in a handful of cycles. This is the justification for the count-min sketch: a fixed-size array of counters that fits in L3, with no per-key allocation and no pointer chasing.
Counter state sizing (making it fit in L3):
Distinct source IPs in an attack can be tens of millions (botnet + spoofed).
A hash map keyed by IP: 100M entries * (16 byte key + 8 byte counter + overhead)
≈ 100M * ~48 bytes ≈ 4.8 GB -> lives in DRAM, cache-missing constantly. Rejected.
Count-min sketch: fixed d x w array of counters, independent of key count.
d = 4 hash rows, w = 2^20 (≈1M) counters per row, 4-byte counters:
4 * 1,048,576 * 4 bytes = 16 MB -> fits in a 32 MB+ L3 cache. Accepted.
Each packet touches d=4 counters (one per row). 4 L3 hits ≈ 40-80 ns.
Still too slow for 6.72 ns? -> we do not classify every packet with the full
sketch; the fast path samples / batches, and the sketch sits per-core so there
is no cross-core cache-line bouncing. More on this below.
Traffic and QPS:
Baseline legitimate traffic for a large customer: ~500K req/sec, ~5 Gbps.
Under attack: 100x+ on packet count, mostly tiny spoofed packets.
Clean traffic forwarded to origin: ~5 Gbps.
Attack traffic absorbed & dropped at scrubbing edge: up to 2-3 Tbps.
The platform's whole value: forward the 5 Gbps, drop the 2 Tbps,
and do the drop decision in nanoseconds per packet.
Storage (logs, not counters):
Attack events + sampled flow records for forensics/billing:
Sampled 1:1000 flow records during attack, ~1 KB each.
A 2 Tbps attack at avg 500-byte packets ≈ 500 Mpps.
Sampled 1:1000 = 500K records/sec * 1 KB = 500 MB/sec during attack.
A 1-hour attack = ~1.8 TB of forensic data. Written to object storage, tiered.
Counters themselves: never persisted. Rebuilt from live traffic in <1 sec.
Bandwidth / provisioning: the defining capacity number is transit and backbone headroom. To absorb a 3 Tbps flood you must have more than 3 Tbps of ingress capacity spread across your scrubbing centers, or the flood saturates your own links before you can drop a packet. This is why scrubbing is a distributed, anycast, massively over-provisioned network problem first and a software problem second. Memory and CPU are cheap; the scarce resource is link capacity close to the sources.
High-Level Design (HLD)
The platform is an anycast scrubbing network in front of customer origins, plus an L7 WAF tier behind the scrubbers, plus a control plane that configures everything and reacts to detected attacks. Traffic for a protected customer is advertised from every scrubbing center via the same anycast prefix, so the internet routes each source to its nearest center - which spreads a geographically distributed flood across the whole fleet automatically instead of concentrating it on one site.
Internet sources (legit users + botnet + spoofed floods)
│
│ anycast prefix advertised from EVERY scrubbing center via BGP
│ (each source routed to its nearest center = flood auto-distributed)
▼
┌───────────────┬───────────────┬───────────────┐
│ Scrub Center │ Scrub Center │ Scrub Center │ (dozens, global)
│ (anycast) │ (anycast) │ (anycast) │
│ │ │ │
│ ┌─────────┐ │ │ │
│ │ Edge │ │ L3/L4 FAST PATH per box: │
│ │ routers │ │ NIC -> XDP/eBPF or DPDK poll │
│ └────┬────┘ │ - stateless filters (BOGON, │
│ │ │ malformed, bad proto) │
│ ┌────▼────┐ │ - per-core count-min sketch │
│ │ Scrub │ │ (per-source-IP rate) │
│ │ boxes │ │ - behavioral anomaly score │
│ │ (fleet) │ │ - SYN cookie / challenge │
│ └────┬────┘ │ decision: FORWARD/DROP/CHALLENGE
│ │ clean │ │ │
└───────┼───────┴───────────────┴───────────────┘
│ clean traffic only (tunnel/GRE to origin or to L7 tier)
▼
┌─────────────────────────────────────────────┐
│ L7 WAF tier (behind scrubbing) │
│ TLS terminate -> parse HTTP -> rule engine │
│ (SQLi/XSS/traversal sigs, L7 rate rules, │
│ bot scoring, JS/CAPTCHA challenge) │
└───────────────────┬─────────────────────────┘
│ clean HTTP
▼
┌──────────────────┐
│ Customer Origin │
└──────────────────┘
Control plane (out of band, not on the packet path):
┌─────────────────────────────────────────────┐
│ Detection/telemetry aggregator (per-box │
│ sketch summaries, NetFlow/sFlow) -> │
│ Attack detector -> mitigation orchestrator -> │
│ pushes rules/thresholds to all scrub boxes, │
│ triggers BGP reroute for on-demand customers │
└─────────────────────────────────────────────┘
Request/packet flow (the fast path):
- A packet for a protected prefix arrives at the nearest scrubbing center (anycast routing). Edge routers hand it to a scrubbing box.
- The box’s NIC delivers the packet to a poll-mode driver (DPDK) or an in-kernel XDP/eBPF program before the normal network stack - this is the fast path. The packet is processed on the CPU core pinned to that NIC queue (RSS steers packets to cores).
- Stateless pre-filters first (cheapest checks, drop the obvious garbage): bogon/martian source addresses, malformed headers, impossible flag combinations, disallowed protocols/ports for this customer. These drop a large fraction of amplification/reflection traffic with zero per-flow state.
- Stateful per-source classification: the source IP is hashed into the per-core count-min sketch to read and bump its recent packet rate. The behavioral scorer combines that rate with protocol-level signals (SYN-without-ACK ratio, new-vs-established connection mix, entropy of ports/sizes).
- Decision: clearly-legit -> forward; clearly-attack (rate way over threshold, anomaly score high) -> drop; ambiguous -> challenge (reply with a SYN cookie so only a real TCP stack completes the handshake, or pass to L7 for a JS/CAPTCHA challenge).
- Forwarded clean traffic is tunneled (GRE/IP-in-IP or a private backbone) to the L7 WAF tier, which terminates TLS, parses HTTP, runs the rule engine and L7 rate limits, then forwards clean HTTP to the customer origin.
- Out of band, each box streams summarized telemetry (sketch heavy-hitter digests, sampled flows) to the control plane, which detects larger-scale patterns, updates thresholds/rules fleet-wide, and for on-demand customers injects BGP routes to pull traffic into scrubbing when an attack starts.
The key architectural insight is step 2 through 5: the expensive, stateful, per-IP work happens entirely in-core, in L3-resident structures, with no lock and no remote call. Everything global (detecting the attack across the fleet, updating rules) happens out of band in the control plane on summarized data, never on the packet’s critical path.
Component Deep Dive
Four hard parts: (1) the per-source-IP counter in the fast path, (2) behavioral classification without false-positive-ing real users, (3) absorbing SYN floods specifically, and (4) the L7 WAF rule engine. I walk each from naive to scalable.
1. Per-source-IP rate counters in the fast path: hash map -> count-min sketch
This is the core challenge. For every packet we need “how many packets has this source IP sent in the last second,” at line rate, across potentially 100M distinct sources.
Approach A: a hash map of IP -> counter (the naive instinct)
Keep map[uint32]Counter. On each packet, look up the source IP, increment, compare to threshold.
packet -> src_ip -> hashmap[src_ip].count++ -> if count > threshold: drop
Correct and exact. Where it breaks: memory and cache. As the BoE showed, 100M sources is ~5 GB of map - it lives in DRAM, and every lookup is a near-guaranteed cache miss costing ~100 ns, when the budget is ~7 ns. Worse, an attacker using spoofed random source IPs creates a new map entry per packet: unbounded memory growth and allocation on the hot path, which is itself a resource-exhaustion attack against your own classifier. A per-key data structure is exactly what a spoofed-source flood weaponizes against you. Rejected.
Approach B: fixed-size array, single hash (naive bounded version)
Bound memory with one fixed array of W counters; index by hash(ip) % W. No per-key allocation, fits in cache.
idx = hash(src_ip) % W # W = 1,048,576
counters[idx]++ # one array slot per hash bucket
Now memory is fixed (4 MB) and cache-resident. Where it breaks: collisions inflate counts and cause false positives. With 100M sources mapped onto 1M slots, ~100 IPs share each slot. A slot’s count is the sum of all colliding IPs, so one slot can cross the threshold purely because many low-rate legitimate IPs hashed together - and now you drop all of them. A single hash gives you no way to tell a real heavy hitter from an unlucky pile-up of innocents. For a system whose top NFR is “negligible false positives,” that is fatal.
Approach C: count-min sketch (the answer)
Use d independent hash functions into d separate rows of w counters each. To record a packet, increment one counter per row (d increments). To query a source’s count, read one counter per row and take the minimum across rows.
# d = 4 rows, w = 2^20 counters each, 4-byte counters => 16 MB, fits in L3
for r in 0..d-1:
sketch[r][ hash_r(src_ip) % w ] += 1
# query: minimum over rows cancels most collision noise
est = min( sketch[r][hash_r(src_ip) % w ] for r in 0..d-1 )
if est > threshold: drop
Why the minimum works: a collision can only ever make a counter too high (another IP added to it), never too low. For an innocent IP to be falsely flagged, it would have to collide with a heavy hitter in all d rows simultaneously, and because the d hashes are independent, that probability is tiny (it falls off geometrically in d). So the sketch over-estimates but never under-estimates, and the over-estimate is bounded: with w counters and d rows, the error is within a small epsilon of the true count with high probability. This is exactly the trade we want - we would rather occasionally over-count an attacker (and challenge them) than ever under-count, and we drive the false-positive-on-an-innocent probability down by adding rows.
Three production details that make it actually work at line rate:
- Fits in L3, lives per-core. 16 MB sits in a modern 32-64 MB L3. Critically, each CPU core gets its own sketch so there is no cross-core cache-line contention and no atomic/lock on the increment - the single biggest fast-path killer is cores fighting over the same cache line. Because RSS steers a given flow consistently to one core, a source’s packets mostly land on the same core’s sketch anyway. The control plane merges per-core sketches (count-min sketches are additive: sum them elementwise) out of band to get the box-wide and fleet-wide view.
- Sliding window via decay. A raw count grows forever. We need “rate in the last second,” so we age the sketch: either keep two sketches and ping-pong (reset the stale one each epoch, query the sum) or periodically halve all counters (exponential decay). Ping-ponging two sketches gives a clean sliding window; the reset is a cheap
memsetdone off the hot path. - Heavy-hitter extraction for the control plane. The sketch tells you a given IP’s rate but not “who are the top attackers.” Pair it with a small top-K structure (a Space-Saving / heap of the current heaviest sources) so the control plane can list offenders for logging, blocklisting, and operator dashboards without scanning 100M IPs.
Why not a Bloom filter?
A Bloom filter answers “have I seen this IP,” not “how many packets” - it has no count. Count-min is the counting generalization. We use a Bloom-style filter elsewhere (e.g. a known-bad-IP reputation set membership check) but the rate decision needs counts, so count-min is the tool.
2. Behavioral classification without nuking real users
A pure rate threshold is blunt: a legitimate NAT gateway or a popular mobile carrier egress can send a huge legitimate packet rate from one IP, while a stealthy low-and-slow attack stays under any per-IP rate. Rate alone both false-positives the NAT and false-negatives the slow attacker.
Naive: single global rate threshold
“Drop any IP over N packets/sec.” Where it breaks: N is impossible to set. Low enough to catch a distributed botnet (each bot sends little) and you block every corporate NAT and mobile carrier. High enough to spare them and a focused attacker walks under it. One scalar cannot separate these populations.
Better: multi-signal anomaly scoring with per-customer baselines
Combine several cheap, fast-path-computable signals into a score, and compare against a learned baseline for this customer rather than a global constant:
- Per-IP rate from the count-min sketch (the magnitude signal).
- Protocol behavior ratios: SYN:ACK ratio (SYN flood gives SYNs with no completing ACKs), new-connection:established ratio, retransmit patterns.
- Entropy signals: a legitimate traffic mix has a characteristic distribution of source ports, packet sizes, TTLs. A reflection/amplification flood has abnormally low entropy (all packets look alike) or abnormally high (fully randomized spoofing). We maintain cheap running entropy estimates per customer prefix.
- Reputation: membership check against a known-bad-IP set (Bloom filter / reputation feed) and whether the source completed a challenge recently.
Each signal is normalized against the customer’s rolling baseline (learned in the control plane from quiet-period traffic and pushed to the boxes as thresholds), scored, and combined. The decision is tiered, which is what protects false positives:
score low -> FORWARD (do nothing, this is normal traffic)
score medium / ambiguous -> CHALLENGE (SYN cookie, or L7 JS/CAPTCHA)
score high AND rate high -> DROP
The crucial design choice for the “negligible false positive” NFR: ambiguous traffic is challenged, never dropped. A real client transparently passes a SYN cookie or solves a JS challenge and is let through; a spoofed source or dumb bot cannot. We only hard-drop when multiple independent signals agree, so the probability of dropping a real user requires several independent anomaly signals to simultaneously misfire. Hard blocks are the last resort, not the first.
The baselines are learned off the hot path: the control plane ingests summarized telemetry during normal periods, computes per-customer normal ranges (rate, entropy, protocol ratios), and pushes compact threshold tables to every box. The fast path only ever does cheap arithmetic against those pushed numbers - no model inference per packet.
3. SYN floods specifically: stateful tracking -> stateless SYN cookies
A SYN flood sends TCP SYNs (often spoofed source) and never completes the handshake, exhausting the server’s half-open connection table.
Naive: track every half-open connection
Keep a connection state table; on SYN, allocate an entry; expire if no ACK. Where it breaks: the whole point of a SYN flood is to make you allocate state per spoofed SYN. Tracking half-opens means the attacker controls your memory - a classic state-exhaustion attack against the defender. The box falls over before the origin does.
Better: SYN cookies (stateless handshake validation)
Do not store half-open state at all. When a SYN arrives, reply with a SYN-ACK whose sequence number is a cryptographic cookie encoding the connection parameters (a hash of the 4-tuple + a secret + a coarse timestamp). Keep zero state. If a real client responds with the final ACK, its acknowledgment number echoes cookie+1; we recompute the cookie from the tuple and verify it - only then do we create real connection state (or complete the splice to the origin). A spoofed source never sends the ACK (it never saw the SYN-ACK, or does not exist), so it costs us nothing.
SYN in -> cookie = HMAC(secret, src_ip,src_port,dst_ip,dst_port, t)[truncated]
-> reply SYN-ACK with seq = cookie, store NOTHING
ACK in -> expected = HMAC(secret, 4-tuple, t_recent)
-> if ack_num-1 == expected (for a recent t): real client, proceed
else: drop, no state ever allocated
This flips the economics: the attacker must complete a full handshake from a real, routable, non-spoofed address to cost us anything, which also de-anonymizes them and lets rate limiting and reputation kick in. Combined with the count-min rate counter (so even real-sourced completions get rate-limited), SYN floods become cheap to absorb.
4. The L7 WAF rule engine: regex-per-rule -> staged compiled matching
Behind scrubbing, the WAF inspects decrypted HTTP for application attacks.
Naive: run every regex rule against every request
Load the OWASP CRS (hundreds of regex rules) and evaluate each against each request field. Where it breaks: hundreds of independent regex passes over every header, URI, and body is enormous CPU per request; a backtracking-prone regex on attacker-controlled input is itself a ReDoS vector (the WAF becomes the DoS). Throughput collapses and the WAF becomes the bottleneck it was meant to prevent.
Better: staged, pre-filtered, compiled matching
- Cheap pre-filter first. Most requests are benign. Run a fast multi-pattern literal scan (Aho-Corasick / Hyperscan) for the suspicious tokens that any real attack must contain (
union select,<script,../,/etc/passwd). Only requests that hit the pre-filter proceed to the expensive, precise rule evaluation. This is the same “cheap stateless filter before expensive stateful work” shape as the L3 fast path. - Compiled, non-backtracking regex. Use a DFA-based engine (RE2/Hyperscan) that guarantees linear time and no catastrophic backtracking, so attacker input cannot blow up matching time. Reject PCRE features that enable ReDoS.
- Request normalization before matching. Decode URL-encoding, unicode, nested encodings, and comments before matching, so
UN/**/ION SE/**/LECTand%55niondo not slip past. Evasion is mostly about encoding tricks; normalize once, match once. - Scoring, not single-rule blocking (anomaly scoring mode). Instead of “any one rule blocks,” sum rule weights and block over a threshold, which cuts false positives from a single overeager rule. Same philosophy as the L3 tiered decision.
- L7 rate + bot defense. On surviving traffic, apply per-identity application-layer rate limits (a token-bucket rate limiter - the companion system) and bot scoring (JA3/TLS fingerprint, header-order heuristics, behavioral challenge) to stop credential stuffing and scraping that are “valid” HTTP but abusive.
API Design & Data Schema
The data path has no client-facing API (it is transparent inline interception). The APIs are the control plane for customers and operators, plus the internal telemetry and rule-push interfaces.
Customer / operator control-plane API
# Onboard a protected prefix / origin
POST /v1/protected-assets
Body: {
"customer_id": "cust_123",
"mode": "always_on", # always_on | on_demand
"origin": { "ip": "203.0.113.10", "tunnel": "gre" },
"prefixes": ["198.51.100.0/24"],
"l7": { "tls_terminate": true, "waf_mode": "block" } # block | detect
}
Response 201: { "asset_id": "asset_abc", "anycast_vips": ["192.0.2.5"] }
# Tune mitigation policy (pushed to the fleet)
PUT /v1/assets/{asset_id}/policy
Body: {
"l3": {
"protocols_allowed": ["tcp/443","tcp/80","udp/443"],
"syn_cookie": true,
"rate_sensitivity": "medium", # maps to sketch thresholds
"on_ambiguous": "challenge" # challenge | drop
},
"l7": {
"ruleset": "owasp-crs-4",
"action": "score", # score | block_any
"block_threshold": 12,
"rate_rules": [{ "key_by":"ip", "limit":"100/min", "path":"/login" }]
}
}
Response 200: { "version": 42, "propagating_to_boxes": 180 }
# Realtime attack status (read from telemetry aggregator)
GET /v1/assets/{asset_id}/attacks?active=true
Response 200: {
"active": true,
"vector": "udp_amplification",
"peak_bps": 2_400_000_000_000,
"peak_pps": 480_000_000,
"dropped_pct": 99.7,
"top_sources": ["x.x.x.x", "..."],
"started_at": "2026-12-01T10:03:11Z"
}
# On-demand: trigger reroute (also auto-triggered by detector)
POST /v1/assets/{asset_id}/mitigation:start -> injects BGP, pulls traffic in
POST /v1/assets/{asset_id}/mitigation:stop -> withdraws, traffic goes direct
Internal rule-push and telemetry
# Control plane -> every scrub box (compact, hot-reloaded, versioned)
PushPolicy(box_id, asset_id, compiled_thresholds, version)
# compiled_thresholds = per-customer sketch thresholds, entropy baselines,
# allowed protocol bitmaps, challenge flags. Boxes apply atomically.
# Box -> telemetry aggregator (summaries only, NOT per packet)
ReportTelemetry(box_id, epoch, {
merged_sketch_digest, # heavy-hitter digest, not the full 16MB
top_k_sources, # Space-Saving top offenders
per_customer: { pps, bps, syn_ack_ratio, entropy, drop_count },
sampled_flows # 1:1000 sampled, for forensics
})
Data stores and why
| Data | Store | Why |
|---|---|---|
| Per-IP rate counters (fast path) | In-core count-min sketch (L3 RAM) | Fixed-size, lock-free, nanosecond access, throwaway. Not a database at all. |
| Customer/asset config & policy | Strongly-consistent KV (etcd/Spanner-like) | Small, read-heavy, must be consistent across the fleet; a stale “allow all” rule is dangerous. |
| Known-bad-IP reputation set | In-memory Bloom filter per box, refreshed from feed | Membership-only, huge set, probabilistic-OK, must be cache-fast. |
| Attack events & dashboards | Time-series DB (per-customer metrics) | High write rate, time-range queries, downsampled retention. |
| Sampled flow records / forensics | Object storage (S3-like), tiered | Large, write-once, read-rarely, cheap cold storage. |
| WAF rules / signatures | Versioned config store -> compiled to DFA on boxes | Changes rarely, compiled artifact pushed to the fleet. |
SQL vs NoSQL / in-memory: the fast-path counter is deliberately not a database - it is an in-memory probabilistic structure because the access pattern (nanosecond, lock-free, approximate, throwaway) matches nothing a disk-backed store can do. Config and policy use a strongly consistent small KV store because correctness of rules matters and volume is trivial. Telemetry uses a time-series DB (append-heavy, time-range reads). Forensics uses object storage (big, cold, cheap). Each store is chosen by access pattern, not by a blanket “we use Postgres.”
Schema sketch (policy KV, the one that must be consistent):
asset_id STRING PK
customer_id STRING
mode ENUM (always_on | on_demand)
anycast_vips LIST<IP>
origin_tunnel JSON (ip, encap type)
l3_policy JSON (allowed protocol bitmap, syn_cookie,
rate thresholds, on_ambiguous action)
l7_policy JSON (ruleset id, action, block_threshold, rate_rules)
baselines JSON (learned per-customer normal ranges)
version INT (monotonic; boxes apply higher versions atomically)
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Transit/link saturation (breaks first, before any software). A 3 Tbps flood fills your ingress pipes before a CPU sees a packet. Fix: anycast the protected prefix from every scrubbing center so the flood is geographically split across the whole fleet (each source hits its nearest center), and massively over-provision backbone/transit capacity. This is the primary scaling lever and it is a network-capacity decision, not a code one. Partner peering and large transit commits are the real defense against volume.
2. Per-packet DRAM access / cache miss (the software breaker). Any per-flow structure in main memory cache-misses at ~100 ns against a ~7 ns budget. Fix: count-min sketch sized to fit in L3 (16 MB), one per core to avoid cross-core cache-line contention and locks. All global state (detecting the fleet-wide attack) is computed out of band on summarized sketches, never on the packet path. Stateless pre-filters drop the bulk of garbage before the sketch is even touched.
3. Lock contention / cross-core bouncing. Shared counters mean cores fight over cache lines and atomics, collapsing throughput. Fix: share-nothing per-core design. RSS steers a flow to a fixed core; that core owns its sketch, its connection state, its decisions. Merge happens off-path. No lock on the hot path, period.
4. Spoofed-source state exhaustion (attack against the defender). SYN floods and random-spoof floods try to make you allocate per-source state. Fix: stateless SYN cookies (no half-open table) and the fixed-size sketch (no per-IP allocation). The defender’s memory is bounded and independent of attacker creativity - the whole fast path uses O(1) memory regardless of source cardinality.
5. Hot shard / hot customer under focused attack. One targeted customer’s prefix concentrates a flood. Fix: anycast already spreads it across centers; within a center, ECMP / RSS spreads it across boxes and cores. For a single enormous target, scale horizontally by adding boxes advertising the same anycast VIP (ECMP across boxes). The sketch’s additive merge means more boxes do not hurt accuracy - partial counts sum correctly in the control plane.
6. False positives (the reputational SPOF). Dropping real users is worse than leaking some attack traffic. Fix: the tiered decision (forward / challenge / drop), hard-drop only on multi-signal agreement, count-min’s one-sided error (over-count never under-count) feeding a challenge not a block, per-customer learned baselines instead of global thresholds, and a “detect-only” mode to shadow-test new rules before enforcing. SYN cookies and JS challenges let real clients self-clear.
7. Control-plane lag reacting to a new attack. If detection and rule-push are slow, the first seconds of a novel vector leak. Fix: the fast path has autonomous local defaults (stateless filters, per-IP sketch thresholds, SYN cookies) that mitigate immediately without waiting for the control plane; the control plane then tunes thresholds and pushes targeted rules within seconds. Detection runs on streaming summaries, not batch, to keep reaction time low. On-demand customers pay a reroute delay (BGP convergence, tens of seconds), which is the argument for always-on for high-value targets.
8. L7 WAF CPU and ReDoS. Hundreds of backtracking regexes per request melts the WAF. Fix: cheap literal pre-filter (Aho-Corasick/Hyperscan) before precise rules, DFA engines (RE2) that cannot backtrack, normalize-then-match once, and anomaly scoring instead of per-rule blocking. Scale the WAF tier horizontally behind the scrubbers since it only sees already-cleaned traffic.
9. Asymmetric routing / return path. Clean traffic must get back to the client correctly through the tunnel. Fix: forward clean traffic to origin over a stable tunnel (GRE/IP-in-IP or private backbone) and either return via the same scrubbing path (symmetric, for full inspection) or direct-from-origin (asymmetric, lower latency) depending on whether you need to inspect responses. State the trade: symmetric return gives full visibility at the cost of a longer return path.
Wrap-Up
The trade-offs that define this design:
- Approximate per-IP counting over exact. We use a count-min sketch that fits in L3 instead of an exact hash map, accepting bounded one-sided over-counting in exchange for lock-free nanosecond access with memory independent of source cardinality. The error is one-sided by design (never under-count an attacker) and feeds a challenge, not a hard drop, so the approximation never costs a real user.
- Share-nothing fast path over coordinated global state. Each core owns its sketch and decisions; everything global happens out of band on summarized data. We give up a real-time exact fleet-wide view to get line-rate, lock-free per-packet classification.
- Challenge over block for anything ambiguous. Because a false positive (blocking a real user) is worse than a false negative (leaking some attack traffic), we hard-drop only when multiple independent signals agree and challenge everything in between. SYN cookies and JS challenges let real clients prove themselves at near-zero cost.
- Stateless where the attacker wants us stateful. SYN cookies and fixed-size sketches deny the attacker the ability to exhaust our memory, flipping the economics so that costing us anything requires a real, routable, rate-limitable source.
- Network capacity first, software second. The first and biggest defense against a multi-Tbps flood is anycast distribution plus massively over-provisioned transit; the clever data structures only matter once the packets actually reach a CPU.
One-line summary: an anycast scrubbing fleet that absorbs volumetric floods by classifying every packet in a share-nothing, L3-cache-resident fast path - stateless pre-filters, a per-core count-min sketch for per-source-IP rate, multi-signal anomaly scoring, and stateless SYN cookies - hard-dropping only on multi-signal agreement and challenging everything ambiguous, with an L7 WAF tier and an out-of-band control plane doing all the global detection and rule-tuning off the packet path.
Comments