Defending Against Malicious Traffic Attacks: 5-Layer Architecture, Production Code & Interview Guide
This article provides a comprehensive four-phase strategy (emergency mitigation, root cause analysis, targeted remediation, long-term defense) for handling malicious traffic attacks on PC websites, detailing a five-layer defense architecture (CDN, WAF, Gateway, Service, Data) with production-ready code for Nginx rate limiting, Spring Cloud Gateway + Sentinel, Resilience4j circuit breaking, Redis cache protection, and API signature verification, plus interview-focused technical deep-dives.
Four-Phase Strategy for Malicious Traffic Attack Defense
The article outlines a strict "stop-loss → locate → cure → defend" methodology, which is the optimal solution and the first-reaction ability interviewers value most.
Phase 1: Emergency Mitigation (Golden 10 Minutes)
Core principle: protect core services first.
Protection Layers and Techniques
Nginx Access Layer (highest cost-performance) : IP-level rate limiting + connection limits + suspicious IP instant blocking. Technologies: limit_req_zone / limit_conn_zone. Expected effect: blocks 80%+ junk traffic.
API Gateway Layer : Interface-level rate limiting + dynamic threshold adjustment. Technologies: Spring Cloud Gateway + Sentinel. Expected effect: protects all backend interfaces.
Service Layer : Circuit breaking + service isolation. Technologies: Resilience4j + thread pool isolation. Expected effect: core business not dragged down.
Resource Scaling : Elastic scaling + traffic splitting. Technologies: K8s HPA + multi-cluster traffic scheduling. Expected effect: quickly increase system capacity.
Key Actions
Non-core interfaces (comments, favorites, recommendations) directly circuit-break , return static degradation page.
Static resources (JS/CSS/images) fully move to CDN , origin only handles dynamic requests.
Disable database slow queries and real-time statistics functions, prioritize write operations.
Phase 2: Rapid Diagnosis (Execute Immediately After Mitigation)
Use three questions to quickly locate root cause:
Where does traffic come from? Check Nginx logs Top 10 IP, User-Agent, requested interfaces.
What is the attack type? CC attack? DDoS? Crawler? Scalping?
Where is the system bottleneck? CPU? Memory? Database connections? Redis cache penetration?
Phase 3: Targeted Remediation (Precision Strike)
Phase 4: Long-Term Defense System (Permanent Solution)
Build a five-layer defense-in-depth system to leave no room for attacks:
CDN Layer → WAF Layer → Gateway Layer → Service Layer → Data Layer
↓ ↓ ↓ ↓ ↓
Static Accel Traffic Clean Interface Rate Circuit Break Read-Write Split
Cache Hit Rule Block Routing Control Service Isolate ShardingCore Construction Points
Full-chain monitoring and alerting : Second-level monitoring of QPS, response time, error rate, database connections, etc., with multi-level alert thresholds.
Regular full-chain stress testing : Discover system bottlenecks in advance, verify effectiveness of rate limiting and degradation strategies.
Emergency drill exercises : Develop SOPs for different attack scenarios, conduct drills at least quarterly.
Security hardening : Interface encryption, parameter validation, prevent SQL injection / XSS attacks.
Why Nginx/Gateway Cannot Replace WAF
WAF is not an optional component, but the first and most important line of defense in website scraping scenarios.
Many mistakenly think "Nginx rate limiting + gateway is enough", a dangerous misconception:
Nginx : solves IP rate limiting, connection limits, simple request filtering. Cannot solve: application-layer attacks, SQL injection, XSS, malicious crawlers, CC attack variants.
API Gateway : solves interface rate limiting, circuit breaking, routing control. Cannot solve: protocol parsing, semantic analysis, behavior recognition, zero-day attack protection.
WAF : solves all above + full application-layer traffic protection. Only cannot solve: large-volume DDoS attacks (requires high-defense IP).
Real case : Attacker used 100,000 different IPs , each sending only 1 request per second, total QPS 100,000. In this case:
Nginx IP rate limiting completely ineffective (each IP within threshold).
Gateway interface rate limiting only limits total QPS, but blocks normal users too.
Only WAF can identify these requests as machine-generated via behavior analysis and intercept with one click.
WAF's Accurate Position in Five-Layer Defense
Core principle: All traffic reaching the origin must pass through WAF, no exceptions.
WAF Core Functions (Must Enable During Scraping Attacks)
1. Intelligent CC Attack Protection (Most Core)
# Alibaba Cloud WAF CC Protection Config Example (Production Grade)
Rule Name: Site-wide CC Protection
Protection Mode: Protection Mode
Detection Threshold: Single IP 100 requests/minute
Intercept Threshold: Single IP 200 requests/minute
Intercept Action: Captcha Challenge (5 minutes)
Advanced Config:
✓ Enable Human-Machine Verification (Slider Captcha)
✓ Enable Behavior Analysis (Mouse Trajectory, Keyboard Input)
✓ Enable Device Fingerprint Recognition
✓ Enable Same-Origin DetectionTechnical highlight : WAF's CC protection is not simple IP counting, but based on machine learning behavior analysis , can identify:
Fixed-interval machine requests
Requests without Referer
Abnormal User-Agent requests
Incomplete Cookie requests
Abnormal access path requests
2. Malicious Crawler Protection
Automatically identify and block all crawlers except search engine crawlers.
Support custom crawler rules (e.g., block specific User-Agent, specific IP ranges).
Support crawler rate limiting (allow slow crawling, block aggressive scraping).
3. Virtual Patching
Protect known vulnerabilities (e.g., Log4j, Spring Boot vulnerabilities) without modifying business code.
Critical in emergencies, can complete vulnerability fix in minutes.
4. Precise Access Control
Support precise control based on IP, region, User-Agent, Cookie, request headers, etc.
Example: one-click block all requests from overseas.
WAF Selection Comparison
Cloud WAF (Alibaba Cloud / Tencent Cloud) : Pros: out-of-the-box, no maintenance, strong protection, elastic scaling. Cons: some cost, traffic passes through cloud vendor. Suitable: 99% of internet companies' first choice.
Hardware WAF (Sangfor / Qihoo 360) : Pros: high performance, data doesn't pass third party. Cons: expensive, complex maintenance, difficult scaling. Suitable: finance, government, industries with extremely high data security requirements.
Open Source WAF (ModSecurity) : Pros: free, customizable. Cons: complex configuration, weak protection, requires professional team maintenance. Suitable: personal projects or teams with extremely limited budget.
Interview bonus answer : "I strongly recommend cloud WAF; its cost-performance and protection capability far exceed open source and hardware WAF. For most companies, developing or maintaining WAF themselves is very uneconomical; professional things to professional people."
WAF Common Misconceptions and Best Practices
Misconception 1: WAF affects performance
Fact : Modern cloud WAF latency typically 1-5ms , negligible. And WAF intercepts 90%+ malicious traffic, actually greatly reduces origin pressure.
Misconception 2: WAF enabled means everything is fine
Fact : WAF is not a silver bullet. It needs to work with other defense layers:
WAF intercepts 90% malicious traffic
Nginx intercepts remaining 9%
Gateway and service layer intercept final 1%
Misconception 3: Stricter WAF rules are better
Fact : Overly strict rules cause false positives blocking normal users. Best practice:
Enable "observation mode" for 1-2 weeks
Analyze false positive logs, adjust rules
Then switch to "protection mode"
Interview Ultimate Bonus
"WAF is the cornerstone of the entire application-layer defense system; a website without WAF is like a house without a door. Nginx and gateway layers only do simple traffic control, while WAF can do semantic-level attack detection. I previously handled an attack where attacker used 200,000 proxy IPs, each sending only 1 request per second, total QPS 200,000. Nginx IP rate limiting completely failed, gateway could only limit total QPS to 10,000, causing 95% of normal users to be blocked. Later we urgently integrated cloud WAF, enabled intelligent CC protection, and within 5 minutes all malicious traffic was intercepted, normal user access completely unaffected. Therefore my view is: any public-facing website must integrate WAF immediately , this is the highest ROI security protection measure."
Core Code Implementation (Production-Grade with Technical Highlights)
1. Nginx Access Layer Rate Limiting (Highest Cost-Performance, Blocks 80% Traffic)
# Technical Highlight: Token Bucket Smooth Rate Limiting + Connection Limits + Dynamic Black/White Lists
http {
# Define rate limit rule: 10r/s smooth rate limiting, burst allows 20 requests, excess returns 503
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
# Single IP max connection limit
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
listen 80;
server_name example.com;
# Global rate limit config
limit_req zone=req_limit burst=20 nodelay;
limit_conn conn_limit 50;
# Static resources go directly to CDN, origin does not process
location ~* \.(js|css|png|jpg|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
# Static resources no rate limit
limit_req off;
}
# Core interface separate rate limit (stricter)
location /api/login {
limit_req zone=req_limit burst=5 nodelay;
proxy_pass http://backend;
}
# Non-core interface: return static degradation page on anomaly
location /api/comment {
error_page 503 /static/503_comment.html;
proxy_pass http://backend;
}
}
}2. Spring Cloud Gateway + Sentinel Dynamic Interface Rate Limiting
// Technical Highlight: Nacos-based Dynamic Rate Limit Rule Config + Hot Parameter Rate Limiting
@Configuration
public class SentinelConfig {
// Initialize Sentinel Rules
@PostConstruct
public void initRules() {
// 1. Global Flow Control Rule
FlowRule flowRule = new FlowRule();
flowRule.setResource("all_api");
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setCount(10000); // Cluster Total QPS Limit
flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);
flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
// 2. Hot Parameter Rate Limiting (Prevent Single IP/User Aggressive Scraping)
ParamFlowRule paramRule = new ParamFlowRule();
paramRule.setResource("api_login");
paramRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
paramRule.setCount(5); // Single Parameter Value Max 5 Times/Second
paramRule.setParamIdx(0); // First Parameter: IP Address
FlowRuleManager.loadRules(Collections.singletonList(flowRule));
ParamFlowRuleManager.loadRules(Collections.singletonList(paramRule));
}
}3. Resilience4j Circuit Breaker Degradation (Prevent Service Avalanche)
// Technical Highlight: Sliding Window Circuit Breaker Algorithm + Thread Pool Isolation
@RestController
@RequestMapping("/api")
public class CommentController {
// Comment Service: Independent Thread Pool Isolation, Does Not Affect Core Service
@Bulkhead(name="comment-service", fallbackMethod="commentFallback")
@CircuitBreaker(name="comment-service", fallbackMethod="commentFallback")
@GetMapping("/comment/list")
public ResponseEntity<List<Comment>> listComments(Long articleId) {
List<Comment> comments = commentService.listByArticleId(articleId);
return ResponseEntity.ok(comments);
}
// Fallback Method: Return Static Default Data
public ResponseEntity<List<Comment>> commentFallback(Long articleId, Exception e) {
log.warn("Comment Service Degraded, articleId: {}", articleId, e);
return ResponseEntity.ok(Collections.emptyList());
}
}4. Redis Cache Penetration Prevention (Hot Key Problem Ultimate Solution)
// Technical Highlight: Mutex Lock + Hot Key Never Expires + Async Update
@Component
public class RedisCacheService {
@Autowired
private StringRedisTemplate redisTemplate;
// Get Hot Data (Prevent Breakthrough)
public String getHotData(String key, Function<String, String> loader) {
String value = redisTemplate.opsForValue().get(key);
if (value != null) {
return value;
}
// Cache Miss, Try Acquire Distributed Lock
String lockKey = "lock:" + key;
Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
if (Boolean.TRUE.equals(locked)) {
try {
// Only One Thread Loads Data From DB
value = loader.apply(key);
if (value != null) {
// Hot Key Never Expires, Background Async Update
redisTemplate.opsForValue().set(key, value);
// Async Update Task
asyncUpdateCache(key, loader);
}
return value;
} finally {
redisTemplate.delete(lockKey);
}
} else {
// Other Threads Wait 100ms Then Retry
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return getHotData(key, loader);
}
}
// Async Update Cache
@Async
public void asyncUpdateCache(String key, Function<String, String> loader) {
while (true) {
try {
Thread.sleep(60000); // Update Every Minute
String value = loader.apply(key);
if (value != null) {
redisTemplate.opsForValue().set(key, value);
}
} catch (Exception e) {
log.error("Async Cache Update Failed, key: {}", key, e);
}
}
}
}5. Interface Signature Verification (Prevent Malicious Interface Calls)
// Technical Highlight: Timestamp Anti-Replay + Asymmetric Encryption Signature + Device Fingerprint
@Component
public class ApiSignInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1. Get Request Parameters
String timestamp = request.getHeader("X-Timestamp");
String sign = request.getHeader("X-Sign");
String deviceId = request.getHeader("X-Device-Id");
// 2. Timestamp Validation: Prevent Replay Attack (Validity 5 Minutes)
long now = System.currentTimeMillis();
if (Math.abs(now - Long.parseLong(timestamp)) > 300000) {
response.setStatus(401);
return false;
}
// 3. Signature Validation
String signStr = deviceId + timestamp + request.getRequestURI();
String serverSign = DigestUtils.md5DigestAsHex((signStr + "secret_key").getBytes());
if (!serverSign.equals(sign)) {
response.setStatus(401);
return false;
}
return true;
}
}Technical Challenges and Solutions Comparison
Service Avalanche Effect : Problem: one non-core service crushed, causing entire call chain collapse, core services also unavailable. Solution: Thread pool isolation + circuit breaker degradation . Highlight: each service uses independent thread pool, automatically circuit breaks on exception and returns degraded data.
IP Blocking False Positives : Problem: simple IP blocking kills normal users sharing IP (e.g., corporate intranet, campus network). Solution: User behavior-based risk control + hierarchical rate limiting . Highlight: don't directly block IP, instead rate limit users with abnormal behavior; different users under same IP counted independently.
Cache Penetration / Avalanche / Breakthrough : Problem: hot key expiration causes database instant crush; large number of keys expire simultaneously causing avalanche; malicious requests for non-existent keys cause penetration. Solution: Breakthrough: mutex + hot key never expires; Avalanche: randomize expiration time; Penetration: Bloom filter + empty value caching . Highlight: Bloom filter preemptively blocks non-existent keys; empty value caching sets short expiration.
Distributed Rate Limiting Consistency : Problem: single-machine rate limiting cannot control cluster total traffic; distributed rate limiting has performance bottlenecks. Solution: Sentinel cluster rate limiting + token bucket algorithm . Highlight: token bucket implements smooth rate limiting; cluster rate limiting uses Redis as token center.
Human-Machine Verification Bypass : Problem: simple captcha easily recognized by AI; slider captcha easily simulated by scripts. Solution: Behavioral captcha + device fingerprint + risk scoring . Highlight: analyze user mouse trajectory, keyboard input speed, etc.; combine device fingerprint to identify malicious devices.
DDoS Attack Protection : Problem: large traffic DDoS directly saturates bandwidth, origin cannot respond. Solution: High-defense IP + Anycast traffic cleaning + hide origin IP . Highlight: traffic first cleaned in high-defense data center, only normal traffic forwarded to origin; origin IP not exposed publicly.
Database Pressure Too High : Problem: large write requests cause database CPU/IO spike, response slows. Solution: Read-write separation + sharding + async write . Highlight: read requests go to replica; large tables sharded; non-real-time writes first enter MQ, async consume to database.
Real Interview Simulation
Scenario: PC Website Maliciously Scraped by Black-Hat Scripts
Interviewer asks: As Java R&D lead, how to design a protection scheme?
Candidate: Defense-in-Depth Architecture
User → CDN/WAF Edge → Nginx/Gateway → Java App → Database
▲ ▲ ▲
① Dirty Traffic Drop ② Token Bucket Rate Limit ③ Business Risk Control + Async Peak ShavingBlock dirty traffic at the edge, Java layer only handles relatively clean traffic.
Edge Layer: CDN + WAF Rate Limiting, IP Reputation, Geographic Blocking
CDN + WAF rate limiting : e.g., Alibaba Cloud WAF, set single IP >20 requests/sec triggers JS challenge, filters scripts directly.
IP reputation library : integrate threat intelligence, blacklist known proxy, IDC IPs.
Geographic blocking : if business only serves domestic, reject all overseas traffic.
These can cut 80% of low-level attacks.
Gateway Layer: Redis + Lua Token Bucket in Spring Cloud Gateway Global Filter
Three key points:
Fine granularity : not just limit IP, but IP + interface path, even IP + userId.
Allow burst : token bucket friendlier than leaky bucket, handles normal traffic spikes.
Atomicity : use Lua script to ensure check and deduct in Redis atomically.
Example Lua script:
-- Each Request Deducts 1 Token, Returns 0 If Insufficient
local tokens = redis.call('HGET', KEYS[1], 'tokens')
tokens = tonumber(tokens or ARGV[2])
if tokens >= 1 then
redis.call('HSET', KEYS[1], 'tokens', tokens - 1)
return 1
else
return 0
endExceed limit returns 429; same IP exceeds limit three consecutive times, throw into temporary blacklist, cool down 5 minutes.
Handling Massive Residential IP Pools: Upgrade from IP to Behavior + Account Dimensions
Device fingerprint : frontend collects Canvas, WebGL to generate unique device ID, rate limit on this ID. Changing IP useless unless device also changed.
Business hard limits : e.g., SMS interface, same phone number 1 per minute, max 5 per day. Iron law, cannot bypass by changing IP.
Rhythm analysis : human click intervals fluctuate, scripts are mechanical. Backend statistics request interval variance, extremely low variance judged as script, direct challenge.
Application Layer: Three Defense Axes
Captcha : login/register/SMS key interfaces. Trigger rate limit then pop slider captcha, backend verify ticket.
Frontend dynamic signature : prevent scripts directly calling interfaces. Page computes timestamp+nonce+sign, backend verifies timeliness and signature.
Business lock : same user repeat operations. Redis SETNX on userId+action for 5-second lock.
Captcha separates human from machine; business lock prevents accidental or malicious duplicate submissions.
Risk Scoring + Graded Punishment Model
Real-time scoring in filter:
Same IP frequently switching User-Agent → +20 points
Request intervals highly consistent (bot trait) → +15 points
Always active at midnight → +10 points
Actions by score:
🟢 Safe (0-30): normal pass
🟡 Suspicious (31-59): pop captcha
🟠 Dangerous (60-79): return degraded data (cache/empty list)
🔴 High Risk (80+): temporary ban, async alert
This intercepts bots without hurting normal users.
Database Pressure Relief: Async Peak Shaving via Message Queue
For async-processable operations (email, logs, reports), never let them directly hit database. Instead:
Throw into message queue (RocketMQ / Kafka), requests enqueue first.
Backend rate-limited consumption, e.g., 50 messages/sec.
If queue backlog exceeds threshold, front layer rejects new requests, prompt "system busy".
This is peak shaving and valley filling , protects database from being overwhelmed.
Monitoring Closed Loop
Instrumented logs : all interceptions, rate limits logged with requestId for tracing.
Monitoring dashboard : Prometheus + Grafana show QPS, rate limit trigger rate, banned IP count.
Auto linkage : when interface rate limit trigger rate exceeds 60%, auto alert and notify ops to adjust WAF strategy, blackhole route attack IP ranges.
This turns passive defense into active immunity.
Core Code Walkthrough (Three Layers)
1. Redis Lua Token Bucket (Gateway Layer Rate Limiting)
// Java Side Call
public boolean tryAcquire(String key, double rate, int capacity) {
String script =
"local tokens = redis.call('HGET', KEYS[1], 'tokens') " +
"tokens = tonumber(tokens or ARGV[2]) " + // First Initialization
"if tokens >= tonumber(ARGV[3]) then " +
" redis.call('HSET', KEYS[1], 'tokens', tokens - tonumber(ARGV[3])) " +
" redis.call('EXPIRE', KEYS[1], ARGV[4]) " +
" return 1 " +
"else " +
" return 0 " +
"end";
List<String> keys = Collections.singletonList("rate:" + key);
List<String> args = Arrays.asList(
String.valueOf(rate), // ARGV[1]: Rate (Tokens/Second)
String.valueOf(capacity), // ARGV[2]: Bucket Capacity
"1", // ARGV[3]: Tokens Consumed Per Request
"10" // ARGV[4]: Key TTL (Seconds)
);
Long result = redisTemplate.execute(
new DefaultRedisScript<>(script, Long.class), keys, args.toArray()
);
return result == 1;
}Highlights :
Lua makes "check+deduct" atomic, avoids concurrent over-issuance.
Supports dynamic rate, dynamic capacity, different interfaces pull params from config center. EXPIRE sets key TTL, prevents memory bloat.
2. Frontend Dynamic Signature Verification (Application Layer Prevent Direct Script Calls)
Frontend (pseudo-code):
const timestamp = Date.now();
const nonce = generateUUID();
const params = { userId: 123, action: 'submit' };
const sign = md5(timestamp + nonce + JSON.stringify(params) + SECRET);Java Backend Verification :
public boolean checkSign(HttpServletRequest request) {
String timestamp = request.getHeader("X-Timestamp");
String nonce = request.getHeader("X-Nonce");
String sign = request.getHeader("X-Sign");
String body = ...; // Read Request Body
// 1. Timeliness Check (60 Seconds Expiry)
if (Math.abs(System.currentTimeMillis() - Long.parseLong(timestamp)) > 60000) {
return false;
}
// 2. Nonce Deduplication (Redis Set)
String nonceKey = "nonce:" + nonce;
if (Boolean.FALSE.equals(redisTemplate.opsForValue().setIfAbsent(nonceKey, "1", 60, TimeUnit.SECONDS))) {
return false; // Replay Attack
}
// 3. Signature Comparison
String expected = DigestUtils.md5Hex(timestamp + nonce + body + SECRET);
return expected.equals(sign);
}Highlights :
Timestamp prevents "old request reuse", Nonce prevents "single replay", Signature prevents "parameter tampering".
Nonce uses Redis SETNX with expiration, O(1) ultra-fast deduplication, no full storage.
3. Risk Scoring Interceptor (Application Layer Stealth Risk Control)
@Component
public class RiskInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate<String, Object> redis;
@Override
public boolean preHandle(HttpServletRequest request, ...) {
String ip = getClientIp(request);
String deviceId = request.getHeader("X-Device-Id");
String userAgent = request.getHeader("User-Agent");
int score = 0;
// Rule 1: Same IP Frequently Changes UA (Suspected Proxy Pool)
String lastUA = (String) redis.opsForValue().get("ua:" + ip);
if (lastUA != null && !lastUA.equals(userAgent)) {
score += 20;
}
redis.opsForValue().set("ua:" + ip, userAgent, 10, TimeUnit.MINUTES);
// Rule 2: Device Fingerprint Anomaly (Multiple IPs In Short Time)
if (deviceId != null) {
Long ipCount = redis.opsForSet().size("device_ips:" + deviceId);
if (ipCount > 5) score += 15;
redis.opsForSet().add("device_ips:" + deviceId, ip);
redis.expire("device_ips:" + deviceId, 10, TimeUnit.MINUTES);
}
// Action Based On Score (Pseudo-code)
if (score > 30) {
// Pop Captcha
return challenge(request, response);
} else if (score > 60) {
// Temporary Ban
return ban(request, response);
}
return true;
}
}Highlights :
Uses Redis to store short-term behavioral features , in-memory computation, near-zero latency.
Multi-dimensional cumulative scoring, immediate interception on threshold breach, forming self-healing defense .
Five Major Technical Challenges and Solutions
🔴 Distributed Rate Limiting Consistency : Why hard: multiple gateway instances each rate limit independently, total quota exceeded. Solution: Redis centralized counting + Lua atomic script . All instances share one token bucket, guarantee global precision.
🟠 IP Proxy Pool Bypass : Why hard: attacker owns massive residential IPs, IP rate limiting fails. Solution: Upgrade to device fingerprint + behavior rhythm analysis . Frontend generates device ID, backend statistics request interval variance, low variance judged as script.
🟡 False Positive on Normal Users : Why hard: strict rules may block real users' burst operations (e.g., Double 11 flash sale). Solution: Flexible punishment gradient (captcha → degradation → ban) . Use token bucket to allow burst. Introduce whitelist (VIP users, internal IPs) to avoid false kills.
🟢 Real-time Risk Control Performance Overhead : Why hard: every request queries Redis, calculates score, may slow response. Solution: Pipelining + local caching . E.g., IP risk score cached locally for 1 second, reduce Redis interactions. Risk calculation rules use lightweight data structures (Set/Hash).
🔵 Frontend Signature Reverse Engineering : Why hard: JS encryption logic and SECRET exposed. Solution: Dynamic obfuscation + short-term validity . SECRET rotated periodically (e.g., 20 min), injected by backend. JS obfuscated, increases cracking cost. Combined with device fingerprint , even if signature cracked, still must pass behavior check.
Especially "Distributed Rate Limiting Consistency" , comparison diagram:
❌ Single-Machine Rate Limit: Each For Itself
[Instance A] → Counter A (Limit 10/s) Total Allowed = A+B = 20/s
[Instance B] → Counter B (Limit 10/s) Actual May Exceed Expectation
✅ Centralized Rate Limit
[Instance A] ↘
→ Redis Token Bucket (Total Capacity 10/s)
[Instance B] ↗
No Matter How Many Instances, Global Rate ConsistentInterviewer concludes: very solid from code implementation to challenge resolution, both global vision and detail-oriented.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
