Skip to Content
Rate Limiting

Rate Limiting & Spam Prevention

Comprehensive documentation of rate limiting mechanisms, spam prevention strategies, and abuse mitigation in the Zentalk decentralized messaging protocol.

Overview

Rate limiting in a decentralized system presents unique challenges compared to traditional centralized architectures. Without a single authority to enforce limits, Zentalk employs a distributed approach combining client-side enforcement, relay node cooperation, and cryptographic proof mechanisms.

Why Rate Limiting in a Decentralized System

ChallengeCentralized SolutionZentalk Approach
Spam preventionSingle enforcement pointDistributed relay consensus
Resource protectionServer-side limitsClient + relay coordination
Fair usagePer-user quotasReputation-weighted limits
DDoS mitigationLoad balancers, CDN3-hop relay, PoW challenges
Abuse detectionContent analysisBehavioral patterns only

Balance Between Usability and Abuse Prevention

Rate limits must be calibrated to allow legitimate high-volume usage while preventing abuse. Zentalk optimizes for the following user profiles:

User ProfileExpected UsageLimit Headroom
Casual user50 messages/day10x buffer
Active user500 messages/day5x buffer
Power user2000 messages/day2x buffer
Group admin5000 messages/day1.5x buffer

Design Principles

PrincipleImplementation
Privacy-preservingNo content inspection, rate-based only
Graduated responseWarnings before restrictions
Transparent limitsUsers informed of current usage
AppealableAutomated restrictions can be reviewed
Distributed enforcementNo single point of control

Distributed Enforcement Challenges

Distributed Rate Limiting Architecture: ┌─────────────────────────────────────────────────────────────────┐ │ User Device │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ Local Rate Limiter │ │ │ │ - First line of defense │ │ │ │ - Prevents unnecessary network requests │ │ │ │ - Maintains local usage counters │ │ │ └─────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────────┐ │ Relay Network │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Relay Node │ │ Relay Node │ │ Relay Node │ │ │ │ - Per-user │ │ - Per-user │ │ - Per-user │ │ │ │ tracking │ │ tracking │ │ tracking │ │ │ │ - Gossip │ │ - Gossip │ │ - Gossip │ │ │ │ protocol │ │ protocol │ │ protocol │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ ↕ ↕ ↕ │ │ Rate limit state synchronization via gossip │ └─────────────────────────────────────────────────────────────────┘

Message Rate Limits

Message rate limits form the primary defense against spam and network abuse.

Standard Rate Limits

ContextLimitWindowBurst Allowance
1:1 messages60Per minute+20 burst
1:1 messages500Per hour+100 burst
Group messages30Per minute+10 burst
Group messages300Per hour+50 burst
Broadcast messages10Per minuteNone
System messages100Per minuteNone

Burst Allowance Mechanism

Burst allowance permits temporary spikes in activity while maintaining long-term averages.

Token Bucket Algorithm: Parameters: bucket_capacity = base_limit + burst_allowance refill_rate = base_limit / window_seconds tokens = bucket_capacity (initial) On message send: if tokens ≥ 1: tokens = tokens - 1 allow_message() else: reject_message(RATE_LIMITED) Every second: tokens = min(tokens + refill_rate, bucket_capacity) Example (1:1 messaging): bucket_capacity = 60 + 20 = 80 tokens refill_rate = 60 / 60 = 1 token/second User can send 80 messages instantly (burst) Then must wait for token refill Sustained rate: 1 message/second maximum

Rate Limit Tiers

Account Type1:1 MultiplierGroup MultiplierNotes
New account (less than 7 days)0.5x0.3xReduced limits during probation
Standard account1.0x1.0xBase limits
Verified account1.5x1.2xPhone or identity verified
Trusted account2.0x1.5xLong history, no violations
Premium account3.0x2.0xSubscription tier

Different Limits for 1:1 vs Group

Aspect1:1 ChatGroup ChatRationale
Base rateHigherLowerGroups amplify impact
Burst allowanceLargerSmallerConversations are bursty
Cooldown on violation5 minutes15 minutesGroups affect more users
Reputation impactLowHighSpam in groups is worse

Message Size Limits

Message TypeMax SizeRate Impact
Text only16 KB1x rate cost
With attachment reference32 KB1x rate cost
Rich content (formatting)64 KB2x rate cost
Large payload256 KB4x rate cost

Rate Limit Response Codes

CodeNameMeaningRetry After
RL_001SOFT_LIMITApproaching limit, warningImmediate (with warning)
RL_002RATE_LIMITEDLimit exceededSee Retry-After header
RL_003BURST_EXHAUSTEDBurst allowance depleted1-5 seconds
RL_004HOURLY_EXCEEDEDHour limit reachedSee Retry-After header
RL_005DAILY_EXCEEDEDDaily limit reachedUntil next day (UTC)
RL_006TEMP_BANNEDRepeated violations1-24 hours

Connection Rate Limits

Connection-level limits prevent resource exhaustion attacks and ensure fair access to relay infrastructure.

WebSocket Connection Limits

Limit TypeValueScopeNotes
Max concurrent connections5Per user identityAcross all devices
Max connections per IP10Per IP addressPrevents IP-based abuse
Max connections per device2Per device IDPrimary + backup
Connection lifetime24 hoursPer connectionMust reconnect daily

Connection Establishment Limits

OperationLimitWindowCooldown on Exceed
New connection attempts10Per minute60 seconds
TLS handshakes20Per minute30 seconds
Authentication attempts5Per minute120 seconds
Failed auth attempts3Per 5 minutes300 seconds

Reconnection Throttling

Reconnection Backoff Strategy: On disconnect: attempt = 0 Reconnection loop: while not connected: delay = calculate_delay(attempt) wait(delay) result = attempt_connection() if result == SUCCESS: break else if result == RATE_LIMITED: wait(retry_after_header) else: attempt = attempt + 1 calculate_delay(attempt): base = 1 second max_delay = 300 seconds // 5 minutes // Exponential backoff with jitter delay = min(base * (2 ^ attempt), max_delay) jitter = random(0, delay * 0.2) return delay + jitter Attempt Schedule: 1: 1-1.2 seconds 2: 2-2.4 seconds 3: 4-4.8 seconds 4: 8-9.6 seconds 5: 16-19.2 seconds 6: 32-38.4 seconds 7: 64-76.8 seconds 8: 128-153.6 seconds 9+: 300-360 seconds

IP-Based Limits

LimitValuePurpose
Connections per IP10Prevent single-IP floods
New users per IP per day5Limit bot account creation
Requests per IP per second100DDoS mitigation
Bandwidth per IP10 MB/sResource fairness

Geographic Distribution Requirements

RequirementThresholdAction on Violation
Unique IPs per userMax 20 per dayFlag for review
Geographic spreadMax 5 countries per hourRequire verification
VPN/Tor detectionAllowed but limited0.5x rate limits
Data center IP detectionFlagged0.3x rate limits

Key Operation Limits

Cryptographic key operations are computationally expensive and require strict rate limiting to prevent abuse.

Prekey Upload Limits

OperationLimitWindowNotes
One-time prekey upload100 keysPer batchMax batch size
Prekey batch uploads10Per hourPrevents key flooding
Total prekeys stored1000Per userServer-side limit
Signed prekey rotation1Per 7 daysMinimum rotation period

Prekey Replenishment Strategy

Prekey Management: Server-side storage: min_prekeys = 20 max_prekeys = 1000 warning_threshold = 50 On prekey request (by peer): prekey = pop_one_time_prekey(user_id) remaining = count_prekeys(user_id) if remaining ≤ warning_threshold: notify_client(PREKEY_LOW, remaining) return prekey Client replenishment: on PREKEY_LOW notification: current = get_prekey_count() to_generate = max_prekeys - current // Generate in batches to avoid blocking for batch in chunks(to_generate, 100): keys = generate_prekeys(batch) upload_prekeys(keys) wait(1 second) // Rate limit compliance

Session Creation Limits

Limit TypeValueWindowPurpose
New sessions initiated50Per hourPrevent session spam
Sessions with same peer3Per hourPrevent reset attacks
Total active sessions500Per userResource limits
Session creation burst10Per minuteAllow contact sync

Identity Registration Limits

OperationLimitWindowCooldown
Identity key registration1Per yearN/A
Identity key update1Per 30 days30 days
Device registration5Per day24 hours
Device deregistration10Per dayNone
Recovery key setup3Per year120 days

Key Bundle Fetch Limits

OperationLimitWindowNotes
Key bundle fetches100Per minuteFor new sessions
Same user bundle fetch5Per minutePrevent enumeration
Bulk bundle fetch50Per requestFor contact import
Failed bundle fetches20Per minuteInvalid addresses

Group Chat Limits

Group chats require additional limits due to message amplification effects.

Maximum Group Size

Group TypeMax MembersMessage RateNotes
Standard group256300/hourDefault limit
Large group1,024600/hourRequires verification
Broadcast channel10,000100/hourAdmin-only posting
Community50,00050/hourHierarchical moderation

Message Rate Per Group

Group SizeMessages/MinuteMessages/HourPer-Member Rate
2-10 members605006/min per member
11-50 members1208002.4/min per member
51-100 members18010001.8/min per member
101-256 members24012000.9/min per member
257+ members3001500Diminishing per member

Member Management Limits

OperationLimitWindowNotes
Add members50Per hourBulk adds throttled
Remove members50Per hourMass removal limited
Admin promotions10Per dayPrevent admin churn
Admin demotions10Per dayStability measure
Invite link generation5Per hourPrevent link spam

Group Creation Limits

Account TypeGroups/DayGroups/WeekTotal Groups
New account1310
Standard account52050
Verified account1050100
Trusted account20100250

Group Metadata Update Limits

OperationLimitWindowCooldown
Name change3Per day8 hours
Description change5Per day4 hours
Avatar change3Per day8 hours
Settings change10Per hourNone

Anti-Raid Protections

Raid Detection Algorithm: Parameters: join_rate_threshold = 10 members/minute message_rate_threshold = 5x normal new_member_message_threshold = 3 messages/minute Monitoring: track join_rate over 5-minute window track message_rate over 1-minute window track new_member_activity over 10-minute window On threshold exceeded: activate_raid_mode(): - Slow mode: 1 message per 30 seconds - New member mute: 10-minute wait before posting - Join rate limit: 2 members/minute - Notify admins duration = 30 minutes auto_deactivate after duration if metrics normalize Raid Mode Restrictions: ┌────────────────────────────────────────────────┐ │ Normal Mode │ Raid Mode │ ├────────────────────────────────────────────────┤ │ 60 msg/min │ 2 msg/min per user │ │ Instant join │ 2 joins/min max │ │ Immediate posting │ 10-min new member mute │ │ Unlimited reactions │ 5 reactions/min │ └────────────────────────────────────────────────┘

Spam Detection

Zentalk employs content-agnostic spam detection to preserve privacy while preventing abuse.

Content-Agnostic Detection (Rate-Based)

SignalThresholdWeightNotes
Messages per minuteMore than 30HighPrimary indicator
Unique recipients per hourMore than 50HighBroadcast behavior
Session creation rateMore than 20/hourMediumContact spam
Failed deliveriesMore than 20%MediumInvalid targets
Identical message timingLess than 100ms varianceHighBot behavior

Behavioral Pattern Analysis

Spam Behavior Patterns: Pattern: Mass Messaging Indicators: - Messages to more than 20 unique users in 5 minutes - Less than 1 second between messages - No replies received Action: Temporary rate reduction (0.25x) Pattern: Group Hopping Indicators: - Joins more than 5 groups in 1 hour - Sends messages immediately after joining - Leaves within 10 minutes Action: Group join cooldown (24 hours) Pattern: Contact Harvesting Indicators: - More than 100 key bundle fetches in 1 hour - Low message-to-fetch ratio (less than 0.1) - Sequential address queries Action: Key bundle rate limit (10/hour) Pattern: Bot Behavior Indicators: - Consistent message timing (low variance) - No typing indicators - 24/7 activity pattern - No read receipts sent Action: Flag for review, CAPTCHA challenge

Detection Without Content Scanning

What We AnalyzeWhat We Never Analyze
Message frequencyMessage content
Recipient patternsEncryption payloads
Timing signaturesUser conversations
Metadata anomaliesAttachment contents
Network behaviorSearch queries
Session patternsContact names

Privacy-Preserving Detection Techniques

TechniquePrivacy GuaranteeDetection Capability
Local rate countingNo server visibilityHigh for volume abuse
Bloom filter matchingProbabilistic onlyMedium for patterns
Differential privacyMathematical guaranteeLow false positives
Federated detectionNo central databaseCross-node patterns

Spam Score Calculation

Spam Score Algorithm: score = 0 // Rate-based factors if messages_per_minute > 30: score += (messages_per_minute - 30) * 2 if unique_recipients_per_hour > 50: score += (unique_recipients_per_hour - 50) * 1.5 // Behavioral factors if avg_time_between_messages < 1 second: score += 20 if reply_rate < 0.05: // less than 5% get replies score += 15 if session_creation_rate > 20: score += 10 // Account factors if account_age < 7 days: score *= 1.5 if has_violations_history: score *= 2.0 // Threshold evaluation if score ≥ 100: action = TEMPORARY_BAN else if score ≥ 50: action = RATE_LIMIT_REDUCTION else if score ≥ 25: action = WARNING else: action = NONE

Proof of Work (Optional)

Proof of Work (PoW) provides a computational cost barrier for high-volume senders, making spam economically unfeasible.

Hashcash-Style PoW for High-Volume Senders

TriggerPoW RequirementDifficulty
Normal usageNoneN/A
Rate limit warningOptional for faster sendingEasy (16-bit)
Rate limit exceededRequired for each messageMedium (20-bit)
Spam score elevatedRequired with higher difficultyHard (24-bit)
Previous violationsAlways requiredVariable

PoW Challenge-Response Protocol

PoW Protocol Flow: 1. Client exceeds rate limit 2. Server responds: { challenge: random_256_bit_nonce, difficulty: target_leading_zeros, algorithm: "sha256", expires: timestamp + 60 seconds } 3. Client computes: nonce = 0 while true: hash = SHA256(challenge || message_hash || nonce) if leading_zeros(hash) ≥ difficulty: break nonce = nonce + 1 4. Client sends message with proof: { message: encrypted_payload, pow_proof: { challenge: original_challenge, nonce: computed_nonce, hash: resulting_hash } } 5. Server verifies: - Challenge is valid and not expired - Hash meets difficulty requirement - Challenge not previously used (prevent replay)

Difficulty Adjustment

FactorEffect on DifficultyRange
Current spam level+2 bits per 10% increase16-28 bits
User reputation-4 bits for trusted12-24 bits
Time of day (load)+2 bits during peakVariable
Recent PoW solves-1 bit per 10 valid solvesMinimum 12 bits

Difficulty Computation Examples

DifficultyExpected IterationsTime (modern CPU)Time (mobile)
16 bits65,536~1 ms~10 ms
20 bits1,048,576~15 ms~150 ms
24 bits16,777,216~250 ms~2.5 s
28 bits268,435,456~4 s~40 s

When PoW is Required

PoW Decision Matrix: │ Good Reputation │ Neutral │ Poor Reputation ────────────────────────┼─────────────────┼─────────┼───────────────── Under rate limit │ Never │ Never │ Optional At rate limit │ Never │ Optional│ Required (easy) Exceeded rate limit │ Optional │ Required│ Required (medium) Spam score elevated │ Required (easy) │ Required│ Required (hard) Previous ban │ Required │ Required│ Required (very hard) PoW Bypass Conditions: - Emergency messages (predefined contacts) - Account verification completed - Premium subscription active - Message to existing conversation (recent activity)

PoW Economics

Spam VolumePoW Cost (electricity)Spam Viability
1,000/day~$0.01Viable
10,000/day~$0.10Marginally viable
100,000/day~$1.00Not viable
1,000,000/day~$10.00Economically prohibitive

Reputation System

Zentalk’s reputation system provides graduated trust levels based on account history and behavior.

Account Age Factor

Account AgeReputation MultiplierRate Limit Multiplier
0-24 hours0.5x0.3x
1-7 days0.7x0.5x
7-30 days0.85x0.75x
30-90 days1.0x1.0x
90-365 days1.1x1.25x
More than 1 year1.25x1.5x

Verified Contacts Boost

Verified ContactsReputation BoostNotes
0NoneNew user
1-5+5%Beginning network
6-20+10%Growing network
21-50+15%Established user
51-100+20%Active user
More than 100+25%Power user (capped)

Reputation Score Components

Reputation Calculation: base_score = 50 // Starting reputation // Positive factors age_bonus = min(account_age_days / 365 * 20, 20) contact_bonus = min(verified_contacts * 0.25, 25) activity_bonus = calculate_activity_score() // 0-10 verification_bonus = (phone_verified ? 5 : 0) + (email_verified ? 5 : 0) // Negative factors violation_penalty = violations_count * 10 spam_penalty = spam_reports_received * 5 rate_limit_penalty = rate_limit_hits_30d * 0.5 // Final calculation reputation = base_score + age_bonus + contact_bonus + activity_bonus + verification_bonus - violation_penalty - spam_penalty - rate_limit_penalty reputation = clamp(reputation, 0, 100) Reputation Tiers: 0-20: Restricted (0.5x limits) 21-40: Limited (0.75x limits) 41-60: Standard (1.0x limits) 61-80: Trusted (1.25x limits) 81-100: Highly Trusted (1.5x limits)

