Overview

Two NICs in one server — one on the office network, one on a dedicated line — looks like the simplest topology in the world. But the moment you put a gateway on that second NIC as well, or add a default route to “send some traffic over the dedicated line”, the entire egress path can flip without warning: ping works for some destinations and not others, existing connections keep running, and every new connection times out.

Nothing was misconfigured. This is how the Linux kernel chooses routes by default: a network namespace has exactly one main routing table, and a “default route” can only have one effective entry. Write two, and the kernel picks by metric — the other stays in the table but never gets selected. Worse, the decision only considers the destination address: not the source address, not the ingress interface, not which process sent the packet.

This article is about pulling “multiple egress paths on one host” apart again. Three approaches, ordered by weight:

  1. Policy routing (multiple route tables + ip rule): touches only the routing decision. No application changes, no NIC changes; two or three commands send a given source address out a given gateway.
  2. network namespace + veth: shove a link and a full protocol stack into its own namespace, so “a few processes” live on a separate virtual machine.
  3. VRF (Virtual Routing and Forwarding): a kernel-native Layer 3 isolation object. NICs are enslaved into an isolated routing domain, and an application becomes VRF-aware by binding its socket to the device.

Along the way we’ll explain a counter-intuitive symptom — why the business that was already running survived the route change, while the “untouched” interface started timing out — and the role rp_filter and arp_ignore play in it. Textbook chapters on policy routing usually cover this in half a page.

By the end you should be able to look at a multi-homed topology, decide which isolation mechanism fits, and write the configuration so it survives a reboot and gives you a diagnostic handle when it breaks.

1. Why Two Egress Paths Degrade to One

Let’s start with kernel behavior. Every pitfall later follows from these few facts.

1.1 One main Table Holds Everything

Linux ships three default tables:

Table IDNamePurpose
255localLocal and broadcast addresses, maintained by the kernel, highest priority
254mainThe table you see with plain ip route; almost everything is configured here
253defaultFallback table, usually empty

When ip route runs without a table argument, it operates on main. The problem is there is only one main, and matching inside it is longest-prefix-wins: 0.0.0.0/0 has prefix length 0, so every specific subnet outranks it. It always sits last, functioning purely as “when nothing else matched”.

Now you have two gateways:

# After putting a gateway on both NICs, the main table looks like this
ip route show
# default via 192.168.10.1 dev eth0 proto static metric 100
# default via 10.20.0.1 dev eth1 proto static metric 101
# 192.168.10.0/24 dev eth0 proto kernel scope link src 192.168.10.21
# 10.20.0.0/24 dev eth1 proto kernel scope link src 10.20.0.21

Two default entries coexisting is perfectly legal; the kernel uses the one with the lower metric. So 0.0.0.0/0 has exactly one egress, and the other entry is decoration.

The insidious part: the dedicated-line gateway 10.20.0.1 pings fine, because 10.20.0.0/24 has a connected route and never consults the default. Yet no business traffic actually leaves through eth1. Engineers see “NIC up, gateway reachable, business broken” and immediately suspect a firewall or an ACL on the far end.

1.2 The Kernel Ignores Source and Process

main is looked up by destination address. It has no idea whether the packet came from Nginx or from a data-sync agent, and no idea which NIC the far end expects it to come from. Two consequences:

  • Source address selection: for an outbound connection, the kernel first resolves the route to pick the egress device, then picks a source IP on that device (the src hint if present, otherwise the primary address). Wrong egress means a wrong source IP, and the far end sees an address it doesn’t recognize — the reply may die in reverse path filtering.
  • Return path consistency: the inbound and outbound directions of a flow must use the same link, or intermediate security devices, load balancers, and even the far end’s rp_filter will treat it as anomalous.

So “just configure both gateways” has no implementation behind it: it would require a multi-dimensional route lookup, and main is one-dimensional.

1.3 A Validation Method That Won’t Fool You

After configuring, don’t validate with ping. Use ip route get:

# Simulate "from 10.20.0.21, to 203.0.113.9" and see what the kernel actually picks
ip route get 203.0.113.9 from 10.20.0.21
# 203.0.113.9 from 10.20.0.21 via 10.20.0.1 dev eth1 table 100 src 10.20.0.21 uid 0

# Simulate "arriving on eth1, replying to 198.51.100.7"
ip route get 198.51.100.7 iif eth1 from 198.51.100.7
# 198.51.100.7 from 198.51.100.7 via 10.20.0.1 dev eth1 table 100 src 10.20.0.21

ip route get prints the kernel’s real decision path, including which table it consulted and which source address it chose. That’s far more useful than ping: ICMP succeeding only proves ICMP took some path — not that TCP takes the same one, and certainly not that the far end accepts your source address.

1.4 Three Illusions That Look Cheaper

Before reaching for policy routing, rule out three common self-persuasions:

  • “I’ll just tune the metric”: metric decides which of two candidate default routes wins. It cannot express “these flows take link A, those take link B”. It solves “pick one of two”, not “split two classes of traffic”.
  • “Just add two static routes, one per gateway”: static routes also match by destination only. For any unknown destination, you still have two default entries and one effective winner.
  • “Just write GATEWAY in the NIC config”: GATEWAY in ifcfg is equivalent to injecting a default into main. Write it on both NICs and you have two entries; which one wins depends on boot order and metric. That is exactly why “after a reboot the route mysteriously changed”.

All three share one flaw: they try to express a two-dimensional choice with a one-dimensional table. There is no way around that.

2. Post-Mortem: One default Route Killed the Whole Intranet

2.1 Topology and Prior State

Anonymized: a data-sync host on a new-energy logistics platform, with two NICs. eth0 on the intranet (192.168.10.0/24, gateway 192.168.10.1); eth1 on a dedicated line to a third-party platform (10.20.0.0/24, gateway 10.20.0.1).

A batch of intranet services called this host, and the host pushed data to a set of intranet APIs. Originally eth1 had no gateway; dedicated-line traffic used a single specific route: ip route add 172.30.0.0/16 via 10.20.0.1 dev eth1. That configuration had been stable for over half a year.

Then, to upload larger sync payloads, someone ran:

ip route add default via 10.20.0.1 dev eth1 metric 50

