Firewall Rule Engine with Prefix Matching
Data Structure DesignModel answerLast updated
Build a rule-based IP filter supporting CIDR blocks, priority resolution, and efficient queries for single IPs and prefix ranges.
You are implementing a firewall rule engine that filters traffic based on IP addresses and CIDR blocks.
First, explain what CIDR notation represents and provide two concrete examples showing how to convert a CIDR string into its corresponding 32-bit integer range and subnet mask.
Then, design and implement a data structure to manage firewall rules where each rule consists of:
- A CIDR prefix (e.g., "10.0.0.0/8")
- An action: either "allow" or "deny"
- A priority value (lower number = higher priority)
Your implementation must support:
-
Basic operations:
addRule(rule)— insert a new ruleremoveRule(ruleId)— delete a rule by IDquery(ipAddress)— determine the action for a single IP
-
Matching semantics: Support both strategies and clarify which you're using:
- Longest prefix match: The most specific (longest) matching prefix wins; ties broken by priority
- First match by priority: Among all matching rules, the highest priority wins
-
Performance targets:
- Handle up to 1,000,000 rules
- Support 100,000 queries per second
- Specify time and space complexity for each operation
-
Extended queries (follow-up): Instead of querying a single IP, the query is now a CIDR block. Implement:
overlap(queryPrefix)— does any rule overlap with this prefix?coveredByAllow(queryPrefix)— are all IPs in this prefix allowed?coveredByDeny(queryPrefix)— are all IPs in this prefix denied?listConflictingRules(queryPrefix)— return rule IDs that overlap this prefix and have conflicting actions
Discuss:
- Which data structures enable efficient range and overlap queries?
- How would your design extend to IPv6 addresses (128 bits)?
- What are the key trade-offs and edge cases?
Hints
Hint 1
CIDR blocks either nest completely or don't overlap at all—this structure maps naturally to a tree where each rule lives at a specific depth
Hint 2
A binary trie indexed by IP address bits places matching rules exactly on the path from root to the queried IP
Hint 3
For range queries, ancestors of a node represent containing blocks while descendants represent contained blocks
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding CIDR Notation
CIDR (Classless Inter-Domain Routing) notation a.b.c.d/n represents all IPv4 addresses where the first n bits match the given address. The remaining 32 - n bits are variable, yielding 2^(32-n) total addresses.
Conversion process:
- Construct the 32-bit integer:
ip = a×2²⁴ + b×2¹⁶ + c×2⁸ + d - Build the subnet mask:
mask = 0xFFFFFFFF << (32 - n) - Normalize to network address:
start = ip & mask - Find the range end:
end = start | (~mask & 0xFFFFFFFF)
Example 1: 172.16.0.0/12
- Integer form:
172×2²⁴ + 16×2¹⁶ = 2886729728 - Mask:
0xFFF00000(binary: 20 ones, 12 zeros) =255.240.0.0 - Range:
[2886729728, 2887778303]representing172.16.0.0through172.31.255.255 - Contains 2²⁰ = 1,048,576 addresses
Example 2: 203.0.113.0/24
- Integer:
3405803776 - Mask:
0xFFFFFF00=255.255.255.0 - Range:
[3405803776, 3405804031]covering 256 addresses
Core Design: Binary Trie
Key insight: CIDR blocks have a crucial property—two blocks either nest completely or are disjoint. They never partially overlap. This makes a bit-indexed trie the natural choice.
Structure:
- Each rule is stored at the trie node corresponding to its prefix length
- Walking from root following the IP's bit pattern visits all matching rules
- Child pointers represent the next bit:
children[0]for bit=0,children[1]for bit=1
Node fields:
class TrieNode:
rules: Dict[id -> (priority, sequence, action)]
best_local: (priority, sequence, id) # winning rule at this node
children: [left, right]
subtree_count: int
subtree_best: (priority, sequence) # best priority anywhere below
Matching Semantics
Longest Prefix Match (LPM):
- Walk the IP's 32-bit path
- Among nodes with rules, the deepest one wins
- If multiple rules exist at the winning node, use the lowest priority
Priority-Based (First Match):
- Walk the IP's path collecting all matching rules
- Select the rule with minimum
(priority, insertion_sequence) - Earlier insertion breaks ties at the same priority level
Both require O(32) time per query—walking the path and tracking the current best match.
Operations
addRule(prefix, action, priority):
- Parse CIDR and walk/create trie path for the first
nbits - Insert rule at the target node with unique ID and sequence number
- Update
best_localat that node - Propagate
subtree_countandsubtree_bestback up to root
- Complexity: O(32 + k) where k = rules at that exact prefix
removeRule(id):
- Locate the rule (maintain a separate id-to-node map)
- Remove from node's rule dictionary
- Recompute
best_localamong remaining rules - Propagate count and priority updates upward
- Complexity: O(32 + k)
query(ip):
- Walk the 32-bit path
- In LPM mode: track deepest node with rules
- In priority mode: track minimum priority seen
- Return the winning action or default if no match
- Complexity: O(32)
Extended Queries (Block-Level)
overlap(queryPrefix):
- Walk to the query block's node
- Return true if any ancestor has rules OR
subtree_count > 0 - Complexity: O(32)
coveredByAllow / coveredByDeny:
- Walk to the query node, inheriting the effective action from ancestors
- DFS through the subtree, partitioning into regions with constant action
- Missing children inherit the parent's action (no deeper rules override)
- Short-circuit when both allow and deny are found (proves not uniform)
- Prune subtrees with
count=0or (in priority mode) whensubtree_bestcan't beat the inherited rule
- Complexity: O(32 + visited_nodes), typically much smaller than full subtree due to pruning
listConflictingRules:
- Collect all rules on the path to the query block (ancestors)
- DFS the subtree collecting all descendant rules
- Return those with mixed actions if conflicts exist
- Complexity: O(32 + subtree_size + output)
Scaling to 1M Rules and 100K QPS
Memory optimization:
- Path compression (Patricia/radix trie) reduces nodes from O(n×32) to O(n)
- 1M rules ≈ 2M nodes with compression
- Compact layout (arrays, not objects) uses ~50-100 MB
Query throughput:
- Single-IP lookup is O(32) with no allocations
- Modern CPUs handle millions of lookups per second per core
- 100K QPS is easily achievable on a single machine
Concurrency strategy:
- Writes are rare; use copy-on-write snapshots
- Readers query immutable snapshots without locks (RCU pattern)
- Atomic pointer swap publishes new versions
- Version each snapshot for consistent reads
Alternative for read-heavy workloads:
- Compile rules into sorted disjoint intervals with precomputed actions
- Binary search requires ~20 comparisons but uses less memory
- Rebuild interval list on rule changes
IPv6 Extension
IPv6 uses 128-bit addresses but the design is identical:
- Parameterize trie depth: change
W=32toW=128 - Use
int128or twouint64for address representation - Path compression is essential (sparse 128-bit space)
- Maintain separate tries for IPv4 and IPv6
- Normalize IPv4-mapped addresses (
::ffff:a.b.c.d) into the v4 trie - Multi-bit strides (e.g., 16 bits per level) reduce depth to ~8 lookups
Edge Cases and Pitfalls
- Non-canonical prefixes:
192.168.1.5/24should be normalized to192.168.1.0/24 - Boundary prefixes:
/0(entire Internet),/32(single host) - Duplicate prefixes: Multiple rules with same CIDR—priority and sequence resolve
- Invalid input: Octets > 255, prefix length > 32, malformed strings
- Default action: Empty rule set or no match—specify explicit default (usually deny)
- Removal of nonexistent ID: Define behavior (error vs. silent no-op)
- Priority ties: Use insertion order as deterministic tiebreaker
Why This Works
The correctness follows from CIDR's nested-or-disjoint property:
- Every rule matching IP
xcorresponds to a prefix ofx's bits - These prefixes form a chain from root to leaf
- The deepest is the longest prefix; the minimum priority is the first match
- For range queries, overlapping rules are exactly the ancestors (containing the query) and descendants (contained by the query)
The trie makes this structure explicit, enabling efficient traversal and pruning for all query types.