DDoS Protection: Defending Against Distributed Denial-of-Service Attacks
In this tutorial, you will learn about DDoS Protection: Defending Against Distributed Denial. We cover key concepts, practical examples, and best practices to help you master this topic.
A Distributed Denial-of-Service (DDoS) attack attempts to make a service unavailable by overwhelming it with traffic from multiple sources. Attacks range from volumetric (bandwidth saturation) to application-layer (targeting specific endpoints or business logic).
flowchart TB
Attacker[Attacker Botnet] -->|Volumetric DDoS| Router[Network Router]
Attacker -->|Application DDoS| LB[Load Balancer]
Attacker -->|Slowloris| WAF[Web Application Firewall]
Router -->|Scrub| CDN[CDN / DDoS Protection]
CDN -->|Filtered| LB
WAF -->|Rate Limit| App[Application]
LB -->|Auto Scale| ASG[Auto Scaling Group]
subgraph Defense Layers
CDN
WAF
RateLimiting[Rate Limiting]
AutoScaling[Auto Scaling]
GeoBlocking[Geo-Blocking]
end
What You'll Learn
- Types of DDoS attacks: volumetric, protocol, application-layer
- Mitigation at each layer: CDN, WAF, rate limiting, auto-scaling
- Application-layer defenses: slow read, slow POST, hash collision
- DDoS response plan and runbooks
Why It Matters
DDoS attacks are increasing in frequency and sophistication. A 30-minute DDoS attack can cost an e-commerce site millions in lost revenue. Even small applications are targeted, often as a distraction for more targeted attacks.
Real-World Use
A gaming platform experiences regular DDoS attacks during peak hours. They use Cloudflare for volumetric mitigation, Nginx rate limiting for application-layer attacks, auto-scaling to absorb traffic spikes, and geo-blocking for regions without users. Average attack is mitigated within 30 seconds.
DDoS Protection Implementations
Application-Layer Rate Limiting
const rateLimit = require('express-rate-limit');
// Per-IP rate limiter
const globalLimiter = rateLimit({
windowMs: 60 * 1000,
max: 100,
message: { error: 'Too many requests' },
standardHeaders: true,
legacyHeaders: false
});
// Endpoint-specific strict limits
const searchLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
keyGenerator: (req) => req.ip
});
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 20,
keyGenerator: (req) => req.ip
});
// Slow POST protection: limit body size and rate
const bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '10kb' }));
app.use(bodyParser.urlencoded({ limit: '10kb', extended: true }));
app.use('/api/', globalLimiter);
app.use('/api/search', searchLimiter);
app.use('/api/auth', authLimiter);
Expected output:
Per IP: max 100 requests/minute globally, 10/min for search, 20/15min for auth. Request body limited to 10KB.
Slow HTTP Attack Protection
const http = require('http');
const server = http.createServer(app);
// Timeout configuration for slow attack protection
server.headersTimeout = 10000; // 10 seconds to receive headers
server.requestTimeout = 30000; // 30 seconds total request time
server.keepAliveTimeout = 5000; // 5 seconds keep-alive
server.timeout = 30000; // 30 seconds socket timeout
// Express middleware for slow read protection
app.use((req, res, next) => {
req.setTimeout(30000, () => {
console.warn('Request timeout from', req.ip);
res.status(408).end();
});
next();
});
// Limit concurrent connections per IP
const connectionCounts = new Map();
app.use((req, res, next) => {
const ip = req.ip;
const count = connectionCounts.get(ip) || 0;
if (count > 10) {
return res.status(429).json({ error: 'Too many concurrent connections' });
}
connectionCounts.set(ip, count + 1);
res.on('finish', () => {
connectionCounts.set(ip, (connectionCounts.get(ip) || 1) - 1);
});
next();
});
Expected output:
Slowloris attacks are mitigated by header and request timeouts. Slow read attacks are blocked by request timeout. Concurrent connection limit prevents connection exhaustion.
CDN and WAF Integration
// Nginx configuration for CDN/WAF-like protection
// /etc/nginx/nginx.conf
events {
worker_connections 1024;
}
http {
limit_req_zone $binary_remote_addr zone=ddos:10m rate=30r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
listen 80;
# Limit connection rate
limit_req zone=ddos burst=20 nodelay;
limit_conn conn_limit 10;
# Block common attack patterns
if ($http_user_agent ~* (bot|crawler|spider)) {
# Allow legitimate bots
}
# Geo-blocking
# allow specific countries only
location / {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
Expected output:
30 requests/second per IP with burst of 20. Max 10 concurrent connections per IP. Attackers are quickly blocked while legitimate users have headroom.
Common Mistakes
- Relying only on scaling to absorb DDoS attacks — auto-scaling increases costs significantly during attacks and may not scale fast enough.
- Not rate-limiting at multiple layers (CDN, WAF, application) — a single layer can be bypassed.
- Blocking all traffic from countries you don't serve — geo-blocking is effective but can block legitimate users via VPNs.
- Not having a DDoS response plan — during an attack, trying to figure out what to do wastes critical minutes.
- Ignoring application-layer attacks — volumetric defenses do not protect against slowloris or hash collision attacks.
Practice Questions
- What is the difference between volumetric and application-layer DDoS?
- How does a CDN protect against DDoS?
- What is a slowloris attack and how do you prevent it?
- How does auto-scaling help during a DDoS attack?
- What is geo-blocking and when is it appropriate?
Challenge
Design a multi-layer DDoS protection Strategy for a payment API. Implement: (1) CDN-level rate limiting, (2) Nginx connection limits, (3) application-level rate limiting per endpoint, (4) slow request timeouts, (5) geo-blocking for unauthorized regions, and (6) auto-scaling policies.
FAQ
Mini Project
Set up a DDoS protection test environment. Use Nginx as a reverse proxy with rate limiting and connection limits. Configure application-level rate limiting in Express. Write a load test that simulates a DDoS attack (100 concurrent connections) and verify that the defense layers protect the application.
What's Next
Continue to API Key Security to learn about securing API key authentication.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro