KatInterview

Firewall Rule Engine with Prefix Matching

Data Structure DesignModel answer
MediumModel answerData Structure Designtrienetworkingbit-manipulation

Last 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:

  1. Basic operations:

    • addRule(rule) — insert a new rule
    • removeRule(ruleId) — delete a rule by ID
    • query(ipAddress) — determine the action for a single IP
  2. 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
  3. Performance targets:

    • Handle up to 1,000,000 rules
    • Support 100,000 queries per second
    • Specify time and space complexity for each operation
  4. 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