API Gateway Traffic Filtering Across Multiple Regions
System DesignModel answerLast updated
Design a system that blocks untrusted IP addresses at an API gateway, handles rule versioning and expiration, and replicates enforcement state across data centers.
API Gateway Traffic Filtering Across Multiple Regions
Your team operates a set of API gateways deployed across several data centers. Security analysts flag IP addresses that should be denied access. Your job is to design the enforcement layer that sits inside each gateway, and then extend it so that rule changes propagate reliably to every region.
Background
Detection (deciding which IPs are bad) and enforcement (acting on that decision at the gateway) are separate concerns. Focus on enforcement. You may assume a control plane already produces rule updates; your design should consume them.
What to Design
-
Single-gateway enforcement — how a gateway decides, on every inbound request, whether the source IP is blocked. Include how you extract the real client address, where rules live in memory, and how you handle expiring rules.
-
Rule management — how rules are created, versioned, and removed. Address both individual addresses and network ranges (including IPv6). Explain how a false positive gets resolved quickly.
-
Multi-region propagation — how a new block or an urgent unblock reaches every data center within an acceptable window. Describe what a gateway does when the control plane is unreachable or its local rule set is stale.
Clarifying Questions to Address
Before diving in, state the assumptions you are making about:
- Who can create or revoke a block, and whether rules carry a scope or expiration.
- Whether rules cover exact IPs, CIDR ranges, or both, and whether IPv6 is in scope.
- What propagation latency is acceptable for normal blocks versus urgent unblocks.
- The desired gateway behavior under control-plane failure.
Constraints
- Rule volume and request throughput are unspecified — pick reasonable defaults and state them.
- Blocking a shared IP (e.g., a corporate NAT or a Tor exit node) may affect legitimate users; accuracy and false-positive cost matter.
- Treat block and unblock as asymmetric operations: an unblock may need faster or more reliable delivery than a new block.
Expected Output
A structured prose answer covering your assumptions, the data structures and APIs you would use, the propagation mechanism, failure-mode behavior, and the trade-offs you considered. No code is required, but diagrams described in words, latency estimates, and concrete technology choices are all encouraged.
Hints
Hint 1
Start by separating two things that look similar but aren't: the IP you see on the TCP socket versus the real client IP forwarded through load balancers. Getting this wrong means you block your own infrastructure. Walk through X-Forwarded-For parsing and why you trust only the rightmost address added by a component you control.
Hint 2
Think about block vs. unblock as two different SLAs, not one. A new block can tolerate a few seconds of propagation lag; an unblock of a falsely flagged IP may need near-instant delivery. This asymmetry should drive your replication design — consider a push channel (pub/sub or change-data-capture) for urgent operations on top of a periodic full-sync for correctness.
Hint 3
A radix trie (Patricia trie) lets you match both exact IPs and CIDR prefixes in O(address length) time, which is effectively O(1) for IPv4 and O(1) for IPv6. Pair this with a versioned snapshot so a gateway can swap in a new rule set atomically rather than applying partial updates mid-request.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions First
Before designing anything, nail down the policy:
- Who creates rules: a security team via an internal admin UI, with changes audit-logged. Automated signals (rate-limiting, WAF alerts) can nominate IPs but a human or automated approval step creates the authoritative rule.
- Rule types: exact IPv4, exact IPv6, and CIDR ranges for both. Ranges are common for cloud-hosted botnets that rotate across a subnet.
- Expiration: every rule carries a TTL (default 24 hours) and an optional manual expiry. Temporary blocks are the norm; permanent blocks are an explicit override.
- Propagation SLA: new blocks within ~5 seconds globally; urgent unblocks within ~1 second. These are asymmetric by design.
- Failure mode: gateways fail open on stale data rather than fail closed. Blocking legitimate traffic is a worse outcome than briefly passing malicious traffic.
Single-Gateway Enforcement
Extracting the Real Client IP
The TCP source address is the load balancer or CDN, not the end user. Parse X-Forwarded-For from right to left, skipping any addresses added by components you own, to find the first untrusted hop. Pinning which hops are trusted must be explicit configuration — trusting the whole header verbatim is a common mistake that lets clients spoof their apparent IP.
In-Memory Rule Store
Use a radix trie (Patricia trie) keyed on bit-prefixes of the IP address. This structure handles both exact addresses and CIDR ranges in O(address length) time — effectively O(1) for a 32-bit or 128-bit address. Each leaf stores the rule metadata: version, expiry timestamp, scope, and who created it.
Keep two copies of the trie: the live copy serving requests, and a shadow copy being updated. When a new snapshot arrives, populate the shadow copy and then do an atomic pointer swap. This avoids partial-update races.
A background goroutine (or equivalent) sweeps expired rules every 30 seconds. Because rules carry a TTL, the sweep is a safety net, not the primary expiry mechanism: on each check the gateway compares the rule's expiry to wall clock time.
Request Check
On every inbound request: extract client IP → look up in trie → if matched and not expired, return 403 with a Retry-After header set to the rule's expiry. Log the block event with rule ID and version for observability. The hot path is a single trie traversal with no I/O.
Rule Management and Versioning
The control plane stores rules in a durable database (Postgres works fine at this scale). Each write increments a global monotonic version counter. Rules are never mutated in place; a new version is appended and the old version is tombstoned. This makes diffs trivial: a gateway that holds version N asks for all changes since N.
For false-positive resolution, the admin UI exposes a one-click unblock that:
- Writes a tombstone with version N+1.
- Publishes an urgent message on a low-latency pub/sub topic (e.g., Kafka with a dedicated partition, or a Redis pub/sub channel).
- Gateways subscribed to that topic apply the unblock in-memory immediately, without waiting for the next sync cycle.
This is the asymmetric delivery model: normal rule changes ride the periodic sync; unblocks also ride the urgent push channel.
Multi-Region Propagation
Normal Path: Versioned Snapshots
Each region's local cache service polls the control plane every 5 seconds, requesting a diff since its last known version. The diff is a compact list of (rule_id, action, payload) tuples. The local cache applies the diff and increments its version. Gateways in the region poll their local cache every 1 second and swap in a new trie snapshot when the version advances.
This gives an end-to-end new-block latency of roughly 5s (control plane → regional cache) + 1s (cache → gateway) = ~6 seconds worst case. Acceptable for most threat scenarios.
Urgent Path: Push Channel
For unblocks, the control plane publishes to a global message bus. Each region has a subscriber that applies the unblock immediately to the in-memory rule set and writes it through to the local cache for durability. This path targets sub-second delivery.
Under Control-Plane Failure
If a gateway cannot reach its regional cache, it keeps serving from its last known trie snapshot. Rules that have passed their TTL are expired locally. The gateway does not block new addresses it has not seen before — it fails open. This means a brief window of reduced protection, which is the accepted trade-off over accidentally blocking valid users due to a stale aggressive rule set.
The local cache persists its snapshot to disk on every version increment. On restart, gateways load from disk before the first network sync, so they are not fully blind during a cold start.
Trade-offs and Common Mistakes
Fail open vs. fail closed. Fail closed (deny all if unsure) sounds safer but causes outages when the control plane hiccups. Fail open is the right default for most API gateways unless the protected resource is extremely sensitive.
Shared IPs. A corporate NAT or Tor exit node serves thousands of users. Before blocking a /24 or larger range, the system should surface utilization data (how many distinct sessions has this prefix generated?) to the analyst. Blocking a shared IP is a policy decision, not just a technical one.
Header spoofing. Trusting X-Forwarded-For blindly is the most common implementation mistake. The enforcement is only as good as the IP extraction.
Version skew. If gateways in the same region apply versions out of order (unlikely with a monotonic counter, but possible under network partitions), a rule could briefly reappear after being deleted. Gateways should reject diffs that would move their version counter backward.
Observability. Emit a counter per rule ID on every block event. This surfaces rules that are firing heavily (potential false positive) versus rules that never fire (candidates for cleanup). Without this, the rule set grows unboundedly and becomes unmaintainable.