Design a Real-Time IP Blacklist and CIDR Lookup Engine
System DesignModel answerLast updated
Design a scalable, low-latency API and propagation architecture to block malicious IP addresses and CIDR ranges across distributed edge nodes.
Design an API and distributed backend architecture for an enterprise IP blacklist system.
The system must allow security operations and automated threat-detection services to add, update, remove, and query blocked IP addresses and network prefixes (CIDR blocks). Distributed edge routers, API gateways, and application microservices must evaluate incoming requests against this blacklist in real time.
Your design should cover:
- API Specifications: Define both management (control plane) and evaluation (data plane) interfaces.
- Data Structure & Storage: Select the data structures and persistent database for efficient single-IP and variable-length CIDR range matching.
- Low-Latency Read Path: Detail how edge components verify IPs under strict latency budgets.
- Cache Invalidation & Sync: Explain how changes flow from the write plane to all edge readers rapidly and reliably.
- Scale, Fault Tolerance & Observability: Address scale targets, edge isolation, edge-case failure modes, and operational monitoring.
Hints
Hint 1
Consider the asymmetry between read and write volumes: reads occur on every inbound HTTP packet/request, while writes are infrequent.
Hint 2
Prefix matching requires specific data structures like Patricia tries or interval arrays rather than plain hash tables.
Hint 3
Think about in-process evaluation (local caching) vs. remote API calls on the critical path.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture: Real-Time IP Blacklist Engine
An IP blacklist engine exhibits extreme read/write asymmetry:
- Writes: Low volume (10–100 writes/sec normally, bursting to 10k/sec during automated mitigation).
- Reads: Extremely high volume (millions of checks/sec) on the critical path of every incoming network connection or HTTP request.
To meet strict latency targets, the data plane must avoid network round-trips to a central database on every request. Instead, the complete ruleset should be distributed to edge nodes and held in-process using space-efficient, fast-lookup data structures.
1. Requirements & System Constraints
Functional Requirements
- Add, update, soft-delete, and fetch IP block rules (single IPv4/IPv6 and CIDR ranges like
192.0.2.0/24or2001:db8::/32). - Support rule metadata (expiration TTL, risk score, rule creator, reason code, and action type:
BLOCK,ALLOW,LOG). - Evaluate whether an IP is blocked and return the matching rule ID and action.
- Support bulk mutations from automated security orchestration platforms (SOAR).
Non-Functional Requirements & Scale
- Throughput: 2M+ read evaluations per second across 1,000+ distributed application instances/gateways.
- Latency:
- In-process local lookup: < 10 microseconds (p99).
- Centralized check service fallback: < 1 millisecond (p99).
- Propagation Latency: Rule mutations must propagate globally within 1–3 seconds.
- Dataset Size: ~10 million active rules (~500 MB to 1 GB total footprint), easily fitting within memory on modern servers.
- Consistency: Eventual consistency for reads; strong durability and serializability for write history.
2. API Design
Control Plane (Admin & Threat Automation)
POST /v1/rules
Body: {
"cidr": "203.0.113.0/24",
"action": "BLOCK",
"reason": "DDoS attack detected",
"source": "auto_mitigation",
"ttl_seconds": 3600
}
Response: 201 Created { "rule_id": "rule_8f9a2", "version": 10452 }
DELETE /v1/rules/{rule_id}
Response: 200 OK { "version": 10453 }
POST /v1/rules:batch
Body: { "ops": [ {"type": "ADD", "cidr": "..."}, {"type": "DELETE", "rule_id": "..."} ] }
Response: 200 OK { "version": 10454 }
GET /v1/snapshot?since_version=10400
Response: 200 OK { "latest_version": 10454, "deltas": [...] }
Data Plane (High-Throughput Read Interface)
For clients unable to run local in-process engines:
GET /v1/check?ip=198.51.100.45
Response: 200 OK
{
"ip": "198.51.100.45",
"blocked": true,
"action": "BLOCK",
"rule_id": "rule_8f9a2",
"version": 10454
}
3. Data Storage & In-Memory Matching Logic
Primary Database (Control Plane)
The authoritative store requires ACID compliance, change tracking, and efficient range queries for administrative auditing.
Primary Relational Database Schema (PostgreSQL):
CREATE TABLE blacklist_rules (
rule_id VARCHAR(64) PRIMARY KEY,
family VARCHAR(4) NOT NULL, -- 'v4' or 'v6'
network_start BYTEA NOT NULL, -- Binary IP representation
prefix_len INT NOT NULL,
action VARCHAR(16) NOT NULL,
reason TEXT,
source VARCHAR(64),
expires_at TIMESTAMPTZ,
deleted_at TIMESTAMPTZ,
version BIGSERIAL NOT NULL
);
CREATE INDEX idx_rules_version ON blacklist_rules(version);
CREATE INDEX idx_rules_prefix ON blacklist_rules USING gist (network_start inet_ops);
In-Memory Lookup Engines (Data Plane Edge)
Standard hash tables fail when matching variable-length subnet masks (CIDRs) because a lookup for IP 203.0.113.45 must match rules defined for 203.0.113.0/24, 203.0.0.0/16, or 203.0.113.45/32.
To handle this efficiently, edge nodes maintain two internal structures:
- Hash Set for /32 (IPv4) and /128 (IPv6) Exact Matches:
- Over 80% of block entries are single host IPs.
- Stored in a standard hash table for $O(1)$ constant time lookup.
- Compressed Radix Trie (Patricia Trie) for CIDR Ranges:
- Bits of the IP address form the traversal path (0 goes left, 1 goes right).
- Longest Prefix Match (LPM): Traversal continues down the trie until the deepest matching rule node is found. This allows granular overrides (e.g., block
10.0.0.0/8except10.1.2.3/32via anALLOWrule). - Space complexity: $O(N)$ where $N$ is total prefixes. Time complexity: $O(K)$ where $K$ is address bit-length (32 for IPv4, 128 for IPv6).
[Root]
/ \
0 / \ 1
[0] [1]
/ \
0 / \ 1
[0.0.0.0/2: BLOCK] [1.0.0.0/2: ALLOW]
Double-Buffering / Copy-on-Write (Lock-Free Reads)
To prevent lock contention on the critical path during high-throughput reads:
- The read path holds a pointer to an immutable instance of the trie + hash set.
- Updates apply modifications to a background copy of the data structure.
- Once ready, the root pointer is swapped using an atomic pointer swap (Read-Copy-Update pattern). Reads proceed without taking locks.
4. End-to-End System Architecture & Real-Time Sync
[ Admin / SOAR ]
│
▼
[ Control API ] ──► [ Primary PostgreSQL ]
│
(CDC / Outbox Pattern)
│
▼
[ Kafka Change Event Log ]
│
┌──────────────────────┼──────────────────────┐
▼ ▼ ▼
[ Full Snapshot Worker ] [ Regional gRPC Sync ] [ Fallback Edge Service ]
│ │ │
▼ ▼ ▼
[ Object Store / S3 ] [ Edge Gateway Sidecars ] [ Local Memory Trie ]
(Bootstrap Download) (Stream Deltas & Swap)
Propagation Mechanics
- Mutation Ingestion: Control API receives a change, writes it to PostgreSQL within a transaction, and generates a monotonically increasing
versionsequence number. - Change Data Capture (CDC): Postgres updates are published to a partitioned Kafka topic (
blacklist-events), ordered by ruleversion. - Distribution Tier: A fleet of long-lived gRPC server-streaming nodes tail the Kafka topic and push deltas to thousands of registered sidecar readers.
- Edge Bootstrap:
- Upon startup, an edge reader downloads the latest complete binary snapshot (compressed trie array) from object storage/CDN (e.g., version 10,000).
- The reader connects to the gRPC streaming service, requesting all delta updates where
version > 10000. - It catches up to the live stream and resumes processing real-time updates.
Expiration / TTL Handling
Instead of triggering an explicit propagation update for every expiring rule, the edge data structure records the expires_at timestamp inside the node payload. During read evaluation:
if match and match.expires_at < current_timestamp:
# Treat as non-match; clean up lazily via background garbage collection
return ALLOW
This prevents thundering-herd issues when thousands of short-lived blocks expire simultaneously.
5. Failure Modes, Edge Cases, and Trade-Offs
| Failure Scenario | Impact | Mitigation / Design Choice |
|---|---|---|
| Kafka / Sync Stream Outage | Edge instances stop receiving updates. | System degrades to stale-read mode. Edge nodes continue enforcing existing in-memory rules while emitting alert metrics (blacklist_sync_delay_seconds). |
| Edge Instance Cold Start | Network down or object store unreadable. | Fall back to calling the centralized Check Service Fleet over local-rack network connections until snapshot download succeeds. |
| Gaps in Version Stream | Network flicker causes missed events (e.g., received v105 after v102). | Edge reader detects version_received != last_version + 1, drops stream, and re-initializes via delta catch-up API or full snapshot re-fetch. |
| Memory Exhaustion | Spike in prefix rules consumes host RAM. | Enforce rigid limits at the Control API level (max active rules = 20M). Compress Trie nodes (e.g., path compression, bitmapped child arrays). |
6. Observability and Performance Verification
- Metrics:
blacklist.check.latency_us: Histogram tracking check duration at p50, p99, p999.blacklist.sync.version_lag: Difference between DB global version and edge local version.blacklist.memory_bytes: In-memory footprint of active lookup structures.
- Auditability & Traceability:
- Include matching
rule_idand global datasetversionin application access logs (X-Blacklist-Match: rule_8f9a2;v10454) to streamline post-mortem analysis of false positives.
- Include matching