Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 40 of 44

Case study: design a traffic inspection gateway

Design an inline, firewall-style gateway that inspects traffic at line rate: packet budgets, per-core flow tables with symmetric hashing, fast and slow paths, kernel bypass, TLS cost, overload, and how to benchmark it, with tested C#.

Case studyApplied24 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 8 code samples
  • 7 interviewer follow-ups
  • 3 self-checks

Read first: Latency, throughput and queues, Load testing and benchmarking, Tail latency and overload

By the end you will be able to
  • Start a data plane design from the packet arithmetic: packets per second and the cycles available per packet.
  • Use per-core ownership of flows, symmetric hashing and a lock-free fast path, and explain what an elephant flow does to it.
  • Separate the slow path (the first packets of a flow) from the fast path (a table lookup), and size the session table and its aging.
  • Say where TLS inspection spends its budget, and how overload and failure should behave for a security device.
  • Describe how such a device is benchmarked: inline, features on, a traffic mix, the highest loss-free rate.

5 code samples (144 lines), collapsed so the explanation stays in focus.

An inline inspection gateway sits in the path of all traffic between two networks. Every packet must be forwarded, dropped or looked at more closely, at tens of millions of packets per second, with state for millions of connections and a delay budget measured in microseconds. It is a clean example of performance engineering driving the design, because the architecture follows from a few numbers.

This lesson designs a generic stateful inspection gateway, the kind of device a firewall or intrusion prevention system is. It describes common techniques and does not describe any vendor's product. The C# shows the algorithms; a production data plane would be written in C, C++ or Rust, where memory layout is under your control and no garbage collector runs on the packet path.

HLD

Clarify the problem

AskWhy it matters
Inline or passive (a tap)?Inline devices must forward every packet and can drop; passive ones can fall behind without breaking the network
What inspection: addresses and ports only, application identification, intrusion signatures, TLS decryption, malware scanning?Each step multiplies per-packet or per-flow cost. The number on a datasheet with everything off is not the number that matters
Throughput target, packet size mix, new connections per second, concurrent sessions?These are four different limits (see below)
Latency and jitter added?Decides batching, queue depths and how much work can sit on the path
What happens on overload and on failure: fail open, fail closed, bypass?A security device chooses between availability and protection (the rate limiter lesson made the same point)
Form factor: appliance, virtual machine, container, cloud fleet?Decides what hardware features exist, such as NIC queues and crypto offload

Functional: forward permitted traffic, enforce a policy by address, port, user, application and content, track connection state, translate addresses if needed, log and export telemetry, apply configuration changes without dropping traffic. Non-functional: line-rate forwarding for established flows, bounded added latency, graceful behavior beyond capacity, high availability, observability, and hitless updates.

HLD

The five numbers

A gateway has several limits, and each is set by a different resource. A single "throughput" figure hides which one you hit.

MetricWhat limits itNotes
Throughput (bits per second)Memory and bus bandwidth, and per-byte work such as encryption or scanningDepends on packet size: large packets are bandwidth-bound
Packets per secondCPU cycles per packetSmall packets are packet-rate-bound, not bandwidth-bound
New connections per secondWork per new flow: policy lookup, state creation, inspection of first packetsDominated by the slow path
Concurrent sessionsMemory per session and table designA hard ceiling
Latency and jitterQueueing, batching, the length of the inspection pipelineMeasure at the highest loss-free rate, not at overload

Standardized benchmarking exists for exactly this class of device. IETF RFC 9411, Benchmarking Methodology for Network Security Device Performance (2023, informational, replacing the older RFC 3511), covers next-generation firewalls and intrusion prevention systems. It tests the device inline, with its security features enabled, and requires publishing a summary of the configuration with the results. The point to carry into an interview is the shape of the method: measure with the features that production will use.

HLD

Do the arithmetic first

Each Ethernet frame occupies its own size plus 20 bytes on the wire (8 bytes of preamble and start delimiter, 12 bytes of inter-frame gap). So the packet rate at line rate is bits per second ÷ ((frame bytes + 20) × 8). A 10 Gbps link carries up to 14.88 million 64-byte frames a second, but only 0.81 million 1,518-byte frames.

Example · estimate
target:       100 Gbps inspected, 10 M concurrent sessions,
              500,000 new sessions a second (illustrative)
worst case:   64-byte frames at 100 Gbps = 148.8 million packets/s
a mixed load: 7 : 4 : 1 of 64, 594 and 1,518-byte frames
              (average 362 bytes) = 32.7 million packets/s
cycle budget: 16 cores x 3 GHz / 32.7 M packets/s
              = about 1,470 cycles per packet
tightest:     10 Gbps of 64-byte frames leaves one 3 GHz core
              about 200 cycles per packet
one miss:     a read from main memory is ~100 ns = ~300 cycles
sessions:     10 M x 128 bytes = 1.3 GB; with hash table slack
              (70% full) about 1.8 GB, split across cores

The last two lines carry the design. One cache miss can cost more than the entire budget for a small packet, so the fast path must touch very little memory, and that memory must be in cache or prefetched. And the budget has no room for locks, system calls, allocation or copies: every one of them is a design decision to avoid.

C# · LineRate19 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public static class LineRate
{
    /// <summary>Bytes a frame occupies on the wire beyond its own size: 8 (preamble and delimiter) + 12 (inter-frame gap).</summary>
    public const int WireOverheadBytes = 20;

    public static double PacketsPerSecond(double linkBitsPerSecond, int frameBytes) =>
        linkBitsPerSecond / ((frameBytes + WireOverheadBytes) * 8.0);

    /// <summary>Packets per second for a mix of frame sizes, each with its share of packets (the shares add up to 1).</summary>
    public static double PacketsPerSecondMix(double linkBitsPerSecond, IEnumerable<(int Frame, double Share)> mix) =>
        linkBitsPerSecond / (mix.Sum(m => (m.Frame + WireOverheadBytes) * m.Share) * 8.0);

    public static double CyclesPerPacket(double cpuHz, int cores, double packetsPerSecond) => cpuHz * cores / packetsPerSecond;
}
C#
Debug.Assert(Math.Abs(LineRate.PacketsPerSecond(10e9, 64) - 14_880_952) < 1);          // 10 GbE of minimum frames
Debug.Assert(Math.Abs(LineRate.PacketsPerSecond(10e9, 1518) - 812_744) < 1);           // the same link of full-size frames
Debug.Assert(Math.Abs(LineRate.CyclesPerPacket(3e9, 1, LineRate.PacketsPerSecond(10e9, 64)) - 201.6) < 0.1);

var mix = new[] { (Frame: 64, Share: 7.0 / 12), (Frame: 594, Share: 4.0 / 12), (Frame: 1518, Share: 1.0 / 12) };
double mixPps = LineRate.PacketsPerSecondMix(100e9, mix);
Debug.Assert(Math.Abs(mixPps - 32_736_796) < 10);
Debug.Assert(Math.Abs(LineRate.CyclesPerPacket(3e9, 16, mixPps) - 1466) < 1);          // about 1,470 cycles per packet

(Definitions of a "typical" traffic mix vary between test labs. Write the mix down with every result.)

HLD

The shape of the gateway

Fig. Share-nothing data plane: each core owns the flows hashed to it
Fig. Share-nothing data plane: each core owns the flows hashed to it
  • Receive-side scaling. The network card hashes each packet's addresses and ports and uses the result to choose one of many receive queues, each served by one core. All packets of a flow arrive on the same core, so that core can keep the flow's state in its own table with no locks.
  • Run to completion. A worker takes a burst of packets (say 32) from its queue and carries each through lookup, verdict and transmit before taking the next. Locality is excellent and there are no hand-offs. Its cost is code size: every feature lives on every core and can overflow the instruction cache. The alternative is a pipeline: stages on different cores connected by lock-free rings, which can specialize each core, at the price of queueing and cache-line transfers between stages. Real systems often blend the two.
  • A separate control plane. Policy compilation, logging, management and updates run off the fast path. The fast path never waits for them.
  • Both directions of a flow must reach the same core. A request and its reply have the source and destination swapped. If they hash differently, the reply lands on a core that has no state for it. The fix is a symmetric hash: order the two endpoints canonically before hashing. (On a NIC, a symmetric hash is usually achieved with a particular repeating hash key.)

The flow table and its shards

A flow is identified by its 5-tuple: source and destination address and port, and protocol. The table maps the canonical key to the session state. The hot part of an entry (key, verdict, last-seen time) should fit one cache line; the rest lives in a cold structure.