Penalty for Violations

Violation TypeReputation ImpactDuration
Rate limit exceeded (first)-2 points7 days
Rate limit exceeded (repeat)-5 points14 days
Spam report received-5 points30 days
Multiple spam reports-15 points90 days
Temporary ban-20 points180 days
Terms violation-30 points365 days
Permanent ban appealed-50 pointsPermanent

Reputation Recovery

Recovery ActionPoints RecoveredTimeframe
No violations+1 pointPer week
Active legitimate usage+0.5 pointsPer week
Successful verification+5 pointsOne-time
Successful appeal+10 pointsPer appeal
Community contribution+2 pointsPer action

Cross-Device Reputation

Multi-Device Reputation Sync: Primary device holds authoritative reputation ├── Device 1 (primary) │ reputation = 75 │ last_sync = now ├── Device 2 (secondary) │ reputation = derived from primary │ deviation_allowance = ±5 points └── Device 3 (secondary) reputation = derived from primary deviation_allowance = ±5 points On violation on any device: - Penalty applied to primary reputation - Synced to all devices within 1 hour - Device-specific rate limits may vary On positive action: - Bonus applied to primary reputation - Synced on next heartbeat

Abuse Response

Zentalk implements a graduated response system for handling abuse.

Temporary Throttling

Offense LevelThrottle DurationRate ReductionMessage to User
First warning5 minutes50%“Slow down”
Second warning30 minutes75%“Rate limited”
Third warning2 hours90%“Significant restriction”
Continued abuse24 hours95%“Temporary restriction”

Throttling Response Headers

HeaderDescriptionExample
X-RateLimit-LimitMaximum requests allowed60
X-RateLimit-RemainingRequests remaining0
X-RateLimit-ResetUnix timestamp for reset1704067200
Retry-AfterSeconds until retry allowed300
X-RateLimit-ReasonHuman-readable reason”hourly_limit_exceeded”

Account Suspension Levels

LevelDurationTriggerRestrictions
WarningNoneFirst minor offenseNone (notification only)
Level 11 hourRepeated minor offensesSend only to contacts
Level 224 hoursModerate offenseNo group messages
Level 37 daysSerious offenseRead-only mode
Level 430 daysSevere offenseFull suspension
PermanentIndefiniteExtreme violationAccount terminated

Suspension Actions by Level

Suspension Level Actions: Level 1 (1 hour): - Can receive messages - Can send to existing contacts only - Cannot create new sessions - Cannot join groups Level 2 (24 hours): - Can receive messages - Can send 1:1 only (10/hour max) - Cannot send to groups - Cannot create groups Level 3 (7 days): - Can receive messages - Cannot send any messages - Can read group messages - Cannot interact Level 4 (30 days): - Cannot send or receive - Account appears offline - Messages queued for 7 days then dropped - Must re-verify to restore Permanent: - Identity key blacklisted - Cannot register new identity - All data purged after 30 days

Appeal Process

StepActionTimeframe
1User submits appealAnytime
2Automated reviewWithin 1 hour
3Human review (if needed)Within 48 hours
4Decision communicatedWithin 72 hours
5Escalation (if disputed)Within 7 days

Appeal Request Format