The intent was “the dedicated line has more bandwidth, so default traffic should go there”. Metric 50 beat the 100 on eth0, the new default took effect, and 0.0.0.0/0 in main began pointing at eth1.

2.2 Symptoms: Half the Connections Alive, Half Timing Out

The fallout appeared within minutes, and it was strikingly inconsistent:

  • Long-lived push connections already running: perfectly fine;
  • Every newly established call to the intranet: timed out;
  • ping 192.168.10.1 from the host: works (the connected route is in main and unaffected);
  • ping the host from elsewhere: works, but curl against its business port: times out.

The on-call engineer’s first instinct was the firewall. iptables -L was clean. The far end hadn’t touched its ACL either. Only when someone thought to run ip route show did the default route turn out to point at the dedicated-line gateway — and those intranet addresses (172.31.0.0/16) had no specific route, so they all fell through to the default, exited via eth1, and hit a gateway with no path back to the intranet. Black hole.

2.3 Why the Old Connections Survived

The “split” behavior is what stretched the incident out. Why were old connections alive? Because a TCP socket caches its egress route and source address at connect time (sk_dst_cache), and later routing table changes do not redirect established connections. Old connections kept using eth0; only new connections followed the new table. So on one host, “two callers of the same service” — one saw success, one saw timeouts.

Worth remembering: a route change breaks new connections, not all traffic. Seeing “some requests succeed, some time out” should send you to check whether routes were touched, not to suspect link flapping. Conversely, when validating a route change, don’t expect existing connections to expose problems — you have to create new ones.

There’s a related cache: conntrack. Connections already tracked keep the source address recorded in their conntrack entry even if routes change, and NAT decisions aren’t recomputed. So “change the route, then flush conntrack” is sometimes necessary (conntrack -D -s <ip>), especially when you rely on SNAT.

2.4 Where the Twenty Minutes Went

The time breakdown is more valuable than the conclusion:

PhaseDurationWhat we didOutcome
Alert to response~3 minSaw timeout alerts, read business logsKnew the far end timed out; no local view
Suspect network gear~6 minChecked security groups, far-end ACLs, switch portsAll green, nothing wrong
Suspect the host~4 minss -lntp, iptables -vnL, dmesgProcess up, rules present, no drop logs
Think of routing~5 minip route showFound default pointing at eth1
Verify and roll back~2 minip route del default via 10.20.0.1 dev eth1 metric 50New connections recovered instantly

Those four minutes spent “suspecting the host” could have been ten seconds with a single ip route get 172.31.x.x. That’s precisely why ip route get belongs in the first section rather than the third: in a triage order, the routing decision is the second thing to check, right after “is the process still up”.

2.5 Three Remediations

  1. No more ad-hoc default routes on business hosts. Switch to “explicit egress plus policy routing”: whoever needs the dedicated line declares its source address.
  2. All route changes go through configuration management. ip route add typed into a shell requires a change ticket.
  3. Add synthetic monitoring: every multi-homed host periodically curls a core intranet endpoint and a public probe, and both must be green. One-sided green means an egress routing problem.

The third item is cheaper than the first two and would have saved those “maybe it’s the firewall” minutes next time. Details in 7.7.

3. Approach One: Policy Routing (Multiple Tables + ip rule)

The lightest of the three: only the routing decision changes. Applications, NICs, and kernel parameters stay untouched.

3.1 Principle: Route Lookup Goes From 1-D to 2-D

The kernel’s actual order is “match a rule first, then look up the table that rule names”:

Outbound packet
  └─> walk ip rule (ascending priority)
        ├─ priority 0    : is the destination a local address? → look up local table, deliver locally
        ├─ priority 1000 : device bound to an l3mdev (VRF)?   → look up that VRF's table  ← added with the VRF
        ├─ priority xxx  : custom rules (from/oif/fwmark, ...)
        ├─ priority 32766: nothing matched yet → look up main
        └─ priority 32767: still nothing → look up default (usually empty) → unreachable

Policy routing inserts rules in the middle. The built-in rules always come last, so any rule you add (priority below 32766) is evaluated first.

Note the priority 0 local rule: it precedes all custom rules. That means “packet addressed to a local address” always wins over your splitting logic. Once you move a NIC’s address out of main, packets from elsewhere to that address still hit local first and get delivered locally — which can look like “splitting works but the service never receives anything”. This is even more visible with VRF (whose local table is shared across VRFs); we’ll come back to it in section 5.

3.2 Complete Configuration: Building an Egress for a Non-Main Source Address

Using the same topology, the goal is: traffic originating from 10.20.0.21 goes out eth1 via the dedicated-line gateway; everything else continues to use eth0.

# 1. Give the custom table a name so ip route show table uplink is readable
#    Note: rt_tables is only a name mapping; editing it doesn't alter existing rules
echo "100 uplink" >> /etc/iproute2/rt_tables

# 2. Write a "complete egress" into table 100: connected subnet + default gateway
#    This is the step most often missed: without the connected route the ARP
#    request for the gateway itself has no path out
ip route add 10.20.0.0/24 dev eth1 src 10.20.0.21 table uplink
ip route add default via 10.20.0.1 dev eth1 table uplink

# 3. The critical step: match on source address (not ingress interface)
#    Start priority at 100 to leave room for finer-grained rules later
ip rule add from 10.20.0.21/32 table uplink priority 100

# 4. Verify immediately: all three commands must be green
ip rule show | head -5
ip route show table uplink
ip route get 203.0.113.9 from 10.20.0.21

A few notes, each learned the hard way:

  • Why from instead of iif: iif (ingress interface) only means something for forwarding and replies. Locally initiated connections have no meaningful ingress, so the rule never matches — and you end up with “the service is reachable but its own outbound calls still take the wrong egress”. from matches the source address and works in both directions.
  • The custom table must contain the connected route: default via ... alone is accepted by the kernel, but without 10.20.0.0/24 dev eth1 in table 100 the kernel has no idea which interface can reach gateway 10.20.0.1, so nothing is transmitted. The symptom is ip route get looking perfect while curl times out 100% of the time — indistinguishable from “the gateway is down”.
  • The src hint matters: if eth1 carries more than one address (a VIP added later, say), omitting src lets the kernel pick “the other” address, and the far end sees a source IP you didn’t intend.

