DDoS Protection at the Edge: Stop Attacks Before They Reach Your Servers
Learn how to implement comprehensive DDoS protection using edge-based rate limiting. Protect your APIs from volumetric attacks, application layer floods, and sophisticated botnets.
Security Expert
• 12 min read
DDoS Protection at the Edge
Distributed Denial of Service (DDoS) attacks are growing in frequency and sophistication. Traditional on-premise solutions are expensive and complex, while basic rate limiting isn't enough against modern attacks. Edge-based protection offers the perfect solution: stop attacks at Cloudflare's global network before they consume your infrastructure resources.
Understanding Modern DDoS Attacks
DDoS attacks have evolved beyond simple volume flooding:
Volume-Based Attacks
- UDP Floods: Overwhelm network bandwidth with UDP packets
- ICMP Floods: Flood targets with ICMP Echo Request packets
- Spoofed Packet Floods: Use forged source IPs to amplify attacks
Protocol Attacks
- SYN Floods: Exploit TCP handshake process
- Ping of Death: Send malformed packets to crash systems
- Smurf Attacks: Use ICMP to amplify traffic via broadcast networks
Application Layer Attacks (Layer 7)
- HTTP Floods: Overwhelm web servers with HTTP requests
- Slowloris: Keep connections open with slow requests
- API Abuse: Target expensive endpoints to exhaust resources
Why Edge Protection Works
Traditional DDoS protection fails because:
- Attacks consume bandwidth before reaching protection
- Origin servers still process malicious traffic
- Single points of failure create vulnerabilities
- Expensive hardware required for large-scale protection
Edge protection solves these problems:
- Global distribution absorbs attacks across 300+ locations
- Infinite scale with Cloudflare's massive network capacity
- Smart filtering distinguishes legitimate from malicious traffic
- Zero infrastructure required from you
Implementing DDoS Protection with Rately
Layer 1: Basic Volume Protection
Start with fundamental protections against simple attacks:
{
"ddos_protection": {
"name": "Basic Volume Protection",
"policies": [
{
"name": "IP Rate Limiting",
"key_template": "ip:{client_ip}",
"limits": [
{
"requests": 100,
"window": "1m",
"action": "block",
"block_duration": "10m"
},
{
"requests": 1000,
"window": "1h",
"action": "challenge",
"challenge_type": "js_challenge"
}
]
},
{
"name": "Geo-based Protection",
"key_template": "country:{geo.country}",
"limits": [
{
"requests": 10000,
"window": "1m",
"action": "rate_limit",
"countries": ["high_risk_countries"]
}
]
}
]
}
}
Layer 2: Behavioral Analysis
Detect sophisticated attacks through behavior patterns:
{
"behavioral_protection": {
"name": "Smart Attack Detection",
"rules": [
{
"name": "Rapid Fire Detection",
"condition": "requests_per_second > 50 AND unique_endpoints < 3",
"action": "temporary_block",
"duration": "5m",
"confidence": 0.8
},
{
"name": "Bot Pattern Detection",
"condition": "user_agent_entropy < 0.3 AND request_timing_variance < 100",
"action": "challenge",
"challenge_type": "captcha"
},
{
"name": "Resource Exhaustion Attack",
"condition": "average_response_time > 2000 AND error_rate > 10",
"action": "throttle_aggressive",
"multiplier": 0.1
}
]
}
}
Layer 3: Machine Learning Detection
Use AI to identify advanced attack patterns:
# ML-based DDoS detection
class DDosDetectionEngine:
def __init__(self):
self.models = {
'volumetric': VolumetricAttackDetector(),
'application': ApplicationLayerDetector(),
'behavioral': BehavioralAnomalyDetector()
}
self.feature_extractors = FeatureExtractorPipeline()
def analyze_traffic(self, traffic_window):
"""Analyze traffic for DDoS indicators"""
features = self.feature_extractors.extract(traffic_window)
predictions = {}
for attack_type, model in self.models.items():
confidence = model.predict(features)
predictions[attack_type] = {
'probability': confidence,
'threshold': model.threshold,
'is_attack': confidence > model.threshold
}
return self.combine_predictions(predictions)
def combine_predictions(self, predictions):
"""Combine multiple model outputs"""
max_confidence = max(p['probability'] for p in predictions.values())
attack_types = [k for k, v in predictions.items() if v['is_attack']]
overall_confidence = min(max_confidence * len(attack_types), 1.0)
return {
'is_attack': overall_confidence > 0.7,
'confidence': overall_confidence,
'attack_types': attack_types,
'recommended_action': self.get_action(overall_confidence, attack_types)
}
def get_action(self, confidence, attack_types):
"""Determine appropriate response action"""
if confidence > 0.95:
return 'block_immediate'
elif confidence > 0.8:
return 'challenge_hard'
elif confidence > 0.6:
return 'rate_limit_aggressive'
else:
return 'monitor'
# Integration with Rately
async def update_protection_rules(analysis):
if analysis['is_attack']:
await rately.create_emergency_rule({
'name': f"DDoS Protection - {int(time.time())}",
'action': analysis['recommended_action'],
'confidence': analysis['confidence'],
'attack_types': analysis['attack_types'],
'expires_at': time.time() + 3600, # 1 hour
'auto_adjust': True
})
Advanced Protection Strategies
1. Adaptive Thresholds
Adjust protection levels based on normal traffic patterns:
{
"adaptive_protection": {
"name": "Dynamic DDoS Thresholds",
"baseline_learning": {
"period": "7d",
"update_frequency": "1h",
"metrics": [
"requests_per_minute",
"unique_ips_per_hour",
"geographic_distribution",
"user_agent_diversity",
"endpoint_coverage"
]
},
"threshold_calculation": {
"normal_multiplier": 3.0,
"suspicious_multiplier": 5.0,
"attack_multiplier": 10.0,
"confidence_adjustment": true
}
}
}
2. Progressive Response
Escalate response based on attack severity:
class ProgressiveDefenseSystem {
constructor() {
this.alertLevels = {
green: { multiplier: 1.0, actions: ['log'] },
yellow: { multiplier: 0.7, actions: ['rate_limit', 'log'] },
orange: { multiplier: 0.3, actions: ['aggressive_rate_limit', 'js_challenge', 'alert'] },
red: { multiplier: 0.1, actions: ['block_suspicious', 'captcha_all', 'emergency_alert'] },
critical: { multiplier: 0.05, actions: ['block_aggressive', 'whitelist_only', 'incident_response'] }
};
}
async assessThreatLevel(metrics) {
const indicators = {
volume: this.calculateVolumeScore(metrics),
pattern: this.calculatePatternScore(metrics),
geography: this.calculateGeoScore(metrics),
behavior: this.calculateBehaviorScore(metrics)
};
const overallScore = this.combineIndicators(indicators);
return this.scoresToLevel(overallScore);
}
async updateDefenses(threatLevel) {
const config = this.alertLevels[threatLevel];
// Update rate limiting
await rately.updateGlobalMultiplier(config.multiplier);
// Execute defensive actions
for (const action of config.actions) {
await this.executeAction(action, threatLevel);
}
// Log and alert
await this.logThreatLevelChange(threatLevel, config);
}
calculateVolumeScore(metrics) {
const currentRPS = metrics.requests_per_second;
const baselineRPS = metrics.baseline_rps;
const ratio = currentRPS / baselineRPS;
if (ratio > 20) return 1.0; // Critical
if (ratio > 10) return 0.8; // Red
if (ratio > 5) return 0.6; // Orange
if (ratio > 3) return 0.4; // Yellow
return 0.0; // Green
}
calculatePatternScore(metrics) {
const indicators = [
metrics.ip_diversity < 0.1 ? 0.3 : 0, // Low IP diversity
metrics.user_agent_diversity < 0.2 ? 0.3 : 0, // Identical user agents
metrics.request_timing_variance < 50 ? 0.2 : 0, // Mechanical timing
metrics.endpoint_focus > 0.9 ? 0.2 : 0 // Targeting few endpoints
];
return Math.min(indicators.reduce((a, b) => a + b, 0), 1.0);
}
}
3. Network-Layer Protection
Protect against protocol and network attacks:
{
"network_protection": {
"tcp_protection": {
"syn_flood_protection": true,
"connection_limits": {
"per_ip": 50,
"per_subnet": 200,
"global": 100000
},
"connection_timeout": 30000
},
"udp_protection": {
"rate_limit": "1000/s",
"packet_size_limit": 1500,
"reflection_protection": true
},
"packet_inspection": {
"malformed_packet_drop": true,
"fragment_reassembly": true,
"protocol_validation": true
}
}
}
Application-Specific Protection
Different applications need tailored protection:
API Endpoints
{
"api_protection": {
"expensive_endpoints": [
{
"path": "/api/search",
"limit": "10/m",
"burst": 20,
"cost_weight": 5
},
{
"path": "/api/ai/generate",
"limit": "3/m",
"burst": 5,
"cost_weight": 50
}
],
"authentication_bypass_protection": {
"unauthenticated_limit": "100/h",
"failed_auth_penalty": "1h_block",
"brute_force_detection": true
}
}
}
Web Applications
{
"web_protection": {
"page_limits": {
"static_assets": "1000/m",
"dynamic_pages": "100/m",
"forms": "10/m",
"login_attempts": "5/15m"
},
"session_protection": {
"max_concurrent_sessions": 10,
"session_hijack_detection": true,
"rapid_session_creation_limit": "3/h"
}
}
}
Real-Time Monitoring and Response
Attack Visualization Dashboard
class DDoSMonitoringDashboard {
constructor() {
this.metrics = new Map();
this.attackTimeline = [];
this.geoMap = new GeoAttackVisualizer();
}
async initializeRealTimeMonitoring() {
// WebSocket connection for real-time updates
this.ws = new WebSocket('wss://api.rately.dev/v1/ddos/stream');
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.updateDashboard(data);
};
// Update dashboard every second
setInterval(() => this.refreshMetrics(), 1000);
}
updateDashboard(data) {
// Update attack metrics
this.updateAttackMetrics(data.metrics);
// Update geographic view
this.geoMap.plotAttackSources(data.geographic_data);
// Update timeline
this.attackTimeline.push({
timestamp: data.timestamp,
intensity: data.attack_intensity,
type: data.attack_type,
blocked: data.blocked_requests,
allowed: data.allowed_requests
});
// Keep only last hour of data
const oneHourAgo = Date.now() - (60 * 60 * 1000);
this.attackTimeline = this.attackTimeline.filter(
entry => entry.timestamp > oneHourAgo
);
}
generateAlerts(data) {
const alerts = [];
// Volume spike alert
if (data.requests_per_second > data.baseline_rps * 10) {
alerts.push({
level: 'critical',
message: `Massive traffic spike: ${data.requests_per_second} RPS`,
recommended_action: 'Enable emergency mode'
});
}
// Geographic concentration alert
if (data.top_country_percentage > 80) {
alerts.push({
level: 'warning',
message: `${data.top_country_percentage}% traffic from ${data.top_country}`,
recommended_action: 'Consider geo-blocking'
});
}
// New attack vector detection
if (data.attack_patterns.includes('new_pattern')) {
alerts.push({
level: 'info',
message: 'New attack pattern detected - updating ML models',
recommended_action: 'Monitor closely'
});
}
return alerts;
}
}
Emergency Response Procedures
Automated Incident Response
class DDoSIncidentResponse {
constructor() {
this.escalationLevels = {
1: 'automated_response',
2: 'team_notification',
3: 'emergency_response',
4: 'customer_communication'
};
}
async handleIncident(attackData) {
const severity = this.calculateSeverity(attackData);
const incidentId = await this.createIncident(attackData, severity);
// Execute automated response
await this.executeAutomatedResponse(attackData, severity);
// Escalate if needed
if (severity >= 2) {
await this.escalateToTeam(incidentId, attackData);
}
if (severity >= 3) {
await this.emergencyResponse(incidentId, attackData);
}
if (severity >= 4) {
await this.customerCommunication(incidentId, attackData);
}
return incidentId;
}
async executeAutomatedResponse(attackData, severity) {
// Increase protection levels
await rately.activateEmergencyMode({
duration: '1h',
protection_level: severity,
auto_adjust: true
});
// Block attack sources
if (attackData.malicious_ips.length > 0) {
await rately.bulkBlockIPs(attackData.malicious_ips, {
duration: '24h',
reason: 'ddos_attack'
});
}
// Enable additional challenges
await rately.enableGlobalChallenge({
type: severity >= 3 ? 'captcha' : 'js_challenge',
duration: '30m'
});
// Scale infrastructure if needed
if (severity >= 3) {
await this.scaleInfrastructure(attackData.projected_load);
}
}
async createAttackReport(attackData, incidentId) {
return {
incident_id: incidentId,
attack_start: attackData.start_time,
attack_duration: attackData.duration,
peak_rps: attackData.peak_requests_per_second,
total_requests: attackData.total_requests,
blocked_percentage: attackData.blocked_percentage,
attack_vectors: attackData.attack_types,
geographic_sources: attackData.source_countries,
mitigation_actions: attackData.mitigation_actions,
impact_assessment: {
service_availability: attackData.availability_percentage,
response_time_impact: attackData.response_time_degradation,
customer_impact: attackData.affected_customers
},
lessons_learned: attackData.lessons_learned,
preventive_measures: attackData.new_protections
};
}
}
Performance During Attacks
Edge protection maintains performance even under attack:
// Performance monitoring during DDoS events
class AttackPerformanceMonitor {
constructor() {
this.metrics = {
edge_latency: [],
origin_latency: [],
block_rate: [],
false_positive_rate: []
};
}
async measurePerformance() {
return {
edge_processing_time: await this.measureEdgeLatency(),
origin_offload_percentage: await this.calculateOriginOffload(),
legitimate_traffic_impact: await this.measureLegitimateImpact(),
protection_efficiency: await this.calculateProtectionEfficiency()
};
}
async measureEdgeLatency() {
// Test edge processing speed
const start = performance.now();
await this.makeEdgeRequest();
const end = performance.now();
return end - start;
}
async calculateOriginOffload() {
const totalRequests = await this.getTotalRequests();
const originRequests = await this.getOriginRequests();
return ((totalRequests - originRequests) / totalRequests) * 100;
}
async generatePerformanceReport() {
const performance = await this.measurePerformance();
return {
summary: {
edge_latency_avg: this.average(this.metrics.edge_latency),
origin_protection: `${performance.origin_offload_percentage.toFixed(1)}%`,
legitimate_user_impact: `${performance.legitimate_traffic_impact.toFixed(1)}ms`,
overall_efficiency: `${performance.protection_efficiency.toFixed(1)}%`
},
recommendations: this.generateOptimizationRecommendations(performance)
};
}
}
Testing Your DDoS Protection
Controlled Testing
# Test rate limiting thresholds
hey -n 1000 -c 10 -q 50 https://api.yourservice.com/endpoint
# Test geographic protection (use VPN)
curl -H "CF-IPCountry: CN" https://api.yourservice.com/endpoint
# Test user-agent based detection
curl -H "User-Agent: AttackBot/1.0" https://api.yourservice.com/endpoint
# Test challenge responses
curl -H "Accept: text/html" https://api.yourservice.com/endpoint
Load Testing with Protection
// Load test that respects rate limits
class ProtectedLoadTest {
constructor(options) {
this.baseURL = options.baseURL;
this.rateLimits = options.rateLimits;
this.clients = options.clients || 10;
}
async runTest(duration) {
const clients = Array(this.clients).fill().map((_, i) =>
this.createClient(`client-${i}`)
);
const results = await Promise.all(
clients.map(client => client.run(duration))
);
return this.aggregateResults(results);
}
createClient(clientId) {
return {
id: clientId,
requests: 0,
blocked: 0,
errors: 0,
async run(duration) {
const endTime = Date.now() + duration;
while (Date.now() < endTime) {
try {
const response = await this.makeRequest();
if (response.status === 429) {
this.blocked++;
// Respect rate limit
await this.sleep(response.retryAfter * 1000);
} else if (response.status >= 400) {
this.errors++;
}
this.requests++;
} catch (error) {
this.errors++;
}
// Natural spacing between requests
await this.sleep(Math.random() * 100);
}
return {
id: this.id,
requests: this.requests,
blocked: this.blocked,
errors: this.errors,
block_rate: this.blocked / this.requests,
error_rate: this.errors / this.requests
};
}
};
}
}
Best Practices for DDoS Protection
- Layer Multiple Defenses: Combine rate limiting, behavioral analysis, and ML detection
- Monitor Constantly: Watch for attack patterns and adjust thresholds
- Test Regularly: Validate protection works without blocking legitimate users
- Plan Response: Have incident response procedures ready
- Learn from Attacks: Improve protection based on attack patterns
- Communicate Proactively: Keep users informed during incidents
Conclusion
DDoS protection has evolved from simple volume filtering to intelligent, multi-layered defense systems. Edge-based protection offers the best combination of scale, performance, and intelligence.
With Rately's edge protection:
- Stop attacks at 300+ global locations before they reach your infrastructure
- Maintain performance with <25ms added latency even during attacks
- Scale infinitely with Cloudflare's massive network capacity
- Adapt intelligently using ML and behavioral analysis
- Monitor everything with real-time attack visibility
Modern DDoS attacks are sophisticated, but edge-based protection is more sophisticated. Don't wait for the next attack to upgrade your defenses.
Get started with Rately's DDoS protection and see how easy it is to protect your APIs at the edge.