Appeal Submission: POST /api/v1/appeal { "user_id": "0x1234...5678", "suspension_id": "susp_abc123", "appeal_type": "wrongful_suspension", "description": "User-provided explanation", "evidence": [ // Optional supporting information ], "contact_email": "user@example.com" } Response: { "appeal_id": "appeal_xyz789", "status": "received", "estimated_review": "2024-01-20T00:00:00Z", "tracking_url": "https://zentalk.io/appeal/xyz789" }

Automated vs Human Review

CriteriaAutomated ReviewHuman Review
Clear-cut rate limitYesNo
First offenseYesNo
Pattern-based detectionYesOptional
User-reported spamNoYes
Appeal submittedInitialFinal decision
Legal/safety issuesNoAlways

DDoS Protection

Distributed Denial of Service protection operates at multiple layers of the Zentalk network.

Relay Node Protection

Protection LayerMechanismCapacity
Network levelTraffic rate limiting10 Gbps
Transport levelSYN flood protection1M SYN/s
Application levelRequest rate limiting100K req/s
Protocol levelInvalid packet filteringUnlimited

Relay Node Defense Mechanisms

Multi-Layer DDoS Defense: Layer 1: Network Edge ├── BGP Flowspec rules ├── IP reputation filtering ├── Geographic restrictions (optional) └── Anycast distribution Layer 2: Load Balancer ├── Connection rate limiting ├── SSL/TLS termination ├── Request inspection └── Backend health monitoring Layer 3: Application ├── Per-user rate limiting ├── Authentication verification ├── Request validation └── Circuit breaker patterns Layer 4: Protocol ├── Message format validation ├── Sequence number checking ├── Replay attack prevention └── Resource exhaustion limits

DHT Flooding Prevention

Attack TypeDetectionMitigation
Sybil attackNode ID clusteringProof of work for node ID
Eclipse attackRouting table analysisMultiple bootstrap nodes
Index poisoningValue verificationSigned records only
Lookup floodingQuery rate monitoringPer-node query limits

DHT Protection Parameters

ParameterValuePurpose
Queries per node per second10Prevent query floods
Responses per query8Limit amplification
Node ID difficulty16 bitsSybil resistance
Routing table size160 buckets, 20 nodes eachLimit memory
Value storage per node10,000 recordsPrevent storage abuse

Circuit Creation Limits

LimitValuePurpose
Circuits per user10 concurrentResource fairness
Circuit creation rate5 per minutePrevent relay exhaustion
Circuit lifetime10 minutesResource recycling
Failed circuit penalty+30s cooldownPrevent probing

Circuit Creation Protocol

Circuit Creation Rate Limiting: Client-side: circuit_tokens = 5 // Replenish 1 per 12 seconds create_circuit(): if circuit_tokens ≤ 0: wait_for_token() circuit_tokens -= 1 result = attempt_circuit_creation() if result == FAILED: circuit_tokens -= 0.5 // Extra penalty return result Relay-side: per_client_circuits = {} // Track per client on_create_request(client_id): count = per_client_circuits[client_id] if count ≥ MAX_CIRCUITS_PER_CLIENT: return REJECT_LIMIT_EXCEEDED if creation_rate(client_id) > MAX_RATE: return REJECT_RATE_LIMITED // Process creation per_client_circuits[client_id] += 1 return create_circuit()

Attack Response Escalation

Threat LevelDetection TriggerResponse
NormalBaseline trafficStandard limits
Elevated2x normal traffic0.75x rate limits
High5x normal traffic0.5x rate limits, PoW required
Severe10x normal trafficEmergency mode, whitelist only
CriticalInfrastructure at riskTemporary shutdown, escalation

Emergency Mode Behavior

Emergency Mode Activation: Triggers: - CPU usage > 90% sustained for 5 minutes - Memory usage > 95% - Network saturation > 90% - Request queue depth > 10,000 Actions: 1. Enable strict rate limiting (0.1x normal) 2. Require PoW for all requests 3. Whitelist known-good clients 4. Drop all unauthenticated connections 5. Alert operations team 6. Begin traffic analysis for attack signature Recovery: - Metrics must be normal for 15 minutes - Gradual limit restoration (25% increments) - Full restoration after 1 hour stable

Implementation Guidelines

Client Implementation Checklist

ComponentRequirementPriority
Local rate limiterToken bucket implementationRequired
Retry logicExponential backoff with jitterRequired
Offline queuePersist messages during rate limitRequired
PoW solverSHA256 hashcash implementationRequired
Rate displayShow remaining quota to userRecommended
Graceful degradationFunction during restrictionsRequired

Server Implementation Checklist

ComponentRequirementPriority
Distributed counterRedis/similar for rate trackingRequired
Sliding windowAccurate rate calculationRequired
Reputation storePersistent user reputationRequired
PoW validatorChallenge generation and verificationRequired
Metrics collectionRate limit hit trackingRequired
Alert systemAnomaly detection and notificationRecommended

Testing Rate Limits

Rate Limit Testing Strategy: Unit Tests: - Token bucket refill accuracy - Burst allowance consumption - PoW difficulty calculation - Reputation score computation Integration Tests: - End-to-end rate limit enforcement - Multi-device rate aggregation - Distributed counter consistency - Recovery after rate limit Load Tests: - Sustained rate at limit boundary - Burst behavior validation - PoW solver performance - System behavior under attack simulation Test Scenarios: 1. Normal user behavior (should never hit limits) 2. Power user behavior (occasional soft limits) 3. Spam simulation (should be blocked quickly) 4. DDoS simulation (should trigger emergency mode)
Last updated on