3.3 The Reverse Direction: Making Replies Take the Same Path

The above only fixes “outbound”. If the far end initiates (an intranet service calling this host), replies must leave through the same NIC. Add a rule keyed on ingress interface:

# Connections arriving on eth1 reply through the uplink table too
# Place it after the from rule so it doesn't steal priority
ip rule add iif eth1 table uplink priority 200

You can also use fwmark with iptables/nftables to lift splitting from the address dimension to the port/protocol dimension:

# Mark traffic to destination port 8443 with 0x10, then select the table by mark
nft add rule inet mangle output tcp dport 8443 meta mark set 0x10
ip rule add fwmark 0x10 table uplink priority 150

fwmark avoids extra NIC addresses and doesn’t depend on who initiated the connection. The cost is an extra hop during troubleshooting: you now have to check nft counters and ip rule together. My habit: use from unless the splitting dimension really is a port or protocol.

3.4 Persistence: Three Legitimate Options, Not Four

ip rule and custom tables are not persistent; they vanish on reboot. Three supported mechanisms:

MechanismWhere the config livesWhen to use
NetworkManagernmcli ipv4.routing-rules / ipv4.route-tableRHEL / CentOS / Alinux default stack
systemd-networkd[RoutingPolicyRule] in a .network fileUbuntu / self-managed systemd distros
ifcfg scriptsroute-eth1 + rule-eth1Only on older initscripts-based systems

systemd-networkd is the most readable:

# /etc/systemd/network/20-eth1.network
[Match]
Name=eth1

[Network]
Address=10.20.0.21/24
Gateway=10.20.0.1
RouteTable=100

# Rule: source address 10.20.0.21 uses table 100
[RoutingPolicyRule]
From=10.20.0.21/32
Table=100
Priority=100

The NetworkManager equivalent:

nmcli connection modify eth1 \
  ipv4.route-table 100 \
  ipv4.routing-rules "priority 100 from 10.20.0.21/32 table 100"
nmcli connection up eth1

The fourth option you should not use: stuffing commands into /etc/rc.local. It races NetworkManager and, on some distros, network-online.target, producing “works 90% of the time after reboot”. A probabilistic failure is worse than a deterministic one, because your first hypothesis will be hardware.

3.5 A Complete Rule Set for Four Egress Paths

One egress is easy. With several, the organization of the rule set matters more than the commands. Below is a host with “intranet + dedicated line + backup line + public internet”, written in the order I recommend:

# ── 0. Clean up history first to avoid duplicate rules piling up ──────────
while ip rule del priority 100 2>/dev/null; do :; done
while ip rule del priority 110 2>/dev/null; do :; done
while ip rule del priority 120 2>/dev/null; do :; done

# ── 1. Four tables: number them in bands so ownership is obvious ─────────
#   100s for dedicated lines, 200s for backups, 300s reserved
cat >> /etc/iproute2/rt_tables <<'EOF'
100 line-a
110 line-b
EOF

# ── 2. Every table needs "connected + default"; neither may be omitted ───
ip route replace 10.20.0.0/24 dev eth1 src 10.20.0.21 table line-a
ip route replace default via 10.20.0.1 dev eth1 table line-a

ip route replace 10.30.0.0/24 dev eth2 src 10.30.0.21 table line-b
ip route replace default via 10.30.0.1 dev eth2 table line-b

# ── 3. Rules: one rule per source address, priorities spaced by 10 ───────
ip rule add from 10.20.0.21/32 table line-a priority 100
ip rule add from 10.30.0.21/32 table line-b priority 110

# ── 4. Inbound replies: one interface-based layer last, never stealing ───
ip rule add iif eth1 table line-a priority 120
ip rule add iif eth2 table line-b priority 130

Two more details worth putting in the runbook:

  • Use ip route replace, not add: add fails with RTNETLINK answers: File exists when the route is already there, leaving your script with a half-applied configuration. replace is idempotent and safe to re-run.
  • Delete rules by priority, not by content: ip rule del from 10.20.0.21/32 errors out when several identical rules exist, while ip rule del priority 100 is always precise.

3.6 The Three-Step Troubleshooting Kit

When policy routing misbehaves, these three steps localize the fault layer:

# Step 1: is the rule being evaluated in the order you expect?
ip rule show

# Step 2: is the table complete (connected route present? two defaults fighting?)
ip route show table line-a

# Step 3: the kernel's actual decision — most often skipped, most useful
ip route get 203.0.113.9 from 10.20.0.21
ip route get 203.0.113.9 from 10.20.0.21 iif eth1

Try step 3 with from alone and then with iif added: the first simulates “locally initiated”, the second simulates “replying to an inbound packet”. When the two disagree, your rule set is asymmetric between outbound and return — and that asymmetry is the usual root cause of “it connects, then dies after a few minutes” failures.

4. Approach Two: network namespace + veth

If the requirement isn’t “a source address” but “these processes must live on a different network”, policy routing is not enough. You need a separate protocol stack.

4.1 Principle: A Virtual Machine for a Process

A network namespace (netns) isolates an entire network stack: devices, addresses, routing table, ARP/neighbour table, iptables rules, conntrack table, even the parameters under /proc/sys/net. Each netns has its own lo, and it starts down.

You connect namespaces with a veth pair — two virtual NICs, one end in A, the other in B. A packet entering one end exits the other, like a virtual cable. To reach the outside, you either NAT on the host or “lend” the physical NIC to the namespace.

Container networking is this same machinery: Docker’s bridge mode and Kubernetes Pod networking are netns + veth + a Linux bridge. The difference is that the runtime does the plumbing for you, and it doesn’t do the parts you’d have to do yourself. For more background, see Related: Linux Namespaces and cgroups.

4.2 Complete Configuration: Putting the Dedicated Line Into a netns

Goal: run the data-sync agent in a namespace that only knows the dedicated line, so no matter what it does, packets can only leave through eth1.

# 1. Create the namespace and bring lo up first (many oddities if you skip this)
ip netns add uplink
ip netns exec uplink ip link set lo up

# 2. Create a veth pair: veth-up on the host, eth0 inside the namespace
ip link add veth-up type veth peer name eth0 netns uplink

# 3. Host side: attach veth-up to a dedicated bridge, then enslave eth1
#    Traffic from the namespace leaves veth-up and reaches eth1 at layer 2
ip link add br-uplink type bridge
ip link set br-uplink up
ip link set veth-up master br-uplink
ip link set veth-up up
ip link set eth1 master br-uplink

# 4. Namespace side: address and default route
ip netns exec uplink ip addr add 10.20.0.22/24 dev eth0
ip netns exec uplink ip link set eth0 up
ip netns exec uplink ip route add default via 10.20.0.1 dev eth0

# 5. Verify: the namespace reaches the far end, and the host's main table is untouched
ip netns exec uplink ip route get 203.0.113.9
ip netns exec uplink ping -c 2 10.20.0.1

Note the trade-off in step 3. Once eth1 joins the bridge its address “disappears” (a bridge port shouldn’t carry an address), and the host’s main table no longer contains the 10.20.0.0/24 connected route. That’s a net win — the connected route that used to pollute main is gone, leaving only the intranet. The cost is that the host itself loses direct access to the dedicated line; reaching it requires ip netns exec or extra host-side configuration.

The alternative is NAT on the host (iptables -t nat -A POSTROUTING -s 10.20.0.22 -o eth1 -j MASQUERADE) with a private range inside the namespace. Both host and namespace can then reach the dedicated line, but the namespace’s source address is rewritten to eth1’s address, and the far end can no longer allowlist by source IP. If the far end requires a fixed source IP, don’t NAT — bridge.

4.3 The Performance Cost: Not Folklore This Time

netns isolation isn’t free. The cost comes from one extra copy across the namespace boundary plus one trip through the per-CPU backlog queue. The numbers have moved a lot over kernel versions:

ScenarioExtra costSource
veth pair, single hop~1-2 μs per packetCommon measurement and documentation
Docker veth (kernel 6.14, sockperf)0.568 μs, ~3.1%opscart container isolation benchmark
Cross-netns throughput26%-31% lower than same-namespaceNetkit paper (netperf TCP_CRR)

The Netkit paper’s explanation is the key part: veth enqueues every received packet onto a per-CPU backlog queue, so crossing a namespace boundary costs an extra enqueue/dequeue; under load, processing can fall to ksoftirqd, which runs at normal scheduling priority, competing with your workload and charging the cycles to the wrong process. So “one extra memory copy” is only the surface. The real cost is scheduling and queueing.

In practice: an IO-bound service pushing a few tens of Mbps per connection won’t notice 1-2 μs per packet. A small-packet, high-frequency workload (Redis, gRPC short connections, telemetry shipping) at hundreds of thousands of pps will see that 26%-31% throughput loss show up in CPU utilization. You can’t decide this from intuition — run iperf3 twice on your own hardware. Method in 7.8.

4.4 Troubleshooting: You Now Have Two “Machines” to Check

The most counter-intuitive part of netns is that diagnostic tools only see the host namespace by default:

  • tcpdump -i eth1 captures nothing inside the namespace (there’s no eth1 there); use ip netns exec uplink tcpdump -i eth0;
  • ss -lntp doesn’t show listeners inside the namespace; use ip netns exec uplink ss -lntp;
  • conntrack -L only shows the host’s table; the namespace has its own;
  • DNS is separate too: the namespace reads /etc/netns/uplink/resolv.conf (a path ip netns exec deliberately supports as an override), otherwise it fights with the host’s resolv.conf.

I imposed one convention on this setup: name namespaces after the business (uplink, report), and wrap every diagnostic script in ip netns exec. A newcomer reading the script immediately knows “this service is not on the host network”. It saved a lot of “why can’t I capture anything” conversations.

One cleanup step people forget: ip netns del uplink removes the veth pair and the bridge membership, but not the bridge br-uplink you created manually, and not the iptables/nftables rules referencing 10.20.0.22. Teardown must reverse “what I created”, or the next rebuild will complain about addresses in use.

5. Approach Three: VRF — Layer 3 Isolation Built Into the Kernel

Policy routing’s weakness is that rules are global and flat. VRF’s strength is that it packages “one routing table plus a set of NICs” into a single kernel object.

5.1 Principle: The l3mdev Domain

Linux represents a VRF as a virtual device (any name; vrf-xxx is conventional) bound to a routing table at creation. Once a physical port joins it:

  • packets received on that port are “lifted” to the VRF device before route lookup, as if they traversed the VRF;
  • on egress, rules steer packets into the VRF driver, which decides which enslaved port to use;
  • creating the VRF adds a priority 1000 rule matching “devices bound to an l3mdev” and pointing at the VRF’s table.

So VRF isolates more than a routing table: it isolates the neighbour table, the tcpdump observation point, and the scope of tc/netfilter. The kernel documentation states this explicitly: VRF affects Layer 3 and above only, so L2 tools like LLDP need not run per VRF; and higher-priority PBR rules can override VRF rules for exceptions.

5.2 Complete Configuration: Two Business Lines, Two Egresses

# 1. Create the VRF: name vrf-blue, bound to table 100
ip link add vrf-blue type vrf table 100
ip link set vrf-blue up

# 2. Enslave the physical port: eth1 now belongs to vrf-blue
ip link set eth1 master vrf-blue
ip addr add 10.20.0.21/24 dev eth1
ip link set eth1 up

# 3. Put routes in the VRF's table (NOT main!)
#    Also add an unreachable catch-all so lookups can't fall back to main
ip route add 10.20.0.0/24 dev eth1 table 100
ip route add default via 10.20.0.1 dev eth1 table 100
ip route add unreachable default metric 4278198272 table 100

# 4. Look at the rule the kernel added for you
ip rule show | grep -i l3mdev
# 1000:  from all lookup [l3mdev-table]

# 5. Verify
ip -d link show vrf-blue
ip route show table 100

That unreachable default metric 4278198272 looks odd but matters: with an unreachable catch-all present, a miss inside the VRF table stops there instead of continuing to main. The huge metric keeps it behind every real default route. Without it, you think you’re isolated, but some destinations still leak out the host’s default egress — and this kind of leak is nearly invisible in monitoring, because the traffic “works”.

5.3 How Applications Become VRF-Aware

This is where VRF differs most from netns: in a netns every process is automatically isolated; in a VRF no process is isolated by default.

Awareness requires binding the socket to the VRF device:

// In C (after socket creation, before connect)
setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, "vrf-blue", strlen("vrf-blue") + 1);

Command-line tools have a wrapper:

# Bind all sockets of this command to vrf-blue
ip vrf exec vrf-blue curl -s https://203.0.113.9/health

This step is the most underestimated part of VRF adoption. Older applications — third-party agents, closed-source SDKs, frameworks that hardcode interface binding — don’t honor SO_BINDTODEVICE. Your options are wrapping the launch in ip vrf exec or writing a systemd drop-in that rewrites ExecStart:

# /etc/systemd/system/sync-agent.service.d/vrf.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/ip vrf exec vrf-blue /usr/local/bin/sync-agent --config /etc/sync-agent.yaml

Red Hat’s documentation prescribes exactly this and adds a deceptively quiet note: services can only bind to local addresses inside the same VRF. Read plainly, it means “a service in the VRF must listen on a VRF-internal address” — that is, the eth1 address, not the host’s eth0 address.

One more subtlety: can services in the default VRF (the unbound portion) accept inbound connections from a VRF? Not by default. Enable net.ipv4.tcp_l3mdev_accept (and udp_l3mdev_accept for UDP) to allow it. This is mandatory when you want the same port served by one instance per VRF.

5.4 Kernel Version: An Absolute Floor

VRF depends on l3mdev. Behavior before 4.8 is incomplete, and on old kernels (typically CentOS 7’s 3.10) running ip link add ... type vrf fails outright:

RTNETLINK answers: Operation not supported

That message is misleading — easily read as “iproute2 is too old”. In reality, when iproute2 has the vrf subcommand but the kernel lacks the device support, this is exactly what it prints. Check uname -r first, then ip -V. My working floor is 4.8 to get started, 4.10+ if you want ip vrf exec — that subcommand landed in iproute2 4.10.

5.5 How VRF Fits Dynamic Routing and Container Platforms

VRF isn’t only for hand-written static routes. Two integration points are worth calling out:

  • Dynamic routing: FRR and BIRD can bind sessions to a VRF (a vrf blue block in FRR, a vrf "blue" declaration in BIRD). That means “BGP on the dedicated line, OSPF on the intranet” can coexist on one host, with each protocol seeing only its own neighbours and advertising only its own routes. This is VRF’s biggest structural advantage over policy routing: policy routing can steer packets, but it cannot steer which routing protocol learns what.
  • Container platforms: CNI plugins are beginning to support VRF natively (attaching a Pod’s veth into a named VRF). Careful, though: processes inside the container are not automatically VRF-aware unless the CNI makes the veth a VRF slave, or you add a layer of ip vrf exec inside. The real question is “who does the binding” — if the CNI binds, all traffic in the container image uses the VRF; if the container binds, two containers in one Pod can egress differently. The latter sounds flexible and is a troubleshooting nightmare in practice. See Related: Cloud-Native Network Architecture.
  • Stacking with netns: the kernel documentation explicitly supports VRFs nested inside namespaces. netns isolates at the device layer, VLANs inside the namespace at layer 2, and VRF at layer 3. Large multi-tenant platforms stack all three. But each layer adds a wrapper to every diagnostic command, so build the layered troubleshooting scripts before you build the stack — otherwise you’ll live in “why can’t I capture anything” loops.

6. Selection: Three Approaches, Plus bond, ECMP, and Cloud Networking

First the comparison, then my recommendations.

DimensionPolicy routingnetns + vethVRF
What is isolatedRouting decision (source/mark/ingress)The whole protocol stackL3 routing domain + neighbour table
Application changesNoneNone (move the process into the ns)Needs SO_BINDTODEVICE or ip vrf exec
Impact on mainCustom table + rules; main untouchedmain gets cleanermain loses that port’s address
Performance costA few extra rules per lookup, negligible1-2 μs per veth hop, cross-ns throughput -26% to -31%One “lift” on route lookup, smaller than netns in practice
TroubleshootingThree commands (ip rule / ip route t / ip route get)Every tool wrapped in ip netns exectcpdump -i vrf-blue captures the whole domain
Kernel requirementVery old kernelsVery old kernels4.8+ (ip vrf exec needs iproute2 4.10+)
Typical effortMinutesHoursHalf a day to a day, including app adaptation

Three explicit recommendations:

First: a single host with two egresses where only one or two processes need the dedicated line — use policy routing. Not because it’s “simpler”, but because its blast radius is smallest: main is untouched, existing routing behaves exactly as before, and deleting one ip rule restores the original state. That “rollback in seconds” property matters more at 2 AM than any architectural elegance.

Second: multiple business lines, multiple tenants, where isolation must exist at the routing layer — use VRF. I’ve seen the counter-example on a multi-tenant telemetry platform: from rules with one table per tenant, roughly 40 tenants, well past a hundred rules. Every new tenant meant editing ip rule ordering, and one insertion in the wrong place made two tenants mutually reachable. VRF turns “tenant → table” into a kernel object: ip -d link show vrf-xxx tells you the table at a glance, tcpdump -i vrf-xxx captures the whole domain, and the mental overhead drops by an order of magnitude.

Third: if DNS, iptables, and stack parameters all need to be independent — use netns; but if the only goal is egress isolation, don’t use netns. This is the most common misuse I encounter: isolating one egress at the cost of a 26%-31% throughput hit, a “can’t capture packets” workflow, and a resolv.conf that must be maintained separately. The cost/benefit doesn’t hold.

One combination worth mentioning: a VRF inside a netns. The kernel documentation supports the nesting — netns isolates at the device layer, VLANs inside it at layer 2, VRF at layer 3. Real large-scale multi-tenant setups (one host running several tenants’ containers, each tenant with multiple egresses) stack exactly like this. Unless that’s your situation, don’t reach for three layers of nesting unprompted.

6.4 bond: Bandwidth Aggregation, Not Egress Selection