C# · FlowKey, Sharder27 lines
public readonly record struct FlowKey(uint SrcIp, uint DstIp, ushort SrcPort, ushort DstPort, byte Protocol)
{
    /// <summary>The same key for both directions of a conversation: the endpoint that sorts first always goes first.</summary>
    public FlowKey Canonical() =>
        (SrcIp, SrcPort).CompareTo((DstIp, DstPort)) <= 0 ? this : new FlowKey(DstIp, SrcIp, DstPort, SrcPort, Protocol);
}

public static class Sharder
{
    // A strong 64-bit mixer (the splitmix64 finalizer): cheap, and it spreads similar inputs apart.
    private static ulong Mix(ulong z)
    {
        z += 0x9E3779B97F4A7C15UL;
        z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
        z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
        return z ^ (z >> 31);
    }

    /// <summary>Which core owns this flow. The seed is secret and random per boot, so an attacker cannot craft flows that all land on one core.</summary>
    public static int ShardOf(FlowKey key, ulong seed, int shards)
    {
        var c = key.Canonical();
        ulong h = Mix(seed ^ ((ulong)c.SrcIp << 32 | c.DstIp));
        h = Mix(h ^ ((ulong)c.SrcPort << 24 | (ulong)c.DstPort << 8 | c.Protocol));
        return (int)(h % (ulong)shards);
    }
}
C#16 lines
var request = new FlowKey(0x0A000001, 0xC0A80005, 51000, 443, 6);
var reply = new FlowKey(0xC0A80005, 0x0A000001, 443, 51000, 6);            // the same conversation, seen from the other side
Debug.Assert(request.Canonical() == reply.Canonical());
Debug.Assert(Sharder.ShardOf(request, 7, 16) == Sharder.ShardOf(reply, 7, 16));    // both directions reach the same core

// Many small flows spread almost evenly over 16 cores ...
var random = new Random(1);
FlowKey RandomFlow() => new FlowKey((uint)random.NextInt64(0, uint.MaxValue), (uint)random.NextInt64(0, uint.MaxValue), (ushort)random.Next(1024, 65535), 443, 6);
var load = new double[16];
for (int i = 0; i < 100_000; i++) load[Sharder.ShardOf(RandomFlow(), 7, 16)] += 1;
Debug.Assert(load.Max() / load.Average() < 1.05);

// ... but one elephant flow carrying 30% of all traffic lands on a single core, whatever the hash does.
load[Sharder.ShardOf(request, 7, 16)] += load.Sum() * 0.30 / 0.70;
double busiest = load.Max() / load.Sum();
Debug.Assert(busiest > 0.30);                                              // about 34%, against a fair share of 6.25%

The elephant is the main weakness of share-nothing designs. A flow is pinned to a core, so one heavy flow is capped by one core and can starve the other flows that share it, while the rest sit idle. Mitigations: rebalance the hash-to-queue table so light flows move off the hot core; split an inspected flow into pipeline stages (decrypt on one core, scan on another); and once a flow has been judged safe, move it to a cheaper cut-through path or onto the card's own flow tables. Moving flows between cores must keep packets in order, so it happens at flow boundaries or with a drain.

Aging idle sessions

Sessions end by FIN or reset, but many just stop. They must be expired, or the table fills with dead flows. Scanning every session each second costs O(n) with millions of entries and drags the whole table through the cache. A timer wheel does it in O(expired): a ring of slots, one per time tick, each holding the flows due to be checked then. A packet does not move its flow to a new slot (that would add work to the fast path); it just updates a last-seen time. When a slot comes due, the check is lazy: if the flow was seen recently, reschedule it; otherwise remove it.

C# · Session, FlowTable67 lines
public sealed class Session
{
    public long LastSeenMs;
    public long Packets;
}

public sealed class FlowTable
{
    private readonly Dictionary<FlowKey, Session> _sessions = new Dictionary<FlowKey, Session>();
    private readonly List<FlowKey>[] _wheel;
    private readonly int _capacity;
    private readonly long _idleMs, _tickMs;
    private long _tick;

    public FlowTable(int capacity, long idleTimeoutMs, int wheelSlots, long tickMs, long startMs)
    {
        _capacity = capacity;
        _idleMs = idleTimeoutMs;
        _tickMs = tickMs;
        _tick = startMs / tickMs;
        _wheel = new List<FlowKey>[wheelSlots];
        for (int i = 0; i < wheelSlots; i++) _wheel[i] = new List<FlowKey>();
    }

    public int Count => _sessions.Count;

    private void Schedule(FlowKey key, long dueMs) => _wheel[(int)((dueMs / _tickMs) % _wheel.Length)].Add(key);

    /// <summary>Create a session (the slow path calls this). Refuses when the table is full: the caller decides whether to drop the new flow or evict.</summary>
    public bool TryAdd(FlowKey key, long nowMs)
    {
        var canonical = key.Canonical();
        if (_sessions.Count >= _capacity || _sessions.ContainsKey(canonical)) return false;
        _sessions[canonical] = new Session { LastSeenMs = nowMs, Packets = 1 };
        Schedule(canonical, nowMs + _idleMs);
        return true;
    }

    /// <summary>The fast path: a hit in either direction updates the session and nothing else.</summary>
    public bool Touch(FlowKey key, long nowMs)
    {
        if (!_sessions.TryGetValue(key.Canonical(), out var session)) return false;
        session.LastSeenMs = nowMs;
        session.Packets++;
        return true;
    }

    /// <summary>Visit the slots that have come due since the last call. Returns how many sessions were removed.</summary>
    public int Expire(long nowMs)
    {
        int removed = 0;
        for (long target = nowMs / _tickMs; _tick <= target; _tick++)
        {
            var slot = _wheel[(int)(_tick % _wheel.Length)];
            if (slot.Count == 0) continue;
            var due = slot.ToArray();
            slot.Clear();
            foreach (var key in due)
            {
                if (!_sessions.TryGetValue(key, out var session)) continue;
                if (nowMs - session.LastSeenMs >= _idleMs) { _sessions.Remove(key); removed++; }
                else Schedule(key, session.LastSeenMs + _idleMs);               // seen recently: look again later
            }
        }
        return removed;
    }
}
C#
var table = new FlowTable(capacity: 2_000, idleTimeoutMs: 30_000, wheelSlots: 64, tickMs: 1_000, startMs: 0);
for (int i = 0; i < 1_000; i++) table.TryAdd(new FlowKey(1, (uint)i, 40000, 80, 6), nowMs: 0);
for (int i = 0; i < 100; i++) table.Touch(new FlowKey((uint)i, 1, 80, 40000, 6), 25_000);   // replies seen at 25 s on 100 of the flows

Debug.Assert(table.Expire(31_000) == 900);                      // 900 flows were silent for 30 s
Debug.Assert(table.Count == 100);                               // the 100 that saw traffic at 25 s were rescheduled, not removed
Debug.Assert(table.Expire(56_000) == 100 && table.Count == 0);  // and they expire 30 s after their last packet

var tiny = new FlowTable(capacity: 2, idleTimeoutMs: 30_000, wheelSlots: 64, tickMs: 1_000, startMs: 0);
Debug.Assert(tiny.TryAdd(new FlowKey(1, 1, 1, 1, 6), 0) && tiny.TryAdd(new FlowKey(1, 2, 1, 1, 6), 0));
Debug.Assert(!tiny.TryAdd(new FlowKey(1, 3, 1, 1, 6), 0));      // full: the new flow is refused and the existing ones are untouched

HLD

Fast path and slow path

Fig. A new flow takes the slow path once, then every packet takes the fast path
Fig. A new flow takes the slow path once, then every packet takes the fast path
  • Slow path, once per flow. Parse the headers, match the policy (by address, zone, user, application), allocate address translation if needed, create the session, and start inspection. Application identification may need the first few kilobytes of payload, so a verdict can be pending and then become final. The policy lookup must not scan rules linearly: use a decision structure built for multi-field matching (tries, hashing over rule fields, or a decision tree), compiled from the policy off the fast path.
  • Fast path, every other packet. Look up the session, update counters and the last-seen time, apply the stored verdict, forward. A few memory touches, all in cache if the design is right.
  • Content inspection. Scanning for thousands of signatures at once uses multi-pattern matching, whose cost grows with bytes scanned, not with the number of patterns. Reassemble streams only as far as needed, and stop scanning a flow when the verdict is final.
  • Admission control for new flows. The slow path is the connection-rate limit. When it saturates (a flood of new connections), bound its queue and drop new flows first, so established flows keep forwarding. This is the overload lesson's rule: shed new work early, protect work in progress. Protect the table too: keep half-open connections in a small, short-lived pool (or answer handshakes statelessly) so a SYN flood cannot fill the full session table.
  • Hitless policy updates. Build the new policy next to the old one and swap a single reference. Packets in flight finish with the old version. Sessions keep their verdict until they are re-evaluated, and the old structure is freed when no core still reads it (the idea behind read-copy-update).

HLD

Kernel stack or bypass

The operating system's network stack is general and convenient: interrupts, per-packet buffers, copies, system calls, locks. It is fine for moderate rates, and at tens of millions of packets a second its per-packet overhead is the bottleneck. Options, from least to most invasive:

ApproachWhat it doesTrade-off
Kernel stack, tunedSpread interrupts and queues across cores, batch with offloadsEasy and observable, but a per-packet cost you cannot remove
XDP / eBPFRun a small verified program at the earliest point in the driverExcellent for dropping and simple steering early; limited program size and features
AF_XDPHand packets to user space with few copiesGood rates, keeps more of the kernel ecosystem
User-space poll-mode drivers (DPDK-style)Own the card in user space, poll it, with huge pages and per-core buffer poolsHighest rates; burns whole cores polling, loses the kernel's tools and TCP stack

The fast-path techniques are the same everywhere: batching (amortize per-call overhead over a burst, at some cost in latency), prefetching the next packet's table entry while processing the current one, huge pages to cut address-translation misses, cache-line aligned and padded per-core data to avoid false sharing, pre-allocated buffer pools (no allocation on the packet path), NUMA-aware placement (buffers and cores near the card), per-core counters merged later instead of shared atomics, and zero-copy handling of descriptors instead of payloads.

Full-content inspection of TCP traffic raises one more choice. A proxy terminates the client's connection and opens a second one to the server, which gives full control and a complete TCP and TLS stack at the cost of two connections per flow. Stream mode reassembles in place and inspects without terminating, which is cheaper but cannot modify encrypted content.

HLD

Where TLS inspection spends the budget

Handshake round trips and window limits are covered in network performance; this section is about the CPU cost.

Inspecting encrypted traffic means decrypting it: the gateway terminates the client's TLS session with a certificate it generates for the requested site (so clients must trust the gateway's signing certificate), opens its own session to the server, and scans the clear text in between.

  • Handshakes cost far more than packets. A TLS handshake does public-key cryptography, orders of magnitude more CPU than forwarding a packet, and the gateway performs two of them per connection. For many short connections the handshake rate is the limit; for long transfers the bulk encryption is. Session resumption, TLS 1.3's shorter handshake, certificate caching and hardware crypto offload all attack the first cost.
  • Latency. Connection setup gains processing time and often an extra round trip.
  • Policy. Some traffic must not be decrypted (certificate-pinned applications, privacy-sensitive categories), so a bypass list is part of the design.
  • Throughput. Decrypted throughput is a fraction of plain forwarding throughput. Quote the two separately.

HLD

Overload and failure

  • Beyond capacity, the card's receive rings overflow and packets are dropped before any software sees them, so watch the ring drop counters, not just CPU. Protect established flows by limiting new ones, and degrade inspection (skip deep scanning for low-risk traffic) before dropping.
  • Failure policy is a product decision, as with the rate limiter: fail closed (drop traffic when inspection is down), fail open (forward uninspected), or bypass (a hardware or software path that keeps the link alive when the device fails, with an alarm). State it per deployment.
  • High availability. An active/standby or active/active pair replicates sessions to its peer so a failover does not reset every connection. The cost is replication traffic and CPU, and the guarantee is eventual: the newest few sessions may be missing after a switch.

HLD

How to benchmark it

Everything from the load testing lesson applies, in network form. Put the device inline between two sets of traffic generators capable of line rate. Use an open-loop load (traffic does not slow because the device is slow) and a documented packet-size mix. Turn on the features production will use. Search for the highest loss-free rate: ramp the offered rate, find where frames start to drop, and report that rate, since a "throughput" that drops packets is not throughput. Then measure latency at that rate, not at overload. Measure the stateful limits separately: connections per second, concurrent sessions, and transaction rates and latency for HTTP and HTTPS. Repeat, and publish the configuration with the numbers.

The loss-free rate is found by bisection, like the bisect of the previous case study: try the midpoint rate, keep the lower half if it passes and the upper half if it does not.

C# · Throughput15 lines
public static class Throughput
{
    /// <summary>The highest offered rate in [low, high] that `noLoss` accepts, to within `resolution`. Returns it and the number of trials.</summary>
    public static (double Rate, int Trials) NoDropRate(Func<double, bool> noLoss, double low, double high, double resolution)
    {
        int trials = 0;
        while (high - low > resolution)
        {
            double middle = (low + high) / 2;
            trials++;
            if (noLoss(middle)) low = middle; else high = middle;
        }
        return (low, trials);
    }
}
C#
// A stand-in for the device: it forwards everything up to 7.3 million packets a second and drops beyond that.
var (rate, trials) = Throughput.NoDropRate(offered => offered <= 7.3e6, low: 0, high: 14.88e6, resolution: 0.01e6);
Debug.Assert(rate > 7.28e6 && rate <= 7.3e6);          // found to within 10,000 packets a second
Debug.Assert(trials <= 11);                             // in eleven trials

Senior depth

What senior interviews ask about a traffic inspection gateway

Interviewer follow-upL5Why does a device's throughput in gigabits depend on the packet size?How to answer

Because most of the cost is per packet, not per byte. The same link carries 14.88 million minimum-size frames a second but only 0.81 million full-size ones, and the device spends roughly the same cycles on each. So small packets exhaust the CPU long before the link is full, while large packets exhaust bandwidth. A throughput claim needs the packet size or the traffic mix next to it.

Interviewer follow-upL6How do you make sure both directions of a connection reach the same core?How to answer

Use a symmetric hash: put the endpoints in a canonical order (or use a symmetric hash key on the card) before hashing, so source and destination swapped give the same value. Without it, replies land on a core with no state, and you either miss the session or take a lock to share it across cores, which defeats the design. Seed the hash with a secret so an attacker cannot craft flows that collide on one core.

Interviewer follow-upL6One core is at 100% and the others are idle. What do you check?How to answer

Look for skew in the traffic: an elephant flow (check per-flow byte counters), a hash that distributes poorly (check per-queue packet counts), or an uneven hash-to-queue table. Check interrupt or polling affinity, and whether the busy core also runs the slow path or the control plane. Then fix by rebalancing the hash-to-queue table, splitting the elephant's work into pipeline stages, or moving established, trusted flows to a cheaper path. Keep packet order when moving flows.

Interviewer follow-upL6How do you size the session table, and what happens when it fills?How to answer

Multiply the target session count by the bytes per session, add slack for the hash table's load factor, and divide by the cores that own shards. Keep the hot fields in one cache line. Expire idle sessions with a timer wheel, with shorter timeouts for closed and half-open connections. When the table fills, decide per policy: refuse new flows (protecting the established ones, the usual choice) rather than evicting live sessions, raise an alarm, and rate-limit new flows per source so one client cannot exhaust it.

Interviewer follow-upL7Throughput with TLS decryption is a small fraction of plain forwarding. Where does the time go, and what do you do?How to answer

Measure first: split connection-rate-bound work (handshakes: public-key cryptography, certificate generation, two handshakes per connection) from byte-rate-bound work (bulk encryption and scanning). Handshake-bound traffic benefits from session resumption, certificate caching, hardware crypto offload and keeping the handshake work on dedicated cores. Byte-bound traffic benefits from hardware AES, larger buffers, scanning only what is needed and stopping early once the verdict is final. Also exclude traffic that need not be decrypted. Report the two limits separately, because a customer's traffic mix decides which one they meet.

Interviewer follow-upL7How would you deploy a policy change with no packet loss?How to answer

Compile the new policy off the fast path into a separate immutable structure, then switch workers to it with one atomic pointer update. Each worker finishes its current burst on the old version, and the old one is freed after every worker has moved on. Existing sessions keep their cached verdicts and are re-evaluated lazily or flagged for re-evaluation, depending on how strict the change must be. Test it under load, since an update that pauses the fast path for even a millisecond drops thousands of packets at line rate.

Interviewer follow-upL7How do you prove a claim of 100 Gbps?How to answer

With a published method, not a number. Inline, with the production feature set enabled, a stated packet-size or application mix, open-loop generators at line rate, the highest loss-free rate found by bisection and repeated, latency reported at that rate, and the stateful limits measured separately (connections per second, concurrent sessions, transaction latency). The configuration goes with the result so someone else can reproduce it. RFC 9411 describes this kind of methodology for network security devices.

HLD

How to present this design in an interview

  1. Clarify: inline or tap, which inspection, targets for throughput, packet rate, connection rate, sessions and latency, failure policy.
  2. Do the arithmetic: packets per second at the worst packet size, the cycles per packet, the cost of one cache miss, the memory for sessions.
  3. Draw the shape: card hashing to per-core queues, share-nothing workers with their own tables, a slow path, a control plane.
  4. Make both directions meet: symmetric hashing, with a secret seed.
  5. Split fast and slow paths, and bound the slow path with admission control.
  6. Size and age the session table: bytes per session, timer wheel, half-open handling, what happens when full.
  7. Choose the stack: kernel, XDP, AF_XDP or user-space polling, with the trade-offs and the fast-path techniques.
  8. Cover TLS, overload, failure and high availability.
  9. Say how you would benchmark it, and which published method you would follow.

Summary

A traffic inspection gateway is a pipeline designed backwards from a cycle budget. Hash flows to cores symmetrically so each core owns its flows and the fast path needs no locks, decide on the first packets in a separate slow path and cache the verdict, keep session state small and age it with a timer wheel, and bypass the operating system's per-packet overhead when the rates demand it. Count the cost of TLS handshakes and bulk encryption separately, protect established flows when new ones overwhelm the slow path, choose a failure policy deliberately, and benchmark inline with features on, reporting the highest loss-free rate with the method published.

Check yourself

Try answering out loud before you reveal each answer.

QuestionHow many minimum-size frames per second fill a 10 Gbps link, and roughly how many cycles per packet does one 3 GHz core have at that rate?Reveal answer

Each 64-byte frame takes 84 bytes on the wire (20 bytes of overhead), so 10 Gbps carries 10,000,000,000 ÷ (84 × 8) = 14.88 million frames a second. One 3 GHz core has 3,000,000,000 ÷ 14,880,952, about 200 cycles per packet, less than one memory miss.

QuestionWhy must the hash that spreads flows across cores be symmetric?Reveal answer

A reply has the source and destination swapped. If the two directions hashed to different cores, the reply would reach a core with no state for the flow, and the design would need locks or cross-core lookups on the fast path. A symmetric hash sends both directions to the same core.

QuestionA table scans every session each second to expire idle ones. What is wrong, and what is the alternative?Reveal answer

The scan costs O(n) per second with millions of sessions and drags the whole table through the CPU cache. Use a timer wheel: slots hold the flows due to be checked at each tick, packets only update a last-seen time, and a slot's flows are rescheduled if they were seen recently or removed if not. The work is proportional to the sessions that expire.

Sources and further reading

  • IETF, RFC 9411: Benchmarking Methodology for Network Security Device Performance (opens in a new tab) (2023), which obsoletes RFC 3511 (firewall benchmarking); and RFC 2544, Benchmarking Methodology for Network Interconnect Devices, which defines throughput as the highest rate with no frame loss.
  • The Linux kernel documentation, "Scaling in the Linux Networking Stack" (receive-side scaling and related mechanisms), and the DPDK programmer's guide for poll-mode drivers, huge pages and packet buffer pools.
  • George Varghese and Tony Lauck, "Hashed and Hierarchical Timing Wheels", SOSP 1987: the timer wheel.
  • Fan, Andersen and Kaminsky, "MemC3: Compact and Concurrent MemCache with Dumber Caching and Smarter Hashing", NSDI 2013: cache-friendly concurrent cuckoo hashing for a lookup-heavy table.
  • Brendan Gregg, Systems Performance, 2nd edition, Addison-Wesley, 2020, for the network and CPU analysis methods behind the counters mentioned above.
Lesson 40 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 41Microsoft system design questions: what candidates report and how to answerThe design prompts candidates report for Microsoft, a worked Teams-style chat design with ordering and fan-out, a tested C# cache with a swappable eviction policy, and the senior follow-ups.

Send a message

It goes straight to my inbox. I usually reply within a few days.