Course contentsShow
← Linux
Lesson 1165 of 1,81910. Network Administration and Kernel StacksFree lesson

Rate Limiting and DDoS Mitigation

Implement kernel-level throttling to protect services from flood attacks.

In this lesson, you will learn how to implement kernel-level packet throttling to prevent service exhaustion during volumetric flood attacks.

When your server is bombarded with more requests than it can handle, the goal of DDoS mitigation is to drop malicious traffic as early as possible—before it reaches the user-space applications or consumes excessive CPU cycles. By leveraging the nftables or iptables hooks we previously studied, we can implement "rate limiting" directly within the kernel stack.

Token Bucket Filtering (TBF) Mechanics

The most efficient way to throttle traffic is using the Token Bucket algorithm. Imagine a bucket that fills with tokens at a fixed rate; every incoming packet must "spend" a token to pass through the filter. If the bucket is empty, the packet is discarded.

In Linux, we implement this using the limit match module. This is significantly faster than application-level filtering because the kernel processes the packet based on metadata before passing it up the stack.

Implementation Example

If you want to protect a specific service (like an SSH port or a web API) from being overwhelmed, you can define a rule that allows a burst of traffic but enforces a strict sustained limit. Using nftables, you can enforce this per source IP to prevent a single malicious actor from monopolizing your bandwidth:

# Allow only 10 connections per minute per IP, with a burst of 5
nft add rule ip filter input tcp dport 80 add @flood_set { ip saddr limit rate 10/minute burst 5 packets } counter accept

By defining a set to track these sources, the kernel keeps a high-performance state table of which IPs are being throttled. This effectively "drops" the attack at the hardware-interrupt or early-netfilter layer, ensuring that your application processes only legitimate, well-behaved traffic.

When configuring these rules, always ensure your burst limits are high enough to accommodate legitimate traffic spikes, but low enough to maintain service availability during a sustained flood. By dropping these packets at the kernel level, you prevent the kernel’s connection tracking (conntrack) table from filling up, which is often the first point of failure during a DDoS event.

Key Takeaway: Kernel-level rate limiting using the token bucket algorithm allows you to discard malicious traffic at the earliest possible stage, preserving system resources for legitimate requests.