“Just bond the two NICs and you have both egresses” is the single most repeated — and most misunderstood — line I hear in design reviews.

bond (Linux link aggregation) solves a layer 2 problem: it merges two NICs into one logical interface presenting one MAC and one IP. 802.3ad (LACP) gives bandwidth aggregation and redundancy; active-backup gives failover. In every mode, there is exactly one IP and one gateway. It cannot express “this NIC takes the dedicated line, that one takes the intranet”, because logically they are already one NIC.

A more practical constraint: LACP requires the peers to be ports on the same switch (or the same stack/MLAG domain) in the same L2 domain. Two cables to two different switches cannot form LACP; force it and you get flapping links plus ports shut down by the switch.

So when is bond correct? When your requirement is link reliability, not egress selection. In cross-site disaster recovery, for instance, two physical paths terminating on the same transport equipment and configured as active-backup so a single fiber cut doesn’t break the service — in that design bandwidth and egress path aren’t variables, reliability is. When I designed RPO<5min / RTO<30min DR, bond was used exactly there, never as a “dual egress”.

6.5 ECMP: The Kernel Has Multipath, and It Is Not Splitting

Multipath routing is a tempting idea:

ip route add default \
  nexthop via 10.20.0.1 dev eth1 weight 1 \
  nexthop via 192.168.10.1 dev eth0 weight 1

The command is legal and the kernel really does spread traffic across both next hops. But by what?

  • net.ipv4.fib_multipath_hash_policy = 0 (the default): hashes on layer 3, i.e. destination IP. The same peer address always takes the same path.
  • Set to 1: hashes on layer 4 (including source and destination ports), so multiple connections to the same peer spread across paths.

Neither fits egress selection:

  • Under policy 0 you cannot say “this business uses the dedicated line”, because that business’s destinations are fixed.
  • Under policy 1 the same peer sees your source IP flip between links. If the peer allowlists source IPs, half the connections are rejected; if it keeps session state, connections reset for no apparent reason.

So in my triage table, ECMP means “two homogeneous egresses, no source-IP requirement, pure bandwidth”. It differs from bond in that bond aggregates at layer 2 (same L2 domain required) while ECMP aggregates at layer 3 (can cross gateways and subnets). Neither expresses “who goes where”.

One troubleshooting trap: ip route get returns a single result for an ECMP route (it simulates one lookup), so you may conclude “splitting isn’t working”. To verify hashing, run ip route get repeatedly with different from values or source ports, or simply watch whether both NICs’ counters increase.

6.6 Multi-Egress in the Cloud: There Is No “Second Default Gateway” in the Console

The first thing to accept in the cloud is: the provider’s network model has no “configure a gateway on this NIC” operation. Secondary (elastic) NICs usually have no gateway; routing is decided by VPC route tables, and the instance’s routes are generated by cloud-init from metadata.

That changes several things concretely:

  • Egress splitting still means policy routing. The primary NIC has a default gateway; a secondary NIC only gets an address inside its subnet. To egress through it you must add a table, write the connected route plus a default whose next hop is the subnet’s gateway address, and add ip rule from. The commands are identical to bare metal; only the gateway address comes from the subnet description.
  • Source/destination check: most clouds enable source_dest_check by default, so packets leaving eth1 with a source address other than eth1’s are dropped by the platform. Turn it off for NAT and forwarding scenarios.
  • Reboots rewrite routes: cloud-init rebuilds eth0’s default route from metadata on every boot, potentially wiping eth1’s configuration. Cloud policy routing must be expressed in systemd-networkd/NetworkManager files, not via ip commands in rc.local.
  • NAT egress is the other path: many “multi-egress” requirements are really “several businesses need independent public source IPs”. The standard answer there is a NAT gateway with separate elastic IPs, not in-instance route isolation. The price is SNAT port exhaustion — I hit that on Related: SNAT Port Exhaustion in the Cloud, where four egress IPs collapsed under 20K long-lived connections and only recovered after expanding IPs and governing connection reuse.

One sentence for the cloud: whatever the platform can do (NAT gateway, dedicated EIP), don’t do inside the instance; whatever must live inside the instance, write as persistent config, exactly as on bare metal.

7. Deployment Checklist: Eight Items

A finished configuration is not a working one. Each of these eight items corresponds to a production failure I’ve seen.

7.1 Return Routing: The Far End Is the Real Bottleneck

Your host can be perfectly configured and still fail if the far end doesn’t know where your source address lives. Before the change, confirm with the network team: does the device at the far end of the dedicated line have a return route to your source address, and is there a source-IP-based security policy? This item isn’t on your machine, and its failure rate is no lower than your own configuration’s.

7.2 rp_filter: The Number One Suspect for Silent Drops

rp_filter (reverse path filtering) runs after PREROUTING and before INPUT: it swaps source and destination, performs another route lookup, and checks whether the egress is the same NIC the packet arrived on. Three values:

ValueSemanticsEffect on multi-egress
0No validationNo drops, and no protection either
1Strict: reverse route must use the same NICThe usual killer once policy routing/VRF is configured
2Loose: reverse route only needs to be reachableThe common setting for multi-egress hosts

The trap is the merge rule: when net.ipv4.conf.all.rp_filter and net.ipv4.conf.eth1.rp_filter both exist, the kernel uses the larger value. Set the interface to 2 while all stays 1 and you’ve changed nothing. The documentation says so, but most people only look at the per-interface line.

Diagnostic signature: tcpdump shows inbound packets, ss -lntp shows a listener, and iptables -vnL INPUT counters don’t move — that’s almost certainly rp_filter.

7.3 Dual NICs in the Same Subnet: ARP Flux

If two NICs end up in the same subnet (easy to do accidentally in “intranet plus device network” setups), you hit ARP flux: whichever NIC receives the “who has IP X” broadcast may answer on behalf of the other NIC’s address, so the peer’s MAC table keeps flipping between ports — intermittent reachability, wildly variable latency.

Two parameters are the standard fix:

# arp_ignore=1: answer only for addresses actually on the receiving NIC
# arp_announce=2: advertise only source addresses in the egress NIC's subnet
# Note: set per interface; setting only all is ineffective on some kernels
sysctl -w net.ipv4.conf.eth0.arp_ignore=1
sysctl -w net.ipv4.conf.eth1.arp_ignore=1
sysctl -w net.ipv4.conf.eth0.arp_announce=2
sysctl -w net.ipv4.conf.eth1.arp_announce=2

The better answer is don’t share the subnet — use different subnets and the problem doesn’t exist. Two NICs in one subnet physically violates “one subnet, one broadcast domain”; patching it with kernel parameters is second-best.

7.4 Stale linkdown Connected Routes

After a NIC has been physically down, its connected route can linger in the table flagged linkdown. That route participates in rp_filter’s reverse lookup and causes drops because “ingress and reverse egress disagree”. Cleaning up is trivial:

ip route show | grep linkdown
ip route del 10.20.0.0/24 dev eth1   # confirm nothing depends on it first

This is much safer than turning rp_filter off, because it fixes the cause.

7.5 Leave Gaps in Rule Priorities

ip rule is evaluated in ascending priority. I start at 100 and space by 10 or 50 — not for aesthetics, but so future insertions don’t require renumbering everything. I’ve seen the failure: three rules at 100/101/102, a new rule that had to sit in the middle, a full renumber, one ordering mistake during the renumber, and 30 seconds of intranet outage.

7.6 Verify Persistence With an Actual Reboot

Running reboot once after configuring is worth ten runbooks. Verify three things: your rules are in ip rule show, the contents of ip route show table 100 are intact, and a newly created connection really uses the correct egress. For the third, use ip route get, not ping.

7.7 Add a Synthetic Probe

# Hit both every minute; both must be green. One-sided green means an egress problem
curl -s -o /dev/null -w '%{http_code} %{time_total}\n' --interface 192.168.10.21 https://intranet.example/health
curl -s -o /dev/null -w '%{http_code} %{time_total}\n' --interface 10.20.0.21 https://partner.example/health

curl --interface forces a specific source address, which is equivalent to “leave via this path”. Ship both results into monitoring with an alert on “either path failing three times in a row” and you’ll detect egress problems before the business reports them. This was the cheapest and most useful item in my remediation list.

7.8 Load Testing: Don’t Judge Performance With ping

There is exactly one way to know whether an isolation approach survives your workload: run iperf3 on the target topology.

# Server side (on the far end of the dedicated line)
iperf3 -s -p 5201

# Client: single stream, reverse, multi-stream, small packets
iperf3 -c 203.0.113.9 -t 30                  # single stream upstream
iperf3 -c 203.0.113.9 -t 30 -R               # single stream downstream
iperf3 -c 203.0.113.9 -t 30 -P 8             # 8 parallel streams: aggregate bandwidth
iperf3 -c 203.0.113.9 -t 30 -l 64 -P 8       # 64-byte packets: pps ceiling

Each round answers a different question: single stream shows whether one connection fills the link; parallel streams show aggregate bandwidth and CPU scaling; the 64-byte round is the one that actually separates the approaches — policy routing barely notices, while the netns path visibly suffers, because every packet crosses a backlog queue.

While it runs, watch three kernel-side signals:

sar -n DEV 1 10                   # per-NIC pps and bandwidth: confirm traffic really uses eth1
mpstat -P ALL 1 10                # which core saturates on softirq (the %soft column)
head -1 /proc/net/softnet_stat    # first column is backlog drops; growth means queue overflow

Growth in that softnet_stat column is the most overlooked signal: the application layer reports “higher latency” while the kernel reports “packets dropped”. When the two disagree, look at that file first.

I won’t give universal thresholds — workloads differ too much. Here’s the decision logic instead: if during the test %soft is approaching a single core’s ceiling while link bandwidth is only at 40%, the bottleneck is the isolation layer, not the link. Then either change approach (VRF or policy routing), spread softirq with RPS/RFS, or accept it and guard the pps ceiling in monitoring.

8. Pitfalls You Only Learn by Hitting Them

Pitfall 1: route changes only affect new connections. We covered the reason (sockets cache egress and source address), but the corollary is more useful than the symptom: during a rolling deployment that coincides with a route change, new Pods/processes take the new path while old ones keep the old one, so new and old instances of one service behave differently. “Half the requests succeed during canary” is, eight times out of ten, a route change landing mid-deployment.

Pitfall 2: ip route add table N default does not bring the connected route along. I’ve seen this in three different teams. A table with only default is not a usable egress; add the dev ethX connected route.

Pitfall 3: iif lo in ip rule is not “traffic originating locally”. It matches “any packet whose ingress is lo”, and locally originated packets do participate in the initial lookup with lo as ingress. Some articles use iif lo to catch all outbound traffic; it can work in some setups but also matches other traffic on lo, so the semantics are muddy. If you mean source address, write from.

Pitfall 4: the unreachable catch-all in a VRF is not optional. Without it, a miss inside the table falls through to main, producing “half isolation” — harder to diagnose than no isolation at all, because the business works.

Pitfall 5: tcpdump -i any will lie to you with VRFs and namespaces. any is a pseudo-interface that drops packets and mangles timestamps on some versions, and it mixes traffic from different VRFs. When locating an egress problem, always name the interface: -i eth1 or -i vrf-blue.

Pitfall 6: ping success doesn’t mean the path is right. ICMP follows the connected route in main; business traffic follows the table you just configured. The two can disagree completely. Always validate with ip route get plus one real business request.

Pitfall 7: the local table doesn’t honor your splitting rules. Of the three built-in tables, local (255) is kernel-maintained and has the highest priority. After you move an address out of main, packets to that address from outside still hit local first and get delivered locally — but the host’s reply may now carry the other NIC’s source address, producing “it connects, then drops after a while”. This is most visible with VRF, because the local table is shared across all VRFs.

Pitfall 8: NIC names change. On multi-NIC and multi-cloud hosts, eth0/eth1 differ across distros and kernel parameters (net.ifnames, biosdevname): ens5, enp1s0, eth1 all occur. Any persistent config using Match Name= or MAC binding must reckon with this: after a machine change the NIC name changes and your rules silently stop applying — no error, traffic simply uses the default egress. My habit is to write both Name=eth1 and a MACAddress= fallback, then run an assertion script after deployment that checks the real names from ip link.

