Prioritize VoIP and Critical Traffic on Linux with DiffServ/DSCP Using iptables and tc

Networking tutorial - IT technology blog
Networking tutorial - IT technology blog

Comparing Linux QoS Approaches: Classification vs. Scheduling

When an uplink saturates, interactive traffic takes an immediate hit. A standard G.711 VoIP call needs barely 85 kbps of bandwidth, but once jitter climbs past 30 ms or packet loss exceeds 1%, call quality collapses into choppy audio and dropped words. Linux gives you plenty of tools to schedule outbound traffic so real-time voice packets skip past bulk TCP streams. In practice, administrators rely on three core strategies:

  • Pure tc classification with filters: Traffic Control handles packet inspection and queuing on its own. It uses u32 or modern flower filters attached directly to egress root queuing disciplines (qdiscs) to match IPs, subnets, and L4 port numbers.
  • Application socket tagging (SO_PRIORITY / IP_TOS): Endpoints mark their own packets. Daemons like Asterisk, BIND, or OpenSSH make system calls on socket creation to set internal socket priorities or write DSCP bits directly.
  • Two-stage hybrid (iptables marking + tc scheduling): Netfilter inspects connection states, dynamic port ranges, or L7 patterns in the mangle table, writing standard DSCP bits into the IP header. Then, lightweight tc filters read those marks at the network interface and steer packets into prioritized hardware queues.

Pure tc filters work well for static IP ranges and fixed single ports. But writing firewall logic in tc syntax quickly becomes unmanageable when handling dynamic SIP RTP port blocks (like UDP 10000–20000) or complex connection-tracking states.

Meanwhile, trusting userland applications to tag their own packets is unreliable; third-party software often ignores DSCP entirely or uses conflicting flags. The hybrid approach gives you the best balance. Let iptables handle the deep inspection, and leave the queue scheduling to tc.

Trade-offs of the Hybrid Architecture

Before rolling this out across production gateways, consider where this design shines and where it hits limits.

Advantages

  • Decoupled operational layers: You separate classification policies from bandwidth allocations. Updating an RTP port range requires modifying a single firewall rule. You never need to rebuild your tc bandwidth tree.
  • Hardware-agnostic standards: Netfilter writes standard DiffServ Code Points into the IPv4 TOS byte or IPv6 Traffic Class field. Downstream hardware—such as Cisco or Juniper edge switches, corporate firewalls, and branch VPN appliances—can read and preserve those marks.
  • Granular connection tracking: The iptables engine inspects conntrack states, payload sizes, MAC addresses, and multiport sets far more efficiently than raw tc matching filters.

Disadvantages

  • Dual configuration files: You manage two separate toolsets (firewall rules and traffic shaping scripts). Both must be properly sequenced and persisted across reboots.
  • Netfilter CPU traversal: Packets traverse the Netfilter stack before hitting interface queuing disciplines. On high-throughput multi-gigabit gateways handling millions of packets per second, this adds measurable CPU overhead.
  • Upstream ISP bleaching: Public internet providers frequently strip DSCP bits or reset them to CS0 (Best Effort) at their network boundaries. As a result, DSCP priority primarily protects your local gateway, your uplink queue, and any private WAN or WireGuard/IPsec tunnels.

Target Architecture for VoIP and Interactive Traffic

On asymmetric lines like a 20 Mbps cable uplink or an LTE backup link, unmanaged bufferbloat can easily push round-trip times from 15 ms to over 600 ms during a large backup upload. To prevent that delay, we implement a Hierarchical Token Bucket (HTB) shaper backed by fq_codel (Fair Queuing with Controlled Delay) leaf queues across three distinct service tiers:

  1. Class 1:10 — Voice & Signaling (DSCP EF / Decimal 46 & CS3 / Decimal 24): Dedicated to RTP audio frames and SIP handshakes. This queue gets highest priority (prio 0) and a guaranteed slice of bandwidth with shallow buffering to ensure latency stays flat.
  2. Class 1:20 — Interactive Operations (DSCP AF31 / Decimal 26): Dedicated to SSH command shells, DNS lookups, and critical database synchronization. It delivers low latency and protects interactive typing from keystroke lag.
  3. Class 1:30 — Best Effort / Bulk (DSCP CS0 / Decimal 0): Catches everything else: web browsing, file downloads, package updates, and backups. It absorbs all leftover throughput after Classes 1:10 and 1:20 take their share.

Step-by-Step Implementation Guide

The following configuration assumes your egress network interface is eth0 with a provisioned upstream speed of 20 Mbps. To avoid ISP-side queue buildup, we shape total egress throughput to 19 Mbps (roughly 95% of the physical link ceiling).

Step 1: Tag Outbound Packets in iptables

We use the mangle table to stamp DSCP values. The PREROUTING chain catches transit packets routed through your Linux gateway, while the OUTPUT chain marks packets generated by local services.

# Flush existing mangle rules
sudo iptables -t mangle -F

# 1. VoIP RTP audio (UDP ports 10000-20000) -> Expedited Forwarding (EF / 46)
sudo iptables -t mangle -A PREROUTING -p udp --dport 10000:20000 -j DSCP --set-dscp-class EF
sudo iptables -t mangle -A OUTPUT -p udp --dport 10000:20000 -j DSCP --set-dscp-class EF

# 2. VoIP SIP signaling (TCP/UDP port 5060) -> Class Selector 3 (CS3 / 24)
sudo iptables -t mangle -A PREROUTING -p udp --dport 5060 -j DSCP --set-dscp-class CS3
sudo iptables -t mangle -A PREROUTING -p tcp --dport 5060 -j DSCP --set-dscp-class CS3
sudo iptables -t mangle -A OUTPUT -p udp --dport 5060 -j DSCP --set-dscp-class CS3
sudo iptables -t mangle -A OUTPUT -p tcp --dport 5060 -j DSCP --set-dscp-class CS3

# 3. Interactive SSH (TCP port 22) -> Assured Forwarding 31 (AF31 / 26)
sudo iptables -t mangle -A PREROUTING -p tcp --dport 22 -j DSCP --set-dscp-class AF31
sudo iptables -t mangle -A OUTPUT -p tcp --dport 22 -j DSCP --set-dscp-class AF31

# 4. Critical DNS queries (UDP port 53) -> AF31
sudo iptables -t mangle -A PREROUTING -p udp --dport 53 -j DSCP --set-dscp-class AF31
sudo iptables -t mangle -A OUTPUT -p udp --dport 53 -j DSCP --set-dscp-class AF31

Step 2: Build the Hierarchical Token Bucket in tc

Next, configure an HTB hierarchy on eth0. By clamping our shaper to 19 Mbps, Linux holds packets in its own queues rather than dumping them into the unmanaged buffer of an ISP modem.

# Clear existing qdiscs on eth0
sudo tc qdisc del dev eth0 root 2>/dev/null || true

# Root qdisc: default unmatched traffic routes to class 1:30
sudo tc qdisc add dev eth0 root handle 1: htb default 30

# Root class: cap maximum interface egress at 19 Mbps
sudo tc class add dev eth0 parent 1: classid 1:1 htb rate 19mbit ceil 19mbit

# Class 1:10 (VoIP): 5 Mbps guaranteed, 10 Mbps burst ceiling, top priority
sudo tc class add dev eth0 parent 1:1 classid 1:10 htb rate 5mbit ceil 10mbit prio 0

# Class 1:20 (Interactive SSH/DNS): 4 Mbps guaranteed, 15 Mbps burst ceiling
sudo tc class add dev eth0 parent 1:1 classid 1:20 htb rate 4mbit ceil 15mbit prio 1

# Class 1:30 (Best Effort): 10 Mbps guaranteed, 19 Mbps burst ceiling
sudo tc class add dev eth0 parent 1:1 classid 1:30 htb rate 10mbit ceil 19mbit prio 2

# Attach fq_codel leaf queues to keep individual streams fair within each class
sudo tc qdisc add dev eth0 parent 1:10 handle 100: fq_codel
sudo tc qdisc add dev eth0 parent 1:20 handle 200: fq_codel
sudo tc qdisc add dev eth0 parent 1:30 handle 300: fq_codel

Step 3: Route DSCP Marks to tc Classes

Now match the DSCP byte using the u32 filter. In IPv4, DSCP values occupy the upper 6 bits of the 8-bit Type of Service (TOS) field, leaving the bottom 2 bits for ECN. To match them, shift the decimal DSCP value left by 2 bits and apply a bitmask of 0xfc:

  • DSCP EF: 46 × 4 = 184 → 0xb8
  • DSCP CS3: 24 × 4 = 96 → 0x60
  • DSCP AF31: 26 × 4 = 104 → 0x68
# Map EF (0xb8) and CS3 (0x60) to VoIP Class 1:10
sudo tc filter add dev eth0 parent 1:0 protocol ip prio 1 u32 \
    match ip tos 0xb8 0xfc flowid 1:10

sudo tc filter add dev eth0 parent 1:0 protocol ip prio 1 u32 \
    match ip tos 0x60 0xfc flowid 1:10

# Map AF31 (0x68) to Interactive Class 1:20
sudo tc filter add dev eth0 parent 1:0 protocol ip prio 2 u32 \
    match ip tos 0x68 0xfc flowid 1:20

Step 4: Verify and Benchmark Queue Behavior

Validate your setup under load. You can generate synthetic saturation by launching an unthrottled upstream test with iperf3 -c <remote-ip> -u -b 25M while running an active SSH session and a voice call.

# Check iptables packet and byte match counters
sudo iptables -t mangle -L -v -n

# Inspect queue throughput, backlog size, and dropped packets
sudo tc -s class show dev eth0

# Live dashboard refreshed every second
watch -n 1 "tc -s -d class show dev eth0"

Under heavy congestion, classes 1:10 and 1:20 should show steadily climbing byte counters with zero drops and near-zero backlog. Any dropped packets or throttling backlogs should occur strictly inside class 1:30.

Step 5: Persisting Configuration Across Reboots

Netfilter rules and tc trees disappear on reboot. On Ubuntu or Debian systems, lock down the configuration with a persistent package and a dedicated systemd service unit.

# Save Netfilter mangle rules
sudo apt-get install -y iptables-persistent
sudo netfilter-persistent save

Save your tc commands into a dedicated script such as /usr/local/sbin/qos-traffic.sh, make it executable with chmod +x, and wrap it in a systemd service:

# Write /etc/systemd/system/qos-traffic.service
sudo tee /etc/systemd/system/qos-traffic.service > /dev/null << 'EOF'
[Unit]
Description=Traffic Control DSCP QoS Shaping
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/qos-traffic.sh
RemainAfterExit=true

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd and activate on boot
sudo systemctl daemon-reload
sudo systemctl enable --now qos-traffic.service

With this shaper in place, your voice calls remain crisp and command prompts stay snappy, even when background transfers pin your uplink at 100%.

Share: