Low-Latency IP Blocklist Service
Medium · System Design · Software Engineer · Onsite
Prompt
Architect the backend service and API layer for a network IP blocklist platform used to filter malicious traffic across an organization's infrastructure.
Security engineers and automated threat-mitigation pipelines rely on this platform to register, modify, remove, and inspect rules covering both individual IP addresses (such as 203.0.113.45) and CIDR subnet prefixes (such as 203.0.113.0/24 or IPv6 /48 blocks, optionally carving out safe exceptions like 203.0.113.12/32). At the same time, edge firewall proxies and internal application microservices query the platform at heavy request volume to determine in real time whether an inbound client connection should be rejected or permitted.
Place particular emphasis on how rules and verdicts are cached, queried, and kept fresh across the system.
Scope & Expectations
- API contracts: Control-plane endpoints for creating, updating, deleting, and searching IP/CIDR rules (supporting both single mutations and bulk threat-feed syncs), paired with a high-throughput check interface for evaluating client IPs.
- Address & range representation: Persistent schemas and in-memory lookup structures capable of indexing exact IPv4/IPv6 addresses alongside variable-length, potentially overlapping CIDR prefixes.
- Low-latency read path & invalidation: Multi-layer caching topology, memory footprint, and change-propagation mechanics that keep verdict lookups fast while bounding staleness whenever blocklist rules change.
- Production operations: Consistency semantics, horizontal scaling under traffic or attack spikes, graceful degradation when dependencies fail, and operational telemetry.
Step-by-step walkthrough
Clarify requirements and system boundaries
An IP blocklist platform answers a deceptively simple question — "Should we reject this inbound IP address?" — for both single addresses (like
203.0.113.45) and CIDR ranges (Classless Inter-Domain Routing blocks like203.0.113.0/24, which means all 256 IPv4 addresses that share the first 24 bits, from203.0.113.0to203.0.113.255).The requirements pull in two opposite directions: security engineers and threat-mitigation pipelines need a write path that is strict, validated, and fully audited, while edge proxies and backend microservices need a read path that answers in microseconds to milliseconds and stays up even if the database crashes. Calling this tension out right away justifies splitting the architecture into a control plane (rule management, validation, audit history) and a data plane (ultra-fast checks that never query the database).
Functional requirements
- Create, update, delete, and inspect blocklist rules for exact addresses and CIDR prefixes across both IPv4 (32-bit) and IPv6 (128-bit).
- Support two actions on a rule:
block, orallowto carve out safe exceptions inside a blocked subnet (for example, "block203.0.113.0/24, except allow partner webhook203.0.113.12/32"). - Attach metadata to every rule:
source(admin,abuse_detector,feed:<name>), human-readablereason, and an optional expiration timestamp (expires_at). - High-throughput check endpoint: "Is this IP blocked, and which rule matched?" for single IPs and batches.
- Admin queries: find all rules containing an IP, all rules overlapping a CIDR block, all rules owned by a feed, and the full change history of any prefix.
Non-functional requirements
- Latency: ~1 microsecond (
1 us) for in-process gateway checks; p99 under2 msfor remote checks inside the same availability zone (AZ). - Throughput: ~1.3 million checks/s globally at peak, versus ~50 writes/s steady state and bursts of ~1,000 writes/s during attacks.
- Availability:
99.99%for checks (must keep working if the database, control API, or another region goes down) and99.9%for rule writes. - Propagation bound: every block or unblock reaches all checkers within
5 sat p99. - Durability and audit: zero lost acknowledged writes, with a tamper-evident audit log.
Clarifying assumptions
- Overlapping rules: Longest-prefix match wins — when multiple prefixes cover an IP, the rule with the largest
/Nprefix length decides the verdict, whetherblockorallow. Each exact prefix(cidr)has at most one rule. - Responsibility: The service returns verdicts (
blocked: true/false); callers enforce them (drop packet, HTTP 403, or CAPTCHA). - Outage behavior: Callers default to fail open using their last known cached verdict, falling back to
allowif none exists. Failing closed would turn a blocklist-service hiccup into a total company outage. - Rule lifetimes: Admin rules may be permanent (
expires_at = null), whereas automated detector and threat-feed rules must carry an expiry (default 24 hours, max 30 days) so recycled residential or cloud IPs do not stay blocked forever.
Back-of-the-envelope numbers
Write down explicit assumptions first, then let the arithmetic dictate the caching architecture.
Rule set size (steady state) Exact IPv4 addresses (/32, mostly threat feeds) 5,000,000 IPv4 CIDR ranges (e.g., /16 to /30) 300,000 IPv6 prefixes (mostly /48 and /64) 200,000 Allow exceptions 20,000 Total active rules ~5,520,000 Write traffic Steady state ~50 changes/s Automated detector burst during DDoS ~1,000 changes/s Threat-feed syncs batches of up to 10,000 ops, a few per hour Read (check) traffic at peak Firewall gateways: 400 instances x 2,500/s 1,000,000 checks/s Application services: 3,000 instances total 300,000 checks/s Global peak 1,300,000 checks/s (busiest region: 50%) RAM for one full in-memory copy of all 5.52M rules (open-addressing hash tables at 70% load) Exact IPv4: 4 B key + 8 B expiry + 4 B meta = 16 B -> 5M x 16 / 0.7 ~115 MB IPv4 CIDRs: ~32 B/entry -> 300k x 32 / 0.7 ~14 MB IPv6 prefixes: 16 B key + 8 B expiry + 8 B meta = 32 B -> 200k x 32/0.7 ~9 MB Per-/24 "finer rule" counters (~2M distinct /24s x 8 B / 0.7) ~23 MB Total per replica ~161 MB (budget 250 MB) Replication bandwidth Full snapshot (~20 B/rule raw) ~110 MB raw, ~50 MB compressed Single change event ~64 B Burst stream per subscriber (1,000/s x 64 B) 64 KB/s Busiest region subscribers (200 gateways + 6 check nodes = 206) -> 206 x 64 KB/s = ~13 MB/s Regional check service sizing (busiest region = 150,000 app checks/s) After 70% hit rate in app SDK cache 45,000 RPCs/s One 4-vCPU gRPC check node capacity ~25,000 RPCs/s Deployment: 2 nodes x 3 AZs = 6 nodes 150,000 RPCs/s capacity (100,000/s if 1 AZ dies)Four design decisions that fall straight out of these numbers:
- The entire 5.52M-rule dataset fits in ~160 MB of RAM. Instead of a partial cache that suffers cache misses on unfamiliar attacker IPs, every checker node can hold a full in-memory replica of the rule set. "Cache invalidation" simplifies to "stream every rule change to every replica in order."
- Reads outnumber writes by ~1,300 to 1 even during an attack burst. Doing extra bookkeeping at write time (assigning gap-free versions, tracking prefix counts) pays off massively if it keeps lookups simple.
- A network hop (~300 us same-AZ) is 300x slower than an in-memory lookup (~1 us). The 400 firewall gateways run a replica agent directly in-process. The 3,000 polyglot application containers are too numerous to each carry a 160 MB replica, so they use a lightweight in-process SDK verdict cache backed by 6 regional gRPC check nodes.
- Update volume is tiny (
64 KB/sat burst). Pushing ordered deltas to 206 regional subscribers takes only ~13 MB/s of distributor egress.
API design
We expose three clean interfaces: a REST Control API for humans and automation, a low-latency gRPC Check API (with a REST mirror) for callers, and an internal Replica Feed for gateway agents and check nodes.
Control API (REST, authenticated & audited) PUT /v1/rules/{cidr} Create or replace rule for exact prefix (e.g., 203.0.113.0%2F24) body: {"action": "block" | "allow", "source": "admin" | "abuse_detector" | "feed:spamhaus-drop", "reason": "credential stuffing, incident SEC-4411", "expires_at": "2026-11-30T12:00:00Z"} -- required when source != "admin" -> 201 Created | 200 OK {"rule": {...}, "version": 88412907} -> 400 INVALID_CIDR malformed CIDR or host bits set (e.g., 203.0.113.45/24) -> 403 NOT_OWNER automated source tried to overwrite an admin-owned rule -> 409 PROTECTED_RANGE overlaps company egress IPs, DNS resolvers, or health probes -> 422 TOO_BROAD shorter than /8 (IPv4) or /32 (IPv6) without two-person approval PATCH /v1/rules/{cidr} Update reason or expiry; requires If-Match: "<rule_version>" DELETE /v1/rules/{cidr} Idempotent delete -> 204 No Content (even if already absent) POST /v1/rules:batch Up to 10,000 put/delete ops applied atomically in one transaction GET /v1/rules?contains=203.0.113.45 All rules covering this IP, ordered longest prefix first GET /v1/rules?overlaps=203.0.0.0/16 All rules inside or enclosing this CIDR range GET /v1/rules/{cidr}/history Audit log of changes for this prefix Check API (gRPC + REST mirror GET /v1/check?ip=...) rpc Check(CheckRequest { ip: bytes, min_version: uint64 optional }) returns (CheckResponse { blocked: bool, rule_prefix: string, // e.g., "203.0.113.0/24" (empty if no rule matched) uniform_block: bool, // true if the entire /24 (IPv4) or /64 (IPv6) shares this verdict ttl_ms: uint32, // max milliseconds the SDK may cache this verdict (e.g., 2000) version: uint64 // ruleset version this node evaluated against }) rpc BatchCheck(BatchCheckRequest { repeated bytes ips }) returns (BatchCheckResponse) Replica Feed (internal gRPC + object storage) GET /v1/ruleset/snapshot/latest -> {"version": 88410000, "url": "...", "sha256": "..."} rpc StreamChanges(since_version) -> ordered stream of ChangeEventWhy these API choices matter:
- Prefix is the primary key (
PUT /v1/rules/{cidr}). Retrying a network timeout overwrites the exact same key safely (idempotency), and two conflicting rules can never exist at the exact same prefix length. - Checks always return HTTP 200 / gRPC OK with
blocked: true | false. An HTTP 403 from the check service itself means "your service credentials are invalid", never "the user IP is blocked." - Server-driven cache hints (
uniform_block,ttl_ms). Only the server knows whether a/24contains narrower/32exceptions or whether a rule expires in 400 ms. Returning those hints keeps client SDKs dumb and consistent. - Source ownership. When an hourly threat feed deletes prefixes that disappeared from today's feed file, the
NOT_OWNERguard stops it from accidentally deleting manual blocks placed by security engineers.
- Prefix is the primary key (
Data model and contiguous versioning
PostgreSQL serves as the source of truth in the control plane. It never touches check traffic, so we pick it for transactional safety and native networking types: its
cidrcolumn rejects invalid host bits automatically, and a GiST index (inet_ops) answers admin "contains" (>>=) and "overlaps" (&&) queries in milliseconds.ip_rules (current state) prefix cidr PRIMARY KEY -- '203.0.113.0/24' or '2001:db8::9/128' family smallint NOT NULL -- 4 or 6 action text NOT NULL -- 'block' | 'allow' source text NOT NULL -- 'admin' | 'abuse_detector' | 'feed:<name>' reason text NOT NULL created_by text NOT NULL updated_at timestamptz NOT NULL expires_at timestamptz NULL -- NULL = permanent (allowed for admin only) rule_version bigint NOT NULL INDEX gist (prefix inet_ops) -- fast admin contains / overlaps queries INDEX (source, prefix) -- fast per-feed sync diffs INDEX (expires_at) WHERE expires_at IS NOT NULL ruleset_head (single-row counter table) id int PRIMARY KEY CHECK (id = 1) version bigint NOT NULL -- latest committed ruleset version change_log (append-only replication stream & 13-month audit log, partitioned monthly) version bigint PRIMARY KEY -- contiguous: 1, 2, 3, ... with zero gaps txn_last_version bigint NOT NULL -- final version in the same DB transaction prefix cidr NOT NULL before_state jsonb NULL -- NULL on insert after_state jsonb NULL -- NULL on delete actor text NOT NULL committed_at timestamptz NOT NULLWhy we do NOT use
SERIAL/BIGSERIALforversion: PostgreSQL sequences hand out numbers before commit and never roll them back on error:Txn A grabs seq 101 -> crashes and rolls back (101 is lost forever!) Txn B grabs seq 102 -> commits first -> replica sees 100, then 102: did it drop 101, or did 101 abort?Instead, every write transaction modifies
ip_rulesfirst, and as its very last step beforeCOMMITupdates the single row inruleset_head:UPDATE ruleset_head SET version = version + :n WHERE id = 1 RETURNING version; -- Stamp versions (returned - n + 1) .. returned onto the n change_log rows, -- setting txn_last_version = returned on every row in the batch, then COMMIT.Because PostgreSQL holds that row lock until
COMMIT,versionis gap-free and strictly matches commit order. Holding the lock for ~3 ms at the tail of a transaction allows ~330 transactions/s; withrules:batchpacking up to 10,000 changes into one ~100 ms lock acquisition, throughput reaches ~100,000 rule changes/s — 100x above our peak burst.High-level architecture
Security Console Abuse Detectors Threat Feeds \ | / v v v +----------------------------------------------+ | Control API (stateless REST pods) | validation, ownership, | PUT / PATCH / DELETE / rules:batch / search | protected-CIDR guardrails +----------------------+-----------------------+ | single DB txn: ip_rules + ruleset_head + change_log v +----------------------------------------------+ +-----------------------+ | PostgreSQL Primary (Region 1, sync AZ stby) | ----> | Snapshot Builder | +----------------------+-----------------------+ | repeatable-read dump | | async streaming replication | every 5 min | +---------------+----------------+ +-----------+-----------+ v v | regional S3/GCS [ Read Replica, Region 1 ] [ Read Replica, Region 2 ] v | | snapshots/v88410000.bin v poll change_log (200 ms) v [ Distributor x3, Region 1 ] [ Distributor x3, Region 2 ] | gRPC StreamChanges (ordered, gap-checked) +--------+--------------------+--------------------------+ v v v Firewall Gateway (x400) Check Service Node (x6/region) (same in every region) + In-Process Replica Agent Full 160 MB RAM Replica L0 lookup ~1 us L2 gRPC Check / BatchCheck ^ | same-AZ gRPC (10 ms deadline) on L1 miss only Application Pod (x3,000) + L1 SDK Verdict Cache (50k entries, <= 2 s TTL)Notice two properties of this topology: - Zero database calls on the check path. If PostgreSQL goes completely offline for maintenance or an incident, all 400 gateways and all 3,000 application pods keep serving traffic at full speed from RAM. - One unified replication mechanism. Both the L0 gateway agent and the L2 check nodes run the exact same snapshot-plus-delta subscriber library.
Deep dive 1: indexing exact addresses and variable-length CIDR prefixes
Each replica needs an in-memory data structure that finds the longest matching prefix among 5.52M rules in ~1 microsecond while accepting live single-rule inserts and deletes.
How the index works: one hash table per prefix length. An IPv4 address is just a 32-bit integer (and IPv6 is a 128-bit integer). Shifting an IP right by
32 - lengthbits strips off the host bits and leaves the exact network prefix!Example: Rule set contains 203.0.113.0/24 -> block, and 203.0.113.12/32 -> allow. Incoming IP: 203.0.113.12 (32-bit binary: 11001011.00000000.01110001.00001100) Lengths in use (probed longest to shortest): [32, 24] 1. Probe /32 table with key (ip >> 0) = 203.0.113.12 -> HIT! Action = "allow" -> STOP, return allow. Incoming IP: 203.0.113.45 1. Probe /32 table with key (ip >> 0) = 203.0.113.45 -> miss 2. Probe /24 table with key (ip >> 8) = 203.0.113 -> HIT! Action = "block" -> STOP, return block.To help downstream SDK caches (Deep dive 2), we also maintain a
finercounter per/24block (IPv4) and/64block (IPv6) counting how many rules longer than/24(or/64) currently live inside that block. Whenfiner[block] == 0, every single IP inside that/24is guaranteed to get the exact same verdict!# Bit widths and cache-block prefix lengths for IPv4 and IPv6 WIDTH = {4: 32, 6: 128} BLOCK_LEN = {4: 24, 6: 64} class RuleIndex: """Full in-memory rule replica using one hash map per active prefix length.""" def __init__(self): # tables[family][prefix_len] -> {prefix_int: {"action": ..., "expires_at": ...}} self.tables = {4: {}, 6: {}} # Active prefix lengths sorted descending (e.g., [32, 28, 24, 16]) for longest-match-first self.lengths = {4: [], 6: []} # finer[family][block_prefix_int] -> count of rules strictly more specific than /24 or /64 self.finer = {4: {}, 6: {}} def put(self, family, network_int, length, rule): width = WIDTH[family] if length not in self.tables[family]: self.tables[family][length] = {} self.lengths[family] = sorted(self.tables[family], reverse=True) table = self.tables[family][length] # In Python, arbitrary-precision ints handle length == 0 (ip >> 32 == 0) safely; # in C/Go/Rust fixed-width ints, guard length == 0 explicitly to avoid shift masking. key = 0 if length == 0 else (network_int >> (width - length)) # Only increment finer when inserting a brand-new prefix longer than the cache block if key not in table and length > BLOCK_LEN[family]: block = network_int >> (width - BLOCK_LEN[family]) self.finer[family][block] = self.finer[family].get(block, 0) + 1 table[key] = rule def remove(self, family, network_int, length): width = WIDTH[family] table = self.tables[family].get(length) if not table: return key = 0 if length == 0 else (network_int >> (width - length)) if key not in table: return del table[key] if length > BLOCK_LEN[family]: block = network_int >> (width - BLOCK_LEN[family]) self.finer[family][block] -= 1 if self.finer[family][block] == 0: del self.finer[family][block] # Prune empty prefix-length tables so lookup() never probes unused lengths if not table: del self.tables[family][length] self.lengths[family] = sorted(self.tables[family], reverse=True) def lookup(self, family, ip_int, now): """Return (winning_rule_or_None, is_uniform_across_block).""" width = WIDTH[family] block = ip_int >> (width - BLOCK_LEN[family]) uniform = block not in self.finer[family] # Probe from longest prefix to shortest; first unexpired hit is the longest match for length in self.lengths[family]: key = 0 if length == 0 else (ip_int >> (width - length)) rule = self.tables[family][length].get(key) if rule is not None: expires_at = rule["expires_at"] # Permanent admin rules have expires_at = None; automated rules carry an epoch timestamp if expires_at is None or expires_at > now: return rule, uniform return None, uniformWhy this beats the classic alternatives:
Data structure Strengths Why we did not pick it here Hash map per prefix length (chosen) ~5–12 hash probes in practice (feeds mostly use /32,/24,/16); O(1) single-rule updatesWorst case 33 (IPv4) or 129 (IPv6) probes if every prefix length is populated Sorted disjoint intervals + binary search Predictable ~23 comparisons for 5.5M ranges; compact flat array Overlapping CIDRs must be flattened; inserting one /16can rewrite thousands of intervalsBinary radix / Patricia trie Bounded 32 / 128 bit steps; natural prefix tree Pointer-chasing across tree nodes causes CPU L3 cache misses on every step Shared Redis sorted sets Centralized state, simple exact-IP lookups Adds a network hop per check; Redis ZADDscores are 64-bit IEEE floats (exact only to2^53), which cannot represent 128-bit IPv6 addressesDeep dive 2: ultra-fast verdict lookups and three-tier caching
The core architectural challenge is caching rules and verdicts safely. Different tiers cache different things:
Tier Location What is cached Hit latency Max staleness L0 Firewall gateway (in-process) Full 160 MB rule replica ~1 us Replica lag (< 1 s typical) L1 App service pod (SDK in RAM) 50k recent verdicts (exact/block) < 1 us Replica lag + TTL (<= 2 s) L2 Regional check node (x6) Full 160 MB rule replica ~300 us RPC Replica lag (< 1 s typical) DB PostgreSQL Source of truth Never called on the check pathWhy L0 and L2 use full replicas instead of a look-aside cache (like Redis): 1. Adversarial miss storms: During a botnet attack, requests arrive from millions of random IPs never seen before. A look-aside cache suffers near-100% cache misses right at peak load, hammering the database. A full replica has a 0% miss rate. 2. Impossible range invalidation: If an admin blocks
203.0.0.0/16, a per-IP cache would hold up to 65,536 stale keys (203.0.x.y) with no efficient way to find and delete them.How the L1 SDK verdict cache solves both problems for the 3,000 app pods: 1. Bounded TTL instead of push invalidation: Every cached verdict expires after
min(2.0s, response.ttl_ms). Replica lag (~1 s) + SDK TTL (2 s) = ~3 s typical propagation, comfortably inside our5 sp99 SLA — without maintaining push-invalidation streams to 3,000 application containers. 2. Block-level caching (uniform_block): In IPv6, a single home router gets an entire/64(2^64addresses) and can rotate the bottom 64 bits on every request. When L2 reportsuniform_block: true, the SDK caches the verdict under the/64(or IPv4/24) block key so rotating addresses hit the cache immediately!import ipaddress import time from collections import OrderedDict class VerdictCache: """In-process L1 LRU verdict cache inside application services.""" def __init__(self, remote_check, max_entries=50_000, ttl_s=2.0, max_stale_s=600.0, on_error="allow"): self.remote_check = remote_check self.max_entries = max_entries self.ttl_s = ttl_s self.max_stale_s = max_stale_s self.on_error = on_error # entries: key -> (blocked, fetched_at, fresh_until) ordered least-recently-used first self.entries = OrderedDict() def is_blocked(self, ip_text): ip = ipaddress.ip_address(ip_text) width = WIDTH[ip.version] block_len = BLOCK_LEN[ip.version] exact_key = (ip.version, int(ip), width) block_key = (ip.version, int(ip) >> (width - block_len), block_len) now = time.monotonic() # Fast path: check exact IP key first, then /24 or /64 uniform-block key for key in (exact_key, block_key): hit = self.entries.get(key) if hit is not None and hit[2] > now: self.entries.move_to_end(key) return hit[0] # Cache miss: query same-AZ L2 check service with a tight 10 ms deadline try: answer = self.remote_check(ip_text) except (TimeoutError, ConnectionError): return self._stale_fallback(exact_key, block_key, now) # Cache at block granularity when L2 confirms no narrower rules exist inside the block target_key = block_key if answer["uniform_block"] else exact_key ttl = min(self.ttl_s, answer["ttl_ms"] / 1000.0) self.entries[target_key] = (answer["blocked"], now, now + ttl) self.entries.move_to_end(target_key) if len(self.entries) > self.max_entries: self.entries.popitem(last=False) return answer["blocked"] def _stale_fallback(self, exact_key, block_key, now): """On L2 outage, use whichever non-ancient cached entry was fetched most recently.""" best_verdict = None newest_fetched_at = -1.0 for key in (exact_key, block_key): entry = self.entries.get(key) if entry is not None: blocked, fetched_at, _ = entry if (now - fetched_at) <= self.max_stale_s and fetched_at > newest_fetched_at: newest_fetched_at = fetched_at best_verdict = blocked if best_verdict is not None: return best_verdict return self.on_error == "block"Three production details that protect L1 and L2: - Cache negative ("allow") verdicts too. Well over 95% of real traffic is legitimate; caching only
"block"verdicts would send 95%+ of all requests straight to L2. - Single-flight request coalescing. If 200 concurrent threads in one app pod miss on the same new IP simultaneously, one thread makes the gRPC call and the other 199 await its result instead of firing 200 duplicate RPCs. - Zero-hit-rate survival math. Notice our sizing: 6 L2 nodes × 25k/s = 150k/s capacity, matching 100% of the busiest region's application check rate at normal peak even if L1 hit rate drops to 0%. An autoscaler watches L1 miss rate alongside CPU to spin up extra L2 pods before a multi-AZ outage + attack coincides.Deep dive 3: ordered change streaming and staleness bounds
With full replicas at L0 and L2, propagation means delivering every committed transaction in exact version order and detecting any dropped packet immediately.
- Cold start (snapshot + delta catch-up): A starting replica downloads the latest compressed snapshot (
~50 MBfrom regional object storage in< 1 s), loads it into RAM atapplied_version = snapshot.version, and opensStreamChanges(since_version = snapshot.version). - Contiguous gap detection: Distributors poll the regional PostgreSQL read replica every
200 ms(WHERE version > :last ORDER BY version LIMIT 10000) and push events over gRPC. Because versions have no gaps, a replica assertsevent.version == applied_version + 1. On any mismatch or disconnect, it reconnects to another distributor fromapplied_version(or reloads a fresh snapshot if behind by> 24 h). - Applying batches without false blocks: Suppose an admin submits a batch adding
block 203.0.113.0/24andallow 203.0.113.12/32together.- On L2 check nodes with plenty of RAM, the replica uses copy-on-write per modified prefix table and swaps the root index pointer atomically once
event.version == event.txn_last_version, so readers never see a half-applied batch and never take a lock. - On memory-constrained gateways updating tables in place, applying the
/24 blockmilliseconds before the/32 allowwould briefly drop partner traffic on.12! Ordering unblocking changes before blocking changes inside each transaction prevents any address that is allowed both before and after the batch from ever being blocked mid-batch:
- On L2 check nodes with plenty of RAM, the replica uses copy-on-write per modified prefix table and swaps the root index pointer atomically once
Batch: [PUT 203.0.113.0/24 -> block, PUT 203.0.113.12/32 -> allow] Wrong order: apply /24 block first -> .12 is FALSELY BLOCKED -> apply /32 allow -> .12 allowed Safe order: apply /32 allow first -> .12 stays allowed -> apply /24 block -> .12 still allowed!def is_unblocking(change): """Return True if this change can only move IPs from blocked to allowed.""" before_action = change["before_action"] # "block", "allow", or None after_action = change["after_action"] # "block", "allow", or None if before_action == "block": # Deleting a block or turning a block into an allow only unblocks IPs return after_action != "block" # Inserting a brand-new allow rule only carves out an allowed exception return before_action is None and after_action == "allow" def apply_transaction_safely(index, txn_changes): """Apply unblocking ops before blocking ops so continuously allowed IPs never flap.""" unblocking_ops = [c for c in txn_changes if is_unblocking(c)] blocking_ops = [c for c in txn_changes if not is_unblocking(c)] for change in unblocking_ops + blocking_ops: if change["after_action"] is None: index.remove(change["family"], change["network_int"], change["length"]) else: index.put(change["family"], change["network_int"], change["length"], change["rule"])- Zero-message expiration: Because
lookup()checksexpires_at > nowlocally using NTP-synced clocks, rules expire everywhere at the exact same second even during a replication outage. A background janitor deletes expired DB rows once a minute purely to reclaim RAM. - Read-your-writes for admins: When an admin blocks an IP in the console and immediately runs a diagnostic check, the console passes
min_version = write_response.version. If the L2 node hasn't reachedmin_versionyet, it waits up to1 son its stream or falls back to PostgreSQL's GiST>>=query.
End-to-end propagation budget (target <= 5 s p99) Primary commit + sync AZ standby ~5 ms Cross-region async DB replication ~100 - 300 ms Distributor poll interval 0 - 200 ms gRPC push + replica batch apply ~10 - 50 ms --> L0 / L2 fresh in < 0.6 s typical App SDK L1 verdict TTL 0 - 2,000 ms --> L1 fresh in < 2.6 s typical- Cold start (snapshot + delta catch-up): A starting replica downloads the latest compressed snapshot (
Consistency guarantees, horizontal scaling, fault tolerance, and telemetry
Consistency model - Writes: Linearizable through the single PostgreSQL primary. - Per replica: Consistent prefix — every replica reflects all committed transactions
1 .. applied_versionwith zero gaps. - Across replicas: Eventual consistency bounded and measured in seconds via 1-second distributor heartbeats carrying(head_version, head_committed_at).What happens if threat feeds grow 10x to 50M rules (~1.6 GB RAM)? 1. Policy-based CIDR aggregation: Threat feeds often list 200 individual bots inside one
/24; collapsing/24s above a policy threshold shrinks rule counts dramatically (noting explicitly that this is a security policy trade-off since neighbors in that/24get blocked too). 2. Tiered L0 gateway replicas: Gateways keep all CIDRs plus active/32s from the last 24 hours (~200 MB), delegating cold/32lookups to L2 check nodes which easily hold 1.6 GB. 3. Prefix-sliced L2 sharding (last resort): Shard L2 nodes by top prefix bits (replicating the rare/0..7rules to all shards).Failure modes and defenses
Failure Impact Mitigation PostgreSQL primary fails Writes return 503 Retry-Afterfor ~30–60 s during standby failoverZero impact on check path; L0, L1, and L2 keep serving from RAM Cross-region link severed Cut-off region stops receiving primary updates Serves last known ruleset; operators can push urgent region-local 1-hour blocks via an emergency overlay table on regional distributors Gateway cold-starts while S3 is down Cannot fetch latest snapshot Loads last snapshot persisted on local disk, then streams deltas; never boots empty and claims to be healthy Single L2 check node lags > 30 s Stale verdicts Fails readiness probe and drains from load balancer — unless > 50% of nodes lag simultaneously (panic threshold keeps stale nodes serving rather than blackholing traffic) Bad admin/feed rule ( 0.0.0.0/0or mass wipe)Outage or wide-open firewall Blocked at Control API ( TOO_BROAD,PROTECTED_RANGE, > 20% feed-drop circuit breaker) + one-click revert to versionVObservability that catches silent bugs - End-to-end synthetic canary: Every minute, a probe writes
block 192.0.2.88/32(RFC 5737 documentation range, never real user traffic), measures exact milliseconds until L0/L2/L1 reportblocked: true, then deletes it and times the unblock. - Max replica lag (max(lag_s)and p99, never average): One wedged gateway hiding behind 399 healthy ones disappears in an average. - Blocked-verdict ratio alert: Pages immediately if the percentage of blocked requests doubles in 10 minutes (catches bad rules within seconds).Summary of the trade-offs
- Full in-memory replicas (L0/L2) vs. look-aside Redis cache: Uses ~160 MB RAM per checker and requires a snapshot + delta pipeline, but eliminates cache misses during DDoS attacks, removes CIDR key-invalidation headaches, and decouples check availability completely from the database.
- In-process L0 on gateways vs. L1 SDK cache + L2 gRPC service for apps: Gives microsecond checks to the 400 gateways handling 77% of traffic without forcing 3,000 polyglot app containers to each carry 160 MB of RAM.
- 2-second SDK TTL +
uniform_blockvs. push invalidation to apps: Accepts up to 2 seconds of bounded staleness in exchange for zero stateful stream management inside 3,000 client pods while keeping/24and/64scan hit rates high. - Hash map per prefix length vs. radix trie or sorted intervals: Trades a handful of hash probes for O(1) live updates without pointer-chasing cache misses or full array rebuilds.
- Serialized
ruleset_headrow lock vs. DB sequence: Caps raw transaction rate (~330 txns/s, ~100k batched changes/s) to buy contiguous, commit-ordered versions that make stream gap detection trivial. - Fail open with stale fallback vs. fail closed: Lets a tiny window of abusive traffic slip through during total check-tier failure rather than turning a blocklist outage into a site-wide outage.
Intuition & how it works
Think of an IP blocklist platform like the security desk at a busy airport. If every guard had to phone central headquarters for every single passenger, the line would back up out the door — and if the phone line went down, the whole airport would grind to a halt. Instead, headquarters prints a compact watch-list binder that fits right on every guard's podium, and sends instant one-line radio updates whenever a name is added or removed. Because our entire blocklist of ~5.5 million exact IPs and CIDR ranges (Classless Inter-Domain Routing blocks like 203.0.113.0/24, meaning all IP addresses sharing the first 24 bits) fits into ~160 MB of RAM, every firewall gateway and check server keeps a full in-memory replica (a complete local copy in RAM) and never calls the database during a check.
The obvious beginner design — putting a look-aside cache (a cache like Redis where a miss queries PostgreSQL and populates the cache) in front of the database — fails right when you need the firewall most. During a botnet attack, requests arrive from millions of brand-new IP addresses that are not in Redis yet, causing a massive cache-miss storm that overwhelms PostgreSQL. Worse, if an engineer blocks a broad CIDR range like 203.0.0.0/16, there is no practical way to locate and delete up to 65,536 individual cached IPs sitting inside Redis.
Walk through a concrete 4-step trace to see how our design handles rules, exceptions, and caching together:
1. Write & version: An engineer blocks 203.0.113.0/24 except partner webhook IP 203.0.113.12/32 (allow) in one batch. PostgreSQL locks a single-row counter (ruleset_head) to assign contiguous versions 101 and 102, then appends both to change_log.
2. Safe propagation: Regional distributors stream versions 101..102 to every gateway and check node, which apply the allow exception (203.0.113.12/32) before the /24 block so .12 is never blocked for even a millisecond.
3. Longest-prefix lookup: When 203.0.113.12 arrives at a gateway, its in-memory RuleIndex probes active prefix lengths from longest to shortest (/32 before /24), hits /32 -> allow in ~1 microsecond, and lets the request through. When 203.0.113.45 arrives, /32 misses and /24 -> block wins (longest-prefix match, the rule that the most specific matching IP range always takes precedence).
4. Smart SDK caching: When an application pod checks 198.51.100.19 (inside a /24 with zero /25..32 sub-rules), the check node returns blocked: true, uniform_block: true, ttl_ms: 2000. The app's in-process SDK caches that verdict for the entire 198.51.100.0/24 block with a 2-second TTL (time-to-live, an automatic expiration timer), so even if the attacker rotates through .20, .21, and .22, every follow-up request hits local RAM in under a microsecond.
Key trade-offs
- Full in-memory replicas vs. a shared look-aside cache. Holding all 5.5M rules (~160 MB) on every gateway and check node guarantees a 0% miss rate during random-IP DDoS attacks, eliminates per-IP cache invalidation when CIDR blocks change, and keeps checks working when PostgreSQL is completely down. The trade-off is building a replication pipeline with periodic snapshots, ordered delta streams, and lag monitoring.
- In-process L0 agents on gateways vs. L1 SDK verdict cache + L2 check nodes for apps. The 400 firewall gateways handle 1M checks/s in ~1 microsecond with zero network hops. The 3,000 application containers avoid carrying 160 MB of RAM each by caching 50,000 recent verdicts locally and calling a regional 6-node gRPC check service only on cache misses.
- Short TTL bounds vs. push invalidation for the 3,000 app SDKs. A 2-second SDK TTL bounds total propagation delay (replica lag + TTL) well inside our 5-second target without wiring stateful invalidation streams into thousands of polyglot app pods. Push invalidation would shave off ~1.5 seconds of staleness, at the risk of silent, unbounded staleness whenever a client drops an invalidation message.
- Block-level SDK caching (
uniform_block) vs. exact-IP caching only. Tracking a per-/24(IPv4) and per-/64(IPv6) counter of narrower rules on the server lets SDKs safely cache whole network blocks whenever no exceptions exist inside them, defeating IPv6/64address rotation at the cost of ~23 MB of server counter memory. - Hash map per prefix length vs. sorted intervals or a radix trie. One hash table per active prefix length (
/32,/24,/16, ...) supports O(1) single-rule updates and answers lookups in a handful of CPU-cache-friendly probes. Sorted disjoint intervals need expensive array rebuilds when overlapping CIDRs change, while a radix trie (a binary tree walked one IP bit at a time) suffers pointer-chasing CPU cache misses. - Serialized contiguous versions vs. database auto-increment sequences. Locking a single
ruleset_headrow at commit time limits raw unbatched writes (~330 txns/s, or ~100,000 changes/s via batching), which is plenty for blocklist writes. In return, versions have zero gaps and match commit order, so any replica guarantees a consistent prefix (having seen every version1..Vwith nothing missing) simply by checkingnext_version == applied_version + 1. - Eventual consistency with measured lag vs. linearizable checks. Running a linearizable read (a quorum or primary read guaranteed to see the very latest write instantaneously) on 1.3M checks/s would wreck latency and availability. Instead, replicas lag by < 1 second, export exact lag metrics, and support an opt-in
min_versionparameter so the admin console still gets read-your-writes consistency. - Fail open with stale fallback vs. fail closed. Failing open (allowing traffic when the check service is unreachable and no recent verdict is cached) risks letting brief abuse slip through during an outage, whereas failing closed (blocking everything on error) turns any bug in the blocklist service into a catastrophic outage for legitimate users.
Common mistakes
- Querying PostgreSQL or Redis on every incoming request. Adding a network round trip and a shared storage dependency on the hot path increases latency by orders of magnitude and lets a database hiccup take down all edge gateways.
- Caching only
"blocked"results in the SDK. Because 95%+ of normal user traffic is allowed, skipping negative caching sends almost every request over the network to the check service. - Trying to delete cached IPs one by one when a CIDR rule changes. Enumerating keys inside a
/16(or2^64keys inside an IPv6/64!) is impossible; either maintain a full rule replica or bound verdict cache staleness with a short TTL. - Maintaining separate allowlist and blocklist tables with ad-hoc priority rules. Storing
blockandallowin a single prefix index under longest-prefix-wins handles exceptions cleanly without conflicting precedence edge cases. - Forgetting
expires_at == Nonefor permanent admin rules or relying on delete events to stop blocking. Evaluatingexpires_at is None or expires_at > nowat lookup time makes automated blocks expire on time everywhere even if the replication stream is delayed. - Using a database
SERIALsequence for replication versions. Rolled-back transactions leave permanent gaps in sequences, and concurrent transactions commit out of sequence order, causing subscribers to either stall waiting for missing numbers or silently skip real updates. - Applying batch updates in arbitrary order on live indexes. Adding
block 203.0.113.0/24beforeallow 203.0.113.12/32briefly drops traffic from the allowed partner IP; always apply unblocking changes before blocking changes (or swap an immutable index snapshot atomically). - Allowing automated threat feeds to overwrite or delete manual admin rules, or accepting
/0typos. Enforce source idempotency (safe retries via prefix keys), per-source ownership checks, protected company CIDR lists, and human approval for overly broad prefixes like/4. - Alerting only on average replication lag. One broken gateway 20 minutes behind 399 healthy gateways barely moves the mean; always monitor
max(lag_s), p99 lag, and an end-to-end synthetic canary rule (192.0.2.88/32).
Follow-up questions
- How would the architecture adapt if external threat feeds expand the active rule set from ~5 million entries to 50 million? At 50 million rules, one full in-memory replica grows to ~1.6 GB — still comfortable on dedicated L2 check servers, but too heavy for every shared firewall gateway. First, apply policy-controlled CIDR aggregation (for instance, collapsing
/24blocks where a single feed already flags more than 50% of addresses, noting the trade-off of blocking neighboring IPs). Second, convert L0 gateways to a tiered replica holding all CIDR ranges plus the exact/32IPs seen in the past 24 hours (~200 MB), forwarding misses to L2 check nodes that hold the full 1.6 GB dataset; only shard L2 by leading IP bits if rules grow past single-node RAM. - During a live security incident, how could you guarantee sub-second global enforcement of an emergency block with verifiable proof of rollout? L0 gateways and L2 check nodes already receive updates in ~0.6 seconds (
5 mscommit +~300 mscross-region replication +200 mspoll +50 msapply), so the bottleneck is the 2-second TTL inside the L1 app SDK cache. Loweringttl_mson new responses does not clear verdicts already cached, so add a lightweight emergency invalidation broadcast channel (or reduce L1 TTL to300 msfor high-risk endpoints) that tells SDKs "evict cached entries insideX/Nimmediately," while keeping the 2-second TTL as a safety net if an SDK misses the broadcast. For verifiable proof, every L0 and L2 node reports itsapplied_versionin real time, letting the console confirm "version 88412907 active on 400/400 gateways and 18/18 check nodes; all L1 caches guaranteed fresh 2.0s later." - How does your caching layer hold up when an attacker rotates across thousands of IPv6 /64 subnets inside a single /48 allocation? A
RuleIndexlookup handlesblock 2001:db8:abcd::/48effortlessly in O(1), because lookup speed depends on the number of active prefix lengths, not the number of attacker IPs. However, rotating across up to 65,536 distinct/64s inside that/48bypasses/64uniform_blockkeys in the L1 SDK cache, driving up L2 RPC traffic. To absorb that, return the actual widest uniform prefix length inCheckResponse(e.g.,uniform_prefix_len: 48, backed by afinercounter at/48in addition to/64) so one L1 cache entry covers the entire/48, while single-flight coalescing and L1-miss-rate autoscaling protect L2 in the meantime.
Follow-up questions
- How would the architecture adapt if external threat feeds expand the active rule set from ~5 million entries to 50 million?
- During a live security incident, how could you guarantee sub-second global enforcement of an emergency block with verifiable proof of rollout?
- How does your caching layer hold up when an attacker rotates across thousands of IPv6 /64 subnets inside a single /48 allocation?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System