9. Appendix: A Reusable Egress Diagnostic Script

All the commands scattered above, folded into one function you can paste into a terminal during an incident. Give it “destination + expected source”, get a full snapshot from rules to kernel decision.

#!/usr/bin/env bash
# egress.sh —— one-shot egress diagnosis for multi-homed hosts
# usage: egress.sh <dst-ip> [expected-src-ip]
set -uo pipefail

DST="${1:?usage: egress.sh <dst-ip> [src-ip]}"
SRC="${2:-}"

echo "=== 1. Routing rules (ascending priority; earlier wins) ==="
ip rule show

echo
echo "=== 2. Custom table contents ==="
for t in $(ip rule show | awk '/lookup/ && $2+0 >= 100 && $2+0 < 32766 {print $NF}' | sort -u); do
  [ "$t" = "main" ] && continue
  echo "--- table $t ---"
  ip route show table "$t" 2>/dev/null
done

echo
echo "=== 3. Actual kernel decision ==="
if [ -n "$SRC" ]; then
  echo "-- egress (locally initiated, source $SRC) --"
  ip route get "$DST" from "$SRC"
  echo "-- return (reply to a packet arriving on eth1) --"
  ip route get "$DST" iif eth1 from "$SRC"
else
  ip route get "$DST"
fi

echo
echo "=== 4. Kernel parameters (note: all and per-interface take the max) ==="
for k in rp_filter arp_ignore arp_announce; do
  printf '%-14s all=%s\n' "$k" "$(sysctl -n net.ipv4.conf.all.$k 2>/dev/null)"
  for i in $(ls /sys/class/net | grep -Ev '^(lo|veth|br-|vrf-)'); do
    printf '%-14s %-6s=%s\n' "" "$i" "$(sysctl -n net.ipv4.conf.$i.$k 2>/dev/null)"
  done
done

echo
echo "=== 5. Suspicious leftovers ==="
ip route show | grep -E 'linkdown|dead' || echo "  no linkdown route"
echo
echo "=== 6. Connection counts (are connections even being created?) ==="
ss -s | head -3

Design notes:

  • Step 2 lists only custom tables with priority between 100 and 32766, skipping local/main/default to keep the output readable;
  • Step 3 must include from; without a source address, ip route get reflects the default egress and tells you nothing about whether your rules work;
  • Step 4 prints both all and every interface, because the max-value merge rule for rp_filter is the most frequently missed detail;
  • Step 6 uses ss -s to show connection state distribution — if timewait explodes while estab doesn’t grow, connections aren’t being established, so the problem is egress, not the application.

With it, the incident in section 2 would be localized in one minute instead of twenty — provided someone remembers to run the script instead of suspecting the firewall. That’s exactly why I keep it as a script rather than a document: documents get skipped, aliases don’t.

Summary

Back to the opening question: why does plugging in a second cable break the intranet?

Because Linux’s default routing is one-dimensional — one main table, destination address only. Writing two gateways is really writing two values into one cell, and one of them will never take effect. When the ineffective one happens to be the path the business needs, you get “NIC up, gateway reachable, business broken” — the most expensive symptom to chase.

The three approaches again, this time with scenarios:

  • Policy routing: split by source address or mark. Small change, fast rollback. Fits a single host with two egresses, one or two processes needing the dedicated line, and a tight change window. Precondition: a manageable number of rules (a dozen or so) and someone on the team who understands ip rule ordering.
  • netns: a whole independent protocol stack. Fits “this process should not even see the intranet” hard isolation, or two mutually invisible services on the same port. Does not fit plain egress isolation.
  • VRF: kernel-native L3 routing domains, the best answer for multi-tenant and multi-business-line setups. The price is applications that can bind devices, a sufficient kernel version, and rewriting ExecStart.

And the three side roads: bond solves link reliability, not egress selection; ECMP aggregates bandwidth across homogeneous egresses and cannot express “who goes where”; in the cloud, prefer platform capabilities (NAT gateway, dedicated EIP) and, when you must work inside the instance, write persistent configuration exactly as on bare metal.

If you remember one sentence: decide what you are isolating — egress, process, or routing domain — before choosing the approach. Using a process-isolation tool to solve an egress problem costs throughput and troubleshooting effort; using an egress-isolation tool to solve a multi-tenant problem costs a rule explosion.

One last point that may be unwelcome: across all three approaches, what breaks most often is never the configuration itself, but its persistence. An ip rule add typed in a shell is always correct when you test it, and always absent after a reboot. So my order is fixed: write the persistent configuration and rollback script first, then run the temporary command to verify — in the opposite order, I’ve been paged at 2 AM to reapply configuration far too many times.

References & Acknowledgments

This article draws on the following sources; thanks to their authors:

  1. Virtual Routing and Forwarding (VRF) — Linux kernel networking documentation; the design of the VRF device, l3mdev rules, tcpdump/netfilter scope, and nesting behavior all follow this reference
  2. ip-rule(8) — Linux manual page — iproute2 manual covering rule selectors (from/iif/fwmark) and priority semantics
  3. ip-route(8) — Linux manual page — multi-table operations, the unreachable route type, and ip route get
  4. Reusing the same IP address on different interfaces — Red Hat RHEL 9 networking guide; persistent VRF configuration and table binding
  5. Starting a service within an isolated VRF network — Red Hat RHEL 8 documentation on ip vrf exec and systemd drop-ins
  6. systemd.network — systemd manual — syntax for [RoutingPolicyRule], RouteTable=, and VRF=
  7. systemd.netdev — systemd manual — defining Kind=vrf in .netdev files with TableId=
  8. ip-netns(8) — Linux manual page — network namespace management and ip netns exec behavior
  9. ip-sysctl — Linux kernel documentation — authoritative semantics and merge rules for rp_filter, arp_ignore, arp_announce, and tcp_l3mdev_accept
  10. Netkit: Specializing Linux Packet Delivery for Container Networks — the 26%-31% cross-namespace throughput cost and its backlog-queue origin, the basis for the performance analysis here
  11. container-isolation-benchmarks — measured Docker veth latency overhead on kernel 6.14 (0.568 μs, about 3.1%)