How to prevent DDoS attacks: layered defenses and what to do when you are hit
There is no single fix for DDoS. Host firewall and kernel settings handle small floods, anything above your port speed needs upstream scrubbing, and beyond that a DDoS-protected IP or CDN. Under attack: identify the type, switch to protection, call your provider, preserve evidence.
How to prevent DDoS attacks comes down to matching the defense to the size of the attack. Floods that stay below your server’s port speed, such as a SYN flood or connection exhaustion, can be handled on the host with kernel settings and a firewall. Once the attack exceeds the port speed, nothing on the host matters: only your hosting provider’s traffic scrubbing or blackhole routing can help. Larger attacks require putting the service behind a DDoS-protected IP or CDN so the vendor’s scrubbing centers absorb the traffic. HTTP floods at the application layer are a separate problem, solved by rate limiting, a WAF and bot challenges. This guide gives the layered plan first, then the order of operations when you are under attack.
Layered DDoS protection: what each layer can stop
| Layer | Measures | Stops | Rough ceiling | Who does it |
|---|---|---|---|---|
| Host | Kernel tuning, iptables/nftables, disabling unused services | SYN floods, small connection floods, scans from a few sources | Limited by port speed and CPU; a 1 Gbps port hit with 2 Gbps is saturated regardless | Server admin |
| Hosting provider | Uplink headroom, out-of-path scrubbing appliances, blackhole routing | Volumetric attacks: UDP floods, reflection/amplification, large SYN floods | The scrubbing capacity in your contract, typically tens to hundreds of Gbps; above that the IP is blackholed | Data center / hosting provider |
| DDoS-protected IP / CDN | Route all traffic through the vendor’s scrubbing centers; origin hidden | Large volumetric attacks; some products also filter layer 7 | The vendor’s advertised protection bandwidth, usually far above a single data center’s scrubbing capacity | You, by subscribing and onboarding |
| Application | Nginx rate limits, WAF, CAPTCHA/JS challenges, caching | HTTP floods, slow-rate attacks, API abuse | Limited by backend capacity, independent of bandwidth | Application / ops team |
The point of this table: a layer only needs to act when the layer below cannot cope, and each ceiling is hard. Buying protected bandwidth does not secure the application layer, and host tuning never replaces upstream scrubbing. The next four sections cover what to do at each layer.
Provider layer: bandwidth headroom, scrubbing and blackholing
Protection at the hosting provider usually has three parts:
- Bandwidth headroom: uplinks with spare capacity, so an attack does not immediately saturate the whole data center’s edge;
- Traffic scrubbing: NetFlow/sFlow detection spots anomalies, the attacked IP’s route is diverted to out-of-path scrubbing appliances, and clean traffic is reinjected to the server;
- Blackhole routing (RTBH): when an attack exceeds scrubbing capacity or the contract threshold, the upstream routes the IP to a null interface, sacrificing one IP to protect the rest of the network.
Before signing, ask for these numbers: the scrubbing trigger threshold, the blackhole threshold, how long an IP stays blackholed, whether scrubbing is billed separately, and whether you can get a replacement IP during an attack. Those terms define your options when an attack happens.
DDoS-protected IP and CDN: hide the origin
A DDoS-protected IP works by passing all traffic through the vendor’s scrubbing nodes before forwarding it to your origin. Onboarding steps:
- Add forwarding rules in the vendor console: port forwarding for layer 4 services (for example TCP 443 → origin IP:443), or the domain name plus TLS certificate for layer 7 services;
- Change the origin firewall to allow only the vendor’s egress IP ranges on service ports and drop everything else;
- Point DNS at the protected IP, having lowered the TTL to 300 seconds or less beforehand so later changes propagate quickly;
- Change the origin IP: the old one is already known to attackers, so keeping it undoes the work;
- Close the leaks: historical DNS records, sending mail server addresses in email headers, and subdomains not behind protection (certificate transparency logs list every hostname you have issued a certificate for).
A CDN hides the origin the same way and can additionally serve static content from the edge. In both cases the firewall rule is the critical piece; without it an attacker bypasses protection and hits the origin directly.
Host layer: firewall and kernel tuning
Host-level measures only work against attacks smaller than your port speed, but they cost nothing and can be done right now. On Linux, start with kernel parameters:
cat >> /etc/sysctl.conf <<'CONF'
# SYN cookies: keep accepting connections when the SYN backlog is full
net.ipv4.tcp_syncookies = 1
# Half-open and accept queue lengths
net.ipv4.tcp_max_syn_backlog = 65536
net.core.somaxconn = 65535
# Fewer SYN+ACK retries so half-open connections time out faster
net.ipv4.tcp_synack_retries = 2
# NIC receive queue
net.core.netdev_max_backlog = 262144
CONF
sysctl -p
Then use iptables to cap concurrent connections and the new-connection rate per source:
# Drop when a single source IP holds more than 50 connections to 80/443
iptables -A INPUT -p tcp -m multiport --dports 80,443 \
-m connlimit --connlimit-above 50 --connlimit-mask 32 -j DROP
# Drop when a single source IP opens more than 30 new connections per second (burst 60)
iptables -A INPUT -p tcp --syn -m hashlimit --hashlimit-name syn \
--hashlimit-mode srcip --hashlimit-above 30/second --hashlimit-burst 60 -j DROP
# Drop packets with an invalid connection state
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
Also check that your server is not exposing services that can be abused for reflection: open DNS recursion, NTP monlist, SSDP, memcached on port 11211. Leaving these open turns your server into an amplifier for attacks on others, and your provider may shut your port in response.
Application layer: rate limiting and bot challenges
If bandwidth is fine but the site is down, the problem is usually at the application layer. In Nginx, limit the request rate and concurrent connections per client IP:
http {
limit_req_zone $binary_remote_addr zone=req_per_ip:10m rate=20r/s;
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
server {
location / {
limit_req zone=req_per_ip burst=40 nodelay;
limit_conn conn_per_ip 30;
}
}
}
Tune the thresholds to your traffic: a static site can be strict, while an API must allow for many users behind one NAT address. Above that sit WAF rules, JavaScript or CAPTCHA challenges for suspicious clients, and caching every page you can, so attack requests never reach the database.
What to do during a DDoS attack: step by step
Do not start by changing configuration. Work through these steps in order.
1. Confirm it is an attack, and which kind
Three indicators separate the types:
# Connection summary: a very high SYN-RECV count means a SYN flood
ss -s
ss -ant state syn-recv | wc -l
# Established connections by source: a few IPs dominating means a connection or layer 7 attack
ss -ant state established | awk 'NR>1{split($4,a,":");print a[1]}' | sort | uniq -c | sort -rn | head
- Inbound bandwidth saturated and packet rate spiking on your graphs → volumetric attack (UDP flood, reflection/amplification). Nothing on the host will help; go straight to step 2;
- Bandwidth moderate but half-open connections spiking → SYN flood. Kernel settings will hold for a while;
- Bandwidth normal but request rate and backend CPU spiking → application-layer attack. Apply rate limits and challenges.
2. Volumetric attack: call the provider, switch to protection
- Contact your provider’s NOC immediately: is the IP already blackholed, has scrubbing kicked in, and when will the IP be released;
- If you already have a protected IP or CDN, switch DNS to it. With a short TTL the cutover takes minutes;
- Without protection, consider requesting a new IP for critical services and leaving the old one in the blackhole;
- On the host, close non-essential ports and tighten connection limits temporarily. Do not expect IP blocking to help: source addresses are mostly spoofed.
3. Notify stakeholders
Post a status notice to affected customers with the scope and estimated recovery time. Hosting providers with many customers should brief sales and support at the same time, so tickets do not pile up on the front line.
4. Preserve evidence
Save evidence during the attack; without it there is no basis for a complaint to the upstream or a police report afterwards:
# Capture 10,000 packets as a sample; do not run a long capture on a struggling server
tcpdump -i eth0 -c 10000 -w /tmp/ddos-$(date +%F-%H%M).pcap
Add screenshots of monitoring graphs, the attack report from your provider or protection vendor, and any extortion emails or chat messages.
5. Post-incident review
- Replace the exposed origin IP and confirm the new one only accepts the protection vendor’s egress ranges;
- Review alert thresholds: the gap between the attack starting and the first human noticing is the number to shrink;
- Compare the attack size with your current protection ceiling and decide whether to upgrade the scrubbing plan or buy a protected IP;
- Write a one-page runbook with DNS TTLs, forwarding rules and provider contacts, so nobody is searching for them next time.
For hosting providers: keep one server from taking down a row
For a hosting provider, one attacked server often affects every other customer on the same switch or uplink. Automatic bandwidth limiting in Toplink DCIM watches average bandwidth over a recent time window, throttles the switch port to a set rate when a threshold is crossed, and lifts the limit once traffic falls back and stays stable, confining the impact to a single port. Customers can also see their own traffic and attack events in the customer portal instead of waiting for support to explain what happened.
FAQ
How long does a blackholed IP stay offline?
That is set by your hosting provider or their upstream carrier. A common policy is automatic release a fixed time after the attack stops, but check your contract. While blackholed, all traffic to that IP is dropped, including legitimate visitors.
Does changing my IP address stop a DDoS attack?
Only briefly. If the new IP is published in DNS the attacker will find it within minutes. Change the IP and at the same time move the origin behind a DDoS-protected IP or CDN, and allow only the protection service's egress ranges to reach it.
Should I use a DDoS-protected IP or a protected CDN?
It depends on the protocol. Game servers and other non-HTTP TCP or UDP services can only use a protected IP with layer 4 port forwarding. Websites and APIs are better served by a CDN or layer 7 protection, which can cache static content and filter on request patterns. The two can be combined.