DDoS Protection: Defending Your Systems Against Distributed Attacks
Distributed Denial of Service (DDoS) attacks remain one of the most disruptive threats to online services. By overwhelming systems with massive volumes of traffic from thousands of sources simultaneously, attackers can bring down even well-architected applications. This guide covers attack types, mitigation strategies at every layer, and practical implementation using modern cloud services. Understanding DDoS protection is essential for system design interviews and real-world operations.
Types of DDoS Attacks
Attack Categories
| Category | OSI Layer | Target | Volume |
|---|---|---|---|
| Volumetric | Layer 3/4 | Network bandwidth | Tbps scale |
| Protocol | Layer 3/4 | Server resources (connection tables) | Millions of packets/sec |
| Application | Layer 7 | Application resources (CPU, memory, DB) | Low bandwidth, high impact |
Volumetric Attacks
These attacks flood the network pipe with massive traffic to saturate bandwidth.
| Attack | Mechanism | Amplification Factor |
|---|---|---|
| UDP Flood | Sends massive UDP packets to random ports | 1x (direct) |
| DNS Amplification | Spoofed DNS queries to open resolvers | 28-54x |
| NTP Amplification | Exploits NTP monlist command | 556x |
| Memcached Amplification | Exploits exposed Memcached servers | 10,000-51,000x |
| ICMP Flood (Ping Flood) | Overwhelming ICMP echo requests | 1x (direct) |
Protocol Attacks
These exploit weaknesses in network protocols to exhaust server or firewall resources.
SYN Flood: Sends thousands of TCP SYN packets without completing the three-way handshake. The server allocates resources for each half-open connection, eventually exhausting its connection table.
# Linux kernel tuning for SYN flood mitigation
# Enable SYN cookies (handles SYN floods without connection state)
sysctl -w net.ipv4.tcp_syncookies=1
# Reduce SYN-ACK retries
sysctl -w net.ipv4.tcp_synack_retries=2
# Increase SYN backlog
sysctl -w net.ipv4.tcp_max_syn_backlog=65536
# Reduce TIME_WAIT connections
sysctl -w net.ipv4.tcp_fin_timeout=15
Application Layer Attacks (Layer 7)
The most sophisticated attacks that mimic legitimate traffic, making detection difficult.
| Attack | Mechanism | Why It is Effective |
|---|---|---|
| HTTP Flood | Massive legitimate-looking HTTP requests | Passes firewall rules, hard to distinguish |
| Slowloris | Opens connections and sends headers very slowly | Exhausts connection pool with minimal bandwidth |
| R-U-Dead-Yet (RUDY) | Sends POST data extremely slowly | Holds server threads waiting for body |
| Cache Busting | Random query parameters bypass cache | Forces origin server processing for every request |
Mitigation Strategies
CDN-Based Protection
Content Delivery Networks absorb attack traffic across their globally distributed edge network. Traffic never reaches your origin server. This is the single most effective defense against volumetric attacks.
# Cloudflare Worker for advanced rate limiting
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const ip = request.headers.get('CF-Connecting-IP')
// Check rate limit using Cloudflare KV
const key = `rate:${ip}`
const count = parseInt(await RATE_LIMITS.get(key) || '0')
if (count > 100) {
return new Response('Rate limited', {
status: 429,
headers: { 'Retry-After': '60' }
})
}
await RATE_LIMITS.put(key, String(count + 1), { expirationTtl: 60 })
return fetch(request)
}
Anycast Routing
Anycast advertises the same IP address from multiple data centers worldwide. Attack traffic is automatically distributed across all locations, preventing any single point from being overwhelmed. Both Cloudflare and AWS use Anycast for DDoS protection.
Auto-Scaling as Defense
Auto-scaling cannot fully stop a DDoS attack, but it can maintain service during moderate attacks and buy time for mitigation.
# AWS Auto Scaling policy with DDoS-aware scaling
# CloudFormation template
Resources:
ScalingPolicy:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AutoScalingGroupName: !Ref WebServerASG
PolicyType: TargetTrackingScaling
TargetTrackingConfiguration:
PredefinedMetricSpecification:
PredefinedMetricType: ALBRequestCountPerTarget
ResourceLabel: !Sub "${ALB}/${TargetGroup}"
TargetValue: 1000
ScaleInCooldown: 300
ScaleOutCooldown: 60 # Scale out quickly during attack
Cloud DDoS Protection Services
AWS Shield
| Feature | Shield Standard (Free) | Shield Advanced ($3,000/month) |
|---|---|---|
| Layer 3/4 Protection | Automatic | Enhanced with real-time detection |
| Layer 7 Protection | Not included | Yes (with AWS WAF) |
| DDoS Response Team | No | 24/7 access to AWS DRT |
| Cost Protection | No | Credit for scaling costs during attack |
| Real-Time Metrics | Basic | Detailed attack diagnostics |
Cloudflare Protection Tiers
| Feature | Free | Pro ($20/mo) | Business ($200/mo) | Enterprise |
|---|---|---|---|---|
| DDoS Mitigation | Unmetered | Unmetered | Unmetered | Unmetered |
| WAF Rules | Limited | Managed rules | Custom + managed | Advanced custom |
| Bot Management | Basic | Basic | Basic | Advanced ML-based |
| Rate Limiting | 1 rule | 10 rules | 15 rules | Unlimited |
| SLA | None | None | 100% uptime | 100% uptime + SLA |
Application-Layer Defense
const express = require('express');
const app = express();
// Defense 1: Request timeout (Slowloris protection)
app.use((req, res, next) => {
req.setTimeout(5000, () => {
res.status(408).end();
});
next();
});
// Defense 2: Body size limits
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ limit: '10kb', extended: true }));
// Defense 3: Connection limits per IP
const connectionCounts = new Map();
const MAX_CONNECTIONS_PER_IP = 50;
app.use((req, res, next) => {
const ip = req.ip;
const count = connectionCounts.get(ip) || 0;
if (count >= MAX_CONNECTIONS_PER_IP) {
return res.status(429).json({ error: 'Too many connections' });
}
connectionCounts.set(ip, count + 1);
res.on('finish', () => {
const current = connectionCounts.get(ip) || 1;
connectionCounts.set(ip, current - 1);
});
next();
});
// Defense 4: Challenge suspicious requests
app.use('/api/expensive-endpoint', (req, res, next) => {
const hasValidToken = req.headers['x-challenge-token'];
if (!hasValidToken) {
return res.status(403).json({
error: 'challenge_required',
challenge: generateChallenge()
});
}
next();
});
Monitoring and Alerting
// DDoS detection metrics to monitor
const metrics = {
// Traffic anomalies
requestsPerSecond: 'Alert if > 10x baseline',
uniqueIPsPerMinute: 'Alert on sudden spike',
bandwidthMbps: 'Alert if > 5x normal',
// Application health
errorRate5xx: 'Alert if > 5%',
responseTimeP99: 'Alert if > 3x baseline',
connectionPoolUsage: 'Alert if > 80%',
// Infrastructure
cpuUtilization: 'Alert if > 85% across fleet',
memoryUsage: 'Alert if > 90%',
networkIn: 'Alert on anomalous patterns'
};
// CloudWatch alarm example
{
"AlarmName": "HighRequestRate",
"MetricName": "RequestCount",
"Namespace": "AWS/ApplicationELB",
"Statistic": "Sum",
"Period": 60,
"EvaluationPeriods": 2,
"Threshold": 50000,
"ComparisonOperator": "GreaterThanThreshold"
}
Incident Response Playbook
- Detect — Automated alerts trigger when traffic exceeds thresholds. Monitor dashboards for anomalous patterns.
- Classify — Determine attack type (volumetric, protocol, or application layer) to apply the right mitigation.
- Mitigate — Enable rate limiting rules, activate WAF rules, engage CDN DDoS protection, scale infrastructure.
- Communicate — Update status page, notify stakeholders, engage cloud provider support (AWS DRT if using Shield Advanced).
- Analyze — Post-incident: identify attack vectors, review what worked, update rules and thresholds.
- Harden — Apply lessons learned: update WAF rules, improve monitoring, add geographic blocks if appropriate.
For comprehensive API security that includes DDoS protection strategies, rate limiting algorithms, and defense-in-depth patterns, explore our full security guide. Test your infrastructure resilience with our API and Network Tools.
Defense Architecture Summary
| Layer | Defense | Handles |
|---|---|---|
| DNS | Anycast, DNS filtering | DNS amplification attacks |
| Edge / CDN | Cloudflare, AWS CloudFront | Volumetric attacks (absorbs traffic) |
| Network | ACLs, blackhole routing, scrubbing | Protocol attacks, IP-based filtering |
| WAF | Rule-based filtering, bot detection | Application layer attacks |
| Application | Rate limiting, timeouts, challenges | Slowloris, HTTP floods |
| Infrastructure | Auto-scaling, redundancy | Maintaining availability during attack |
Frequently Asked Questions
Can DDoS attacks be completely prevented?
No DDoS attack can be 100% prevented, but the impact can be minimized to near-zero. The goal is mitigation — absorbing and filtering attack traffic while maintaining service for legitimate users. CDN-based protection like Cloudflare can handle attacks exceeding 1 Tbps. The key is having protection in place before an attack occurs, not scrambling during one.
How much does DDoS protection cost?
Cloudflare provides basic DDoS protection on their free plan. AWS Shield Standard is free for all AWS customers. For enterprise-grade protection, Cloudflare Business starts at $200/month, and AWS Shield Advanced costs $3,000/month. The cost of not having protection (downtime, revenue loss, reputation damage) almost always exceeds the protection cost.
How do I tell the difference between a DDoS attack and a traffic spike?
Legitimate traffic spikes show gradual ramp-up, diverse geographic distribution, normal user behavior patterns, and correlated with events (marketing campaigns, product launches). DDoS attacks show sudden spikes, repetitive patterns, unusual geographic concentrations, abnormal HTTP headers, and no business correlation. Advanced monitoring tools use ML to distinguish the two automatically.
What should I do if I am currently under DDoS attack?
Immediately: (1) Enable your CDN's "under attack" mode. (2) Activate all WAF rules. (3) Contact your cloud provider's DDoS response team. (4) Scale infrastructure if possible. (5) Update your status page. Do not try to fight the attack at your origin server — push mitigation to the edge. Most cloud DDoS protection services can be activated within minutes. Explore encryption and zero trust for additional security layers, and visit our Security Crypto Tools for testing.