Low-Latency IP Rule Enforcement Service
Easy · System Design · Software Engineer · Onsite
Prompt
Architect a distributed access-control service that evaluates incoming or outgoing network traffic against IP address policies and returns an allow or deny verdict at very low latency. Establish where in the network stack checks execute, support single IPs, CIDR subnets, and arbitrary [start, end] intervals across IPv4 and IPv6, define unambiguous conflict-resolution rules when policies overlap, and detail how rule updates roll out safely to enforcement hosts across multiple geographic regions.
Scope & Expectations
- Address normalization, policy semantics & API: Define canonical binary normalization and strict input validation across IPv4/IPv6 (including dual-stack forms), deterministic tie-breaking across overlapping rules, scoping dimensions (environment, traffic direction, tenant, service), rule expiry, per-scope fail-open vs. fail-closed defaults, and the local decision contract.
- Control-plane persistence & data-plane compilation: Contrast relational rule authoring (version lineage, authorship, justification, lifecycle state) against hot-path lookup structures (hash tables, prefix tries, interval trees, and pre-compiled disjoint tables), guaranteeing bounded per-packet work and lock-free atomic snapshot swaps.
- Global rollout, staleness & break-glass paths: Cover cryptographically authenticated monotonic snapshots, per-region acknowledgment tracking, Last-Known-Good behavior under network partitions, staged rollouts with safe rollback, strong authorization gates, and a fast, guardrail-bounded emergency block mechanism.
- Explainability, testing & day-two operations: Show how decisions remain auditable by rule and snapshot version without logging sensitive payloads or raw PII, and specify boundary/normalization test suites, pre-promotion shadow diffing, operational alerts (latency, rollout lag, stale nodes, hit spikes), and safe cleanup of unused rules.
Step-by-step walkthrough
Clarify requirements and enforcement boundaries
An IP filtering service looks simple on the surface — check an IP address and return
allowordeny— yet almost every real production incident comes from the surrounding details: which IP address you inspect behind proxies, which rule wins when two rules overlap, how updates reach thousands of machines safely, and how you prove weeks later why a customer was blocked.Where enforcement happens (decide this first, because it determines which IP you see):
- Inbound at the edge proxy / API gateway: Filters on the client's source IP. Behind a CDN or load balancer, the direct TCP peer is the balancer itself, so we extract the client IP from the load balancer's
PROXYprotocol header or fromX-Forwarded-Forby scanning right-to-left past proxy IPs we own and stopping at the first untrusted hop. Reading the leftmostX-Forwarded-Forentry is a classic bug because clients can forge anything on the left. - Inbound at internal service sidecars: A sidecar (a small helper proxy running alongside an application container on the same machine) locks internal admin and operations tools to corporate VPN IP ranges.
- Outbound at an egress proxy: Filters on the destination IP for outbound calls — for example, restricting payout API calls to partner banks' IP blocks and blocking internal ranges or the cloud metadata IP
169.254.169.254to prevent SSRF (Server-Side Request Forgery, tricking a server into fetching internal URLs). Crucially, the egress proxy checks the resolved IP right before opening the TCP socket, defeating DNS rebinding (where an attacker's domain resolves to a safe public IP during validation and switches to169.254.169.254milliseconds later at connect time).
Functional and non-functional targets
- Support exact addresses, CIDR prefixes (Classless Inter-Domain Routing blocks such as
172.20.4.0/24, where the top 24 bits are fixed and the remaining 8 bits cover172.20.4.0through172.20.4.255), and arbitrary inclusive[start, end]ranges across both IPv4 and IPv6. - Attach an action (
allow/deny), priority, scope(environment, direction, tenant, application), optional expiration, author, and reason to every rule. - Latency and autonomy: In-process lookups take microseconds (<= 1 ms p99 via local sidecar) and never call the central management service on the request path; if the management plane goes completely offline, traffic filtering keeps running on its local rule snapshot.
- Propagation speed: Routine staged rollouts reach >= 99% of enforcement points within 2 minutes per stage; emergency blocks reach >= 99% of connected points within 30 seconds.
- Inbound at the edge proxy / API gateway: Filters on the client's source IP. Behind a CDN or load balancer, the direct TCP peer is the balancer itself, so we extract the client IP from the load balancer's
Back-of-the-envelope numbers
Fleet & request load enforcement points 4 regions x ~1,250 hosts = ~5,000 agents (edge, sidecar, egress) total decisions ~200,000 decisions/s at global peak (~2,000-5,000/s on a busy edge proxy) Rule volume operator & tenant ~50,000 rules (~500 edits/day) automated threat feeds ~500,000 prefixes (refreshed hourly, 1-5% daily churn) design ceiling N = 1,000,000 active rules Compiled lookup table size (worst case: 1,000,000 rules in a single table) disjoint segments N rules create at most 2N endpoints -> at most 2N + 1 = ~2,000,001 segments if 100% IPv4 4 B start IP + 4 B rule index = 8 B/segment -> ~16 MB if 100% IPv6 16 B start IP + 4 B rule index = 20 B/segment -> ~40 MB typical 80/20 mix ~20 MB per full snapshot (shared feed table is ~8 MB stored once per host) lookup work binary search over 2M entries = ceil(log2(2,000,001)) = 21 array probes -> ~1-2 microseconds even with CPU cache misses Distribution & audit logs simultaneous cold pull 20 MB x 5,000 hosts = 100 GB -> serve via regional caches + small KB deltas logged decisions all denies (~2% = 4,000/s) + 1% sampled allows (~2,000/s) = 6,000 events/s 6,000/s x 150 B = 0.9 MB/s = ~78 GB/dayWhat these numbers tell us: Evaluating 1,000,000 rules in 2 microseconds in local RAM is completely feasible once overlapping rules are pre-compiled into flat, sorted segments. The real engineering challenges are unambiguous precedence rules, safe global distribution to 5,000 machines, and explainable, privacy-safe audit logs.
Normalize addresses and define rule precedence and fail modes
1. Canonical binary address normalization: String representations never touch the hot lookup path. IPv4 addresses become 32-bit unsigned integers (
0to2^32 - 1) and IPv6 addresses become 128-bit unsigned integers (0to2^128 - 1), and every rule becomes an inclusive integer interval(family, start, end).- Dual-stack unwrapping: Dual-stack OS sockets report IPv4 clients as IPv4-mapped IPv6 addresses (
::ffff:198.51.100.7). At decision time we unwrap::ffff:0:0/96to IPv4 (family = 4) so an IPv4 rule for198.51.100.7is never bypassed. - Strict authoring validation: Reject ambiguous rule strings up front — leading-zero octets like
010.1.1.1(parsed as octal8by legacy C libraries), link-local zone IDs (fe80::1%eth0), IPv4-mapped rule inputs (require plain IPv4 notation), and CIDRs with non-zero host bits like172.20.4.19/24(almost always a human typo for172.20.4.19/32or172.20.4.0/24).
import ipaddress def normalize_request_ip(raw_text: str) -> tuple[int, int]: """Convert a live request IP into (family, unsigned_int), unwrapping ::ffff:a.b.c.d to IPv4.""" # Strip any OS interface zone suffix like "%eth0" seen on local sockets. clean_text = raw_text.split("%")[0] addr = ipaddress.ip_address(clean_text) if addr.version == 6 and addr.ipv4_mapped is not None: addr = addr.ipv4_mapped return addr.version, int(addr) def parse_rule_bounds(rule_text: str) -> tuple[int, int, int]: """Validate an authored rule string and return inclusive (family, start_int, end_int).""" text = rule_text.strip() if "%" in text: raise ValueError(f"Zone IDs are forbidden in filter rules: {rule_text}") if "-" in text: parts = text.split("-") if len(parts) != 2: raise ValueError(f"Invalid IP range format: {rule_text}") low = ipaddress.ip_address(parts[0].strip()) high = ipaddress.ip_address(parts[1].strip()) if low.version != high.version or int(low) > int(high): raise ValueError(f"Range endpoints must share family with start <= end: {rule_text}") else: # strict=True (default) rejects host bits set, e.g., "172.20.4.19/24", and leading zeros. net = ipaddress.ip_network(text, strict=True) low, high = net.network_address, net.broadcast_address if low.version == 6 and (low.ipv4_mapped is not None or high.ipv4_mapped is not None): raise ValueError(f"Author IPv4 rules directly instead of IPv4-mapped IPv6: {rule_text}") return low.version, int(low), int(high)2. Deterministic conflict precedence (settle overlap rules before choosing a lookup structure): Suppose
R1isdeny 172.16.0.0/12 (priority 100)andR2isallow 172.20.4.0/24 (priority 200). What happens to172.20.4.19?Precedence Policy Winner for 172.20.4.19 Why It Can Surprise You -------------------------------------- ---------------------- ---------------------------------------------- Longest-prefix match (router style) R2 -> ALLOW A tenant's /32 allow punches through a /12 security block! Deny-overrides (firewall style) R1 -> DENY Impossible to carve out a legitimate /28 partner exception Explicit priority bands + tie-breakers R1 -> DENY Security band (100-999) always outranks tenant band (1000+)We choose explicit priority bands (
0-99emergency,100-999security,1000-4999tenant,5000-9999app) with total tie-breaking so load order never matters: (1) lowest priority number wins -> (2)denybeatsallow-> (3) narrower range (end - start + 1) wins -> (4) lowestrule_idwins. If nothing matches, the scope's default action applies.3. Scope, fail modes, and ahead-of-time expiration: Each scope
(environment, direction, tenant, application)defines both its unmatched default and its cold-boot fail policy (fail-open, allowing traffic when no valid snapshot exists at all, vs. fail-closed, blocking traffic):Protected Traffic Scope Default (No Match) Cold-Boot / No Usable Snapshot --------------------------------- ------------------- -------------------------------------------- Public consumer API (inbound) ALLOW Fail-open (allow + page SRE; auth still runs) Partner webhook/API (allowlisted) DENY Fail-closed (deny) Internal admin / ops tools DENY Fail-closed (deny) Outbound partner-bank payouts DENY Fail-closed (deny)Because a pre-compiled lookup table stores only the single winning rule per segment (not the runner-up if that rule expires), agents do not skip expired rules dynamically at lookup time. Instead, whenever a rule carries
expires_at, the compiler pre-publishes a companion next snapshot witheffective_from = expires_at, allowing agents to cut over locally on time even if disconnected from the control plane.- Dual-stack unwrapping: Dual-stack OS sockets report IPv4 clients as IPv4-mapped IPv6 addresses (
APIs: Local decision call and control-plane workflow
We split the system into a data plane (the local library or sidecar executing per-request lookups in memory) and a control plane (the administrative service where operators edit, simulate, approve, and publish rules).
DATA-PLANE CALL (in-process library or local Unix-domain socket; zero network hops) decide(scope, direction, raw_ip) -> Decision { action: ALLOW | DENY, reason: RULE | DEFAULT | STALE_POLICY | NO_SNAPSHOT, rule_id: int | None, rule_version: int | None, snapshot_version: int, # monotonic main snapshot version overlay_version: int # monotonic emergency-block version (0 if none) } CONTROL-PLANE HTTP API (SSO + MFA, role-checked per scope and priority band) POST /v1/rules create draft rule PATCH /v1/rules/{id} create new draft version of rule POST /v1/changesets bundle rule drafts into one atomic change POST /v1/changesets/{id}:simulate estimate traffic impact against 7-day logs POST /v1/changesets/{id}:approve second-person approval (mandatory in prod) POST /v1/changesets/{id}:publish compile, sign, start staged rollout -> snapshot_version GET /v1/rollouts/{snapshot_version} ack progress & stale host list per region/stage POST /v1/rollouts/{snapshot_version}:rollback compile & push version V+1 with V-1's rule content POST /v1/emergency-blocks narrow, expiring, signed deny-only overlay GET /v1/explain?scope=...&direction=...&ip=...&snapshot_version=...Notice two deliberate API invariants:
decide()always returnssnapshot_versionandoverlay_versionso application and audit logs know the exact rule snapshot used, and rollback creates a higher versionV + 1rather than reusingV - 1so agents strictly enforcenew_version > active_versionand reject replayed old snapshots.Separate authoring storage from compiled serving snapshots
Operators need rich relational auditability (who wrote a rule, which ticket approved it, full version history), whereas proxies on the request path need a compact, pre-validated byte array they can swap in one CPU instruction. A compiler bridges the two models:
CONTROL-PLANE STORE (PostgreSQL — strong ACID transactions, low write rate) rules rule_id PK, owner_team, latest_version, created_at rule_versions PK (rule_id, version) — immutable rows: scope fields (env, direction, tenant, app), family, start_bin, end_bin, canonical_text, action, priority, expires_at, state, author, approver, reason, ticket changesets changeset_id PK, rule_version_refs[], sim_report_id, author, approver, state snapshots snapshot_version PK (monotonic), changeset_id, effective_from, sha256_hash, kms_key_id, cryptographic_signature, created_at enforcement_points point_id PK, region, kind, subscribed_scopes[], active_version, last_heartbeat_at rollout_acks PK (snapshot_version, point_id) -> status (APPLIED | REJECTED), agent_applied_at, server_received_at audit_log append-only hash-chained log of every control-plane mutation DATA-PLANE COMPILED SNAPSHOT (immutable binary blob per snapshot_version) header snapshot_version, effective_from, sha256_hash, kms_key_id, signature shared_table global '*' rules (500k threat-feed prefixes + global security rules) ipv4_starts: u32[], ipv4_winners: u32[] ipv6_starts: u128[], ipv6_winners: u32[] scope_tables[] per subscribed scope: (default_action, fail_mode, max_staleness_sec, ipv4_starts, ipv4_winners, ipv6_starts, ipv6_winners) rule_metadata[] compact array indexed by winner_idx -> (rule_id, rule_version, action, precedence_tuple)Keeping author names, ticket IDs, and free-text comments out of the binary snapshot shrinks downloads and avoids leaking internal security notes if an edge host is compromised.
High-level architecture
CONTROL PLANE (Primary Region + Warm Standby) Operators / Threat Feeds | (SSO + MFA, scoped RBAC) v [ Rules & Changeset API ] ---> [ PostgreSQL: rules, changesets, acks, hash-chained audit ] | +--> [ Traffic Simulator ] <--- 7-day prefix-aggregated logs & shadow-stage counters v [ Rule Compiler ] --(signs digest via KMS/HSM)--> [ Immutable Object Store (Snapshots & Deltas) ] | | v v [ Rollout Controller ] ---- target stage versions ----> [ 4 Regional Distributors ] ^ (blob/delta cache + gRPC push + signed heartbeats) | acks (version, server_received_at) | | v +---------------------------------------------- [ Local Agent on 5,000 Hosts ] - verify KMS signature, hash & monotonic version - deserialize off hot path & atomic pointer swap - persist Last-Known-Good (LKG) snapshot on local disk | decide() in local RAM (~1-2 us) | Edge Proxy / Service Sidecar / Egress Proxy | sampled privacy-safe logs + 100% rule hit metrics v [ Log & Metrics Store ] --> Explain API & AlertsDeep dive: Compile overlapping rules into disjoint segments
Why not use a standard router prefix trie or an interval tree on the hot path? Let's compare all four candidate data structures directly:
Data Structure Rule Shapes Built-in Precedence Lookup Work (N = 1M rules) --------------------------- ------------- ---------------------- --------------------------------------- Exact-match hash map Single IPs None O(1), cannot match subnets or ranges Binary / multibit trie CIDRs only Longest-prefix match Up to 32/128 steps (or 4/16 in 8-bit stride), must inspect all ancestor nodes for priority & split arbitrary ranges into <= 62/254 CIDRs Interval tree Any range None (returns overlaps) O(log N + K) — scans all K matching rules! Compiled disjoint segments Any range Any policy (pre-solved) O(log N) = <= 21 binary-search steps, 1 winnerHow disjoint segment compilation works: Imagine drawing overlapping rules as horizontal bars over the integer number line
[0, 255], sayR1: deny [20, 120] (prio 100)andR2: allow [40, 60] (prio 200). If we slice vertically at every rule'sstartandend + 1, the set of active rules inside each slice never changes — so the compiler picks one winner per slice, and adjacent slices with the same winner merge automatically:Addresses: 0 20 40 61 121 255 R1 (p=100): |--------- DENY (prio 100) ---------| R2 (p=200): |- ALLOW -| Raw slices: [0..19:-] [20..39:R1][40..60:R1][61..120: R1 ][121..255: - ] Merged: starts = [0, 20, 121] winners = [None, R1, None] <-- R2 wins 0 segments (compiler flags R2 as shadowed!)We compute these merged segments in
O(N log N)time (~1–2 seconds for 1M rules) using a sweep-line algorithm (walking sorted cut points left-to-right) paired with a min-heap and lazy deletion (leaving expired rules inside the heap until they bubble to the top, since buried rules cannot affect the current winner):import bisect import heapq def precedence_key(rule) -> tuple[int, int, int, int]: """Smaller tuple wins: priority -> deny(0) before allow(1) -> range size -> rule_id.""" action_order = 0 if rule.action == "deny" else 1 span_size = rule.end - rule.start + 1 return (rule.priority, action_order, span_size, rule.rule_id) def compile_table(rules: list, family_max: int) -> tuple[list[int], list]: """Flatten overlapping rules into sorted segment starts[] and single winners[].""" # Collect every boundary where the winning rule could possibly change. cut_points = set() for rule in rules: cut_points.add(rule.start) # Guard against overflowing family_max (2**32 - 1 or 2**128 - 1) when a rule hits the top IP. if rule.end < family_max: cut_points.add(rule.end + 1) sorted_rules = sorted(rules, key=lambda r: r.start) starts = [0] winners = [None] # active_heap stores (precedence_key, rule.end, rule.rule_id), ordered by highest precedence. active_heap = [] rule_idx = 0 for point in sorted(cut_points): # 1. Push every rule whose interval starts at or before this cut point. while rule_idx < len(sorted_rules) and sorted_rules[rule_idx].start <= point: r = sorted_rules[rule_idx] heapq.heappush(active_heap, (precedence_key(r), r.end, r.rule_id)) rule_idx += 1 # 2. Lazy deletion: pop top rules whose end address is already strictly behind `point`. while active_heap and active_heap[0][1] < point: heapq.heappop(active_heap) best_rule_id = active_heap[0][2] if active_heap else None # 3. Coalesce adjacent slices that share the exact same winning rule. if best_rule_id == winners[-1]: continue if starts[-1] == point: winners[-1] = best_rule_id else: starts.append(point) winners.append(best_rule_id) return starts, winners def lookup_segment(starts: list[int], winners: list, ip_int: int): """Find the single winning rule_id in O(log N) via rightmost binary search.""" segment_idx = bisect.bisect_right(starts, ip_int) - 1 return winners[segment_idx]Keeping memory small across scopes + atomic swap: Global
*rules (the 500k threat feeds) live in oneshared_tableper host, while tenant/app rules live in tiny per-scope tables. At lookup time, the agent runslookup_segmenton bothshared_tableand the scope's table and picks whichever returned rule has the smallerprecedence_key— exact mathematically, using two binary searches instead of duplicating 8 MB of threat feeds across 50 scopes. When a new snapshot arrives, a background thread builds the new immutable object in fresh memory, verifies its SHA-256 and signature, and swaps a single atomic reference pointer so in-flight requests never see half-updated rules.Propagate updates safely and handle disconnected hosts
1. Distribution, verification, and measurable staleness: Agents keep persistent gRPC streams to regional distributors (with a 30-second HTTP poll fallback). Every 30 seconds, distributors forward a control-plane-signed heartbeat
{stage_target_version, issued_at}so an agent can distinguish "no rule edits today" from "my network link is severed." Before swapping, every agent checks: (1) valid signature from a pinned KMS (Key Management Service, hardware-backed signing keys never exported from cloud security modules) key, (2)new_version > active_version, (3) matchingsha256_hash, and (4) non-empty table sanity for previously populated scopes. Agents then sendAPPLIEDorREJECTEDacks; the control plane stampsserver_received_aton arrival so rollout lag metrics never trust skewed host clocks.2. Staged rollout, monotonic rollback, and Last-Known-Good (LKG) behavior:
Normal Staged Rollout (~45 min total) Stage 0: Shadow (all hosts evaluate V alongside V-1, enforce V-1, emit diff counts) 10 min Stage 1: Canary (1% of hosts in 1 region enforce V) 10 min Stage 2: Full single region 15 min Stage 3: Remaining regions (gated on >= 99% ack, stable p99 latency & 403 rates) Disconnected / Stale Agent Behavior Heartbeat < 2 min old -> Healthy: enforce active snapshot 2 min .. max_staleness (1 h) -> Enforce LKG snapshot, tag Decision.reason = STALE_POLICY, alert > max_staleness (1 h) -> Page on-call; keep LKG on public scopes, optional deny-all on admin scopes Process restart while offline -> Load & verify signed LKG snapshot from local disk Fresh host with empty disk -> Stay unready in load balancer; apply per-scope fail-open / fail-closedIf a canary gate trips, rollback compiles version
V + 1containingV - 1's rules and pushesV + 1to all stages immediately — preserving monotonic version numbers so nobody can replay stale snapshots.3. Unauthorized-change defense and the fast emergency block path: Standard production changes require SSO+MFA, per-band RBAC, and two-person approval. During an active attack, on-call security engineers use a dedicated break-glass endpoint (
POST /v1/emergency-blocks) that skips simulation and staged waits while keeping signing and auditing intact:- Guardrails:
deny-only, priority band0-99, each block no wider than IPv4/16or IPv6/32, <= 1,000 prefixes, mandatory TTL <= 24 hours, and automatic rejection if it overlaps aprotected_networksallowlist (load-balancer health checks, partner banks, corporate VPN) without a second approver. - Fast overlay mechanics: Instead of recompiling all 1,000,000 rules, the compiler signs a tiny KB-sized emergency overlay (
overlay_version + 1) in ~1 second and pushes it to all 4 regions in parallel (~2–3 seconds). Agents check the overlay first; because band0-99isdeny-only and outranks every other band, an overlay hit immediately returnsDENYwith identical semantics to a full recompile, reaching connected hosts in ~3–5 seconds and stream-disconnected hosts on their next 30-second poll (~35 seconds).
- Guardrails:
Audit decisions, guard privacy, and test interval boundaries
1. Versioned, privacy-conscious decision logs: A log entry can only explain a past block if it records the exact compiled version active on that host at that microsecond, while avoiding raw PII or request payloads:
Decision Log Record (~150 B; 100% of denies [rate-capped per rule] + 1% of allows) timestamp, point_id, region, scope, direction, request_id action, reason, rule_id, rule_version, snapshot_version, overlay_version ip_prefix IPv4 truncated to /24, IPv6 truncated to /48 (network-level visibility) ip_token HMAC(daily_rotating_key, full_ip_bytes) -> correlates single-IP bursts within 24 h; daily keys are destroyed after 30 days so tokens become irreversible omitted HTTP bodies, headers, cookies, URL query strings, user IDsWhen support investigates a blocked customer who supplies their IP,
GET /v1/explainloads archivedsnapshot_version(kept >= 1 year), evaluates both the human-readablerule_versionsand the archived binary blob, lists every matching rule in precedence order, and alerts SRE if the two representations ever disagree.2. Two-tier pre-promotion diffing: Offline simulation runs candidate rules against 7 days of
/24- and/48-aggregated logs to flag broad mistakes before approval; then Stage-0 online shadow evaluation runs inside agents against live, full in-memory IPs and emits only aggregate flip counters per(old_rule, new_rule, scope, /24)— giving 100% exact impact diffs without ever writing full user IPs to disk.3. Boundary and differential testing (probe adjacent neighbors at every endpoint): Off-by-one bugs hide right at
start - 1andend + 1(such as treating broadcast.255as outside a/24, or overflowing2^32 - 1 + 1on255.255.255.255/32):def boundary_test_addresses(rule, family_max: int) -> list[int]: """Return start-1, start, end, and end+1 clipped safely to [0, family_max].""" candidates = [rule.start - 1, rule.start, rule.end, rule.end + 1] valid_points = [] for addr in candidates: if 0 <= addr <= family_max: valid_points.append(addr) return valid_pointsCI runs four automated suites on the compiler: (1) boundary probes on
/0,/32,/128,0.0.0.0, andfamily_max; (2) nested/12+/24combinations across lower, equal, and higher priorities; (3) normalization rejections (010.1.1.1,172.20.4.19/24,%eth0) plus::ffff:198.51.100.7dual-stack matching; and (4) randomized differential testing checking thatlookup_segmentmatches a trivial brute-force loop over raw rules at every boundary point across thousands of random rule sets.Operations, failure recovery, metrics, and trade-offs summary
- Automated hourly threat feeds without human fatigue: Feed updates bypass human two-person approval only if automated policy gates pass:
deny-only in sub-band900-999(so security overrides at100-899still beat false positives, while tenants at1000+cannot bypass feeds), zero overlap withprotected_networks, <= 10% prefix churn, and a mandatory 48-hour expiry so a dead feed cleans itself up. - Safe rule retirement: Rules with 0 hits over 90 days (from 100% in-agent per-rule Prometheus counters) or rules flagged by the compiler as completely shadowed notify their owner, move to
DISABLEDthrough a simulated changeset (verifying 0 diff), wait 30 days for instant one-click restore, and then move toRETIRED. - Key operational alerts: Decision p99 latency by host kind; publish-to-applied rollout lag (> 2 min normal, > 30 s emergency); count of stale hosts (> 2 min and > 1 h) and distinct active snapshot versions; per-rule hit spikes (> 10x 7-day baseline or > 2x simulation forecast); and any rejected snapshot signature/hash (immediate security page).
Core design trade-offs recap:
- Priority bands + deterministic tie-breaks vs. longest-prefix tries: Authors choose explicit priorities, preventing tenant
/32rules from punching holes in security/8blocks and supporting arbitrary non-CIDR ranges cleanly. - Pre-compiled disjoint segments vs. runtime interval/trie walks: Paying ~1–2 seconds at publish time buys a worst-case 21-step binary search in local RAM regardless of how many rules overlap.
- Local pushed snapshots + LKG vs. centralized RPC: Accepting bounded, heartbeat-measured staleness eliminates network latency and keeps every service running through total control-plane outages.
- 45-minute staged rollouts + narrow KB emergency overlay: Routine edits get shadow and canary safety nets, while active attacks get 3–5 second global blocks under strict scope and TTL guardrails.
- Automated hourly threat feeds without human fatigue: Feed updates bypass human two-person approval only if automated policy gates pass:
Intuition & how it works
Think of an IP address filtering service like running passport and watchlist checks across 5,000 airport boarding gates in four countries. Headquarters (the control plane) is where supervisors carefully draft rule changes, check that a new rule won't accidentally ground an entire partner airline, require a second supervisor's signature, and print a numbered edition of the rulebook. Each boarding gate (the data plane) keeps a pre-sorted, flat lookup sheet right at the desk so an agent can check any traveler in microseconds — even if headquarters loses internet connectivity for an hour — and stamps the exact rulebook edition number onto every denial slip so an auditor can reconstruct the decision months later.
Three obvious designs fail quickly at production scale. Calling a central filtering microservice over the network on every request adds milliseconds of latency and turns a single control-plane outage into a company-wide outage. Scanning a list of 1,000,000 rules in memory per request is way too slow, while storing rules in a router-style prefix trie (a binary tree walked bit-by-bit along an IP address) naturally implements longest-prefix match — which lets a tenant's narrow /32 allow rule silently override a security team's broader /8 block and cannot represent arbitrary non-CIDR ranges without splitting them into dozens of pieces.
Walk through a concrete two-rule example to see how our design solves conflict resolution, compilation, and lookup end to end:
- Authoring & precedence: Security creates
R1: deny 172.16.0.0/12 (priority 100)and a tenant createsR2: allow 172.20.4.0/24 (priority 200). Under our deterministic precedence policy (lowest priority number wins ->denybeatsallow-> smaller range -> lowestrule_id),R1beatsR2across the entire172.16.0.0–172.31.255.255range. - Offline segment compilation: Instead of resolving overlaps on every HTTP request, the compiler slices the 32-bit IPv4 integer line at every rule's
startandend + 1using a sweep-line min-heap, producing just three disjoint segments:[0.0.0.0 -> None, 172.16.0.0 -> R1, 172.32.0.0 -> None]. NoticeR2wins zero segments, so the compiler immediately warns the reviewer thatR2is completely shadowed! - Signed push & atomic swap: The compiler signs
snapshot_version = 57using a hardware-backed KMS (Key Management Service) key and pushes it through regional distributors. Each host verifies the signature and57 > active_version, builds the new array off the hot path, and swaps one pointer atomically. - Microsecond lookup & versioned audit: A client connects on a dual-stack socket from
::ffff:172.20.4.19. The proxy unwraps the IPv4-mapped IPv6 address to IPv4172.20.4.19, runs a binary search overstarts(landing on172.16.0.0), and immediately returnsDENYwhile logging(rule_id=R1, snapshot_version=57, ip_prefix=172.20.4.0/24).
Key trade-offs
- Explicit priority bands + tie-breakers vs. longest-prefix match or deny-overrides. Longest-prefix match is great for IP packet routing, where more specific routes should win, but dangerous in multi-tenant security where a tenant's
/32allow must never punch through a security/8block. Pure deny-overrides prevents bypasses but cannot express "block this cloud provider's/12except one vetted partner's/28." Priority bands (0-99emergency,100-999security,1000-4999tenant,5000-9999app) require explicit numbering in exchange for expressive, unambiguous control over any range shape. - Pre-compiled disjoint segments vs. runtime tries or interval trees. Pre-compiling
Nrules takesO(N log N)work (~1–2 seconds for 1M rules) and up to2N + 1array entries (~16–40 MB worst case), requiring a recompile when rules change. In return, per-request evaluation drops to a bounded binary search (<= 21 probes for 2M segments) with zero sensitivity to how deeply rules overlap. - Local in-process evaluation vs. a centralized decision RPC. Pushing snapshots to 5,000 agents means rules propagate asynchronously over seconds and staleness must be tracked via signed heartbeats. The payoff is microsecond latency, zero extra network hops, and 100% data-plane survival when the control plane is down.
- Per-scope fail-open vs. fail-closed defaults. Failing open on Last-Known-Good (LKG) rules protects the public customer API from total outages, whereas failing closed on partner IP allowlists, admin tools, and bank payout egress prioritizes preventing unauthorized access over uptime.
- 45-minute staged rollouts vs. a narrow emergency overlay. Shadowing and canarying normal changes catches typos before global impact, while an active attack uses a separate signed KB-sized
deny-only overlay (band0-99, <=/16IPv4 or/32IPv6, <= 24 h TTL) to achieve 3–5 second global enforcement without weakening verification or auditability. - Privacy-reduced logs + in-agent shadow diffs vs. logging raw client IPs. Storing
/24or/48prefixes plus daily-rotated HMAC tokens (keyed hashes that correlate one IP within a day and become irreversible once the daily key is deleted) avoids retaining sensitive raw IPs and request payloads while still enabling abuse correlation, exact Stage-0 shadow diffing in agent memory, and deterministic replay when a user supplies their IP to support.
Common mistakes
- Picking a prefix trie before defining conflict semantics, accidentally locking the product into longest-prefix match and then struggling to bolt on priority bands and arbitrary
[start, end]ranges. - Comparing IPs as strings or skipping canonical normalization, such as letting
::ffff:198.51.100.7slip past an IPv4 rule for198.51.100.7, misparsing leading-zero octets like010.1.1.1as octal8, or silently masking typos like172.20.4.19/24instead of rejecting them. - Trusting the leftmost address in
X-Forwarded-For, which any external client can spoof trivially, instead of parsing right-to-left across trusted proxy hops (or checking post-DNS socket IPs on outbound egress to stop DNS rebinding). - Off-by-one boundary and integer-overflow bugs, such as treating
endas exclusive, dropping a subnet's broadcast address, or computingrule.end + 1unconditionally whenrule.end == 2^32 - 1(255.255.255.255) in a fixed-width 32-bit integer. - Mutating live in-memory lookup structures in place, exposing concurrent request threads to partially updated state or crashes instead of building an immutable snapshot and swapping one atomic reference.
- Implementing rollback by re-publishing an old version number (
V - 1), which forces agents to accept lower version numbers and opens a replay vulnerability where an attacker or stale cache can downgrade security rules. - Dropping to blanket "allow all" when disconnected from the control plane, rather than continuing to enforce the verified Last-Known-Good snapshot on disk.
- Logging
ALLOW/DENYwithoutsnapshot_versionandoverlay_version, making post-incident audits guesswork once rules have been edited or expired.
Follow-up questions
- How should the system handle an arbitrary inclusive IP interval that does not align to a single CIDR boundary? Keep arbitrary ranges natively as inclusive
(start_int, end_int)pairs in both the authoring database and our compiled disjoint-segment array, which handles any integer interval directly without splitting. When targeting an enforcement backend that only accepts CIDR prefixes (such as a Linux kernel LPM map or cloud WAF), decompose each already-flattened disjoint segment at compile time into the minimal exact set of aligned CIDR blocks — which takes at most2W - 2prefixes forW-bit addresses (62for IPv4,254for IPv6), such as decomposing192.0.2.5–192.0.2.20into192.0.2.5/32,192.0.2.6/31,192.0.2.8/29,192.0.2.16/30, and192.0.2.20/32. Decomposing after flattening overlaps is crucial so precedence is already baked in and the emitted CIDRs never overlap. - What is the fastest end-to-end propagation time achievable for an urgent global block rule, and how do you verify every region is enforcing it? Compiling and KMS-signing a tiny KB-sized emergency overlay takes ~1 second, streaming it via gRPC to all four regional distributors and down to connected agents takes ~2–3 seconds, and local signature verification plus pointer swap takes milliseconds — reaching connected hosts in ~3–5 seconds and stream-interrupted hosts on their 30-second fallback poll (~35 seconds), comfortably meeting a 30-second p99 SLA for connected points. To prove activation without trusting host clocks, every agent sends a signed acknowledgment
(point_id, overlay_version, sha256_hash)stamped with the control plane'sserver_received_at, powering a live per-region completeness tally that names every unacknowledged host (and drains long-disconnected hosts from load balancers). In addition, synthetic regional probes query each agent's local admin socket with a test IP inside the blocked prefix to verifyDENYwith the newoverlay_version. - How does your data-plane design shift if filtering runs inside the OS kernel versus an L7 edge gateway? In the Linux kernel via eBPF/XDP (sandboxed bytecode running directly inside the network driver before socket allocation), data structures are restricted to fixed-size kernel maps such as longest-prefix-match (
BPF_MAP_TYPE_LPM_TRIE) maps, and the hook sees only raw packet source IPs (usable only where no upstream load balancer hides the client IP). The compiler therefore emits disjoint CIDR prefixes with winners pre-resolved, swaps maps atomically via a map-of-maps pointer update, and aggregates hit counts in per-CPU ring buffers. At an HTTP L7 edge proxy or third-party CDN, you gain visibility into trustedX-Forwarded-Forhops and URL routes (enabling per-tenant/per-app scopes and clean HTTP403error bodies withrequest_ids), though third-party CDNs impose strict rule-count caps and vendor propagation delays that you must track via embedded snapshot-version headers and external canary probes. - What safeguards catch a misconfigured rule before or shortly after it blocks traffic from a major customer subnet? Defense runs across three phases: before publish, static policy checks block or require security sign-off on prefixes wider than IPv4
/16or IPv6/32and any overlap with aprotected_networksregistry (major customer/partner ASNs, health checkers, corporate offices), while 7-day log simulation plus Stage-0 online shadow diffing quantify the exact percentage of traffic and top/24networks flipping fromALLOWtoDENY. During staged rollout, automated canary gates compare per-scope deny rates and partner403rates against the shadow forecast and halt/rollback automatically on deviation. After rollout, streaming anomaly detectors monitor 100% per-rule hit counters and page on-call whenever a rule exceeds 10x its 7-day baseline or 2x its simulated hit rate, while automated threat-feed entries overlappingprotected_networksare quarantined automatically before compilation.
Follow-up questions
- How should the system handle an arbitrary inclusive IP interval that does not align to a single CIDR boundary?
- What is the fastest end-to-end propagation time achievable for an urgent global block rule, and how do you verify every region is enforcing it?
- How does your data-plane design shift if filtering runs inside the OS kernel versus an L7 edge gateway?
- What safeguards catch a misconfigured rule before or shortly after it blocks traffic from a major customer subnet?
Similar questions
- Cross-Border Remittance Cost Comparison Engine
- Scalable Production Link Shortening Service
- Architecture Walkthrough and Deep Dive on a Past System
- Stepping Beyond Your Scope and Owning an Engineering Failure
- Settle Net Account Balances
- Preventing Schedule Slips and Pivoting Mid-Project
More Remitly interview questions
- Cross-Border Remittance Cost Comparison Engine Medium
- Stepping Beyond Your Scope and Owning an Engineering Failure Medium
- Settle Net Account Balances Easy Pro
- Preventing Schedule Slips and Pivoting Mid-Project Easy Pro
- Scalable Production Link Shortening Service Hard Pro
- Single-Queue Elevator Stop Scheduler Medium Pro
- Preparing for a Cross-Functional PM Collaboration Interview Easy Pro
- Finding k Nearest Geographic Locations Medium Pro
- Bijective Character Cipher Check Medium Pro
- Architecture Walkthrough and Deep Dive on a Past System Hard Pro