Add Discord rate limiting with exponential backoff and Redis coordination (#284)
Closes #284
π Description
This PR implements robust Discord API rate limit handling to improve bot resilience and production readiness.
It introduces automatic handling of HTTP 429 responses using exponential backoff and Redis-based coordination, preventing user-facing failures when Discord rate limits are hit.
The implementation ensures:
Automatic 429 detection
Exponential backoff retry logic (2^n + jitter)
Configurable maximum retry attempts (default: 3)
Redis-based distributed rate limit tracking
Per-channel bucket isolation
Command queueing using per-channel asyncio locks
Graceful failure after retry exhaustion
This resolves the issue of silent failures and improves reliability during high traffic.
π§ Changes Made
Added DiscordRateLimiter class for retry and backoff handling
Implemented per-channel Redis bucket tracking
Integrated rate limiter into Discord bot message sending logic
Added per-channel asyncio.Lock to prevent retry storms
Added unit tests for retry and backoff validation
Added documentation in docs/DISCORD_RATE_LIMITING.md
π· Screenshots or Visual Changes (if applicable)
Not applicable β backend resilience improvement only.
π€ Collaboration
Collaborated with: N/A
β Checklist
- [x] I have read the contributing guidelines.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] I have added necessary documentation (if applicable).
- [x] Any dependent changes have been merged and published in downstream modules.
Summary by CodeRabbit
-
New Features
- Improved Discord messaging reliability with distributed rate-limit handling, per-channel serialization, and automatic chunked message delivery.
- Expanded Discord intents for richer interactions (including DMs and member events).
-
Documentation
- Added comprehensive Discord rate-limiting docs covering retry behavior, distributed coordination, configuration, and operational guidance.
-
Tests
- Added tests validating rate-limit retry logic, backoff behavior, and Redis-backed coordination.
Adds a Redis-backed Discord API rate limiter with exponential backoff and per-channel asyncio locking, updates the Discord bot to use the limiter for send operations, and adds tests and documentation describing the design and behavior. π― 4 (Complex) | β±οΈ ~45 minutes π° I nibble bytes and hop in code, Through Redis fields and backoff road. βοΈ Tip: You can configure your own custom pre-merge checks in the settings.π Walkthrough
Walkthrough
Changes
Cohort / File(s)
Summary
Documentation
docs/DISCORD_RATE_LIMITING.mdNew doc describing architecture: 429 detection, exponential backoff with jitter, configurable retries, Redis-based distributed tracking (
discord_ratelimit:<bucket>), per-channel bucket isolation, asyncio lock-based queuing, performance characteristics, config and testing notes.
Rate limiter core
backend/rate_limiter.pyNew
DiscordRateLimiter class: Redis-aware per-bucket wait, _set_limit, _wait_if_limited, exponential backoff with jitter, and execute_with_retry wrapper that handles 429 responses and retry logic.
Discord integration
backend/integrations/discord/bot.pyReworked bot flow to use per-channel
asyncio.Lock and DiscordRateLimiter; removed previous queue/triage path, initializes rate limiter (uses REDIS_URL), serializes per-channel processing, and sends responses in rate-limited chunks. Constructor signature simplified.
Tests
tests/test_rate_limiter.pyNew unit tests for rate limiter: success path, retry-on-429, max retries exceeded, backoff progression, Redis key set on 429, and wait behavior; uses async mocks and a Mock429 HTTPException.
Sequence Diagram(s)
sequenceDiagram
autonumber
participant User
participant Bot as DiscordBot
participant RL as DiscordRateLimiter
participant Redis
participant DiscordAPI
User->>Bot: Send command / message
Bot->>Bot: _get_or_create_thread() & acquire channel lock
Bot->>RL: execute_with_retry(send_request, bucket=channel_id)
RL->>Redis: GET discord_ratelimit:<bucket> (check reset)
alt Redis indicates limited
RL->>RL: sleep until reset / backoff
end
RL->>DiscordAPI: HTTP request to send message
alt DiscordAPI returns 429
DiscordAPI-->>RL: 429 with retry_after
RL->>Redis: SET discord_ratelimit:<bucket> (expiry)
RL->>RL: calculate backoff + jitter, retry
RL->>DiscordAPI: retry request (up to max_retries)
else 2xx/other success
DiscordAPI-->>RL: success
end
RL-->>Bot: result / raise on exhaustion
Bot->>Bot: release channel lock / send acknowledgement
Bot-->>User: Response delivered
Estimated code review effort
Poem
When 429s block the way, I try,
With jitter hops and patience high.
Hooray β our messages now fly! π₯β¨π₯ Pre-merge checks | β
2 | β 3
β Failed checks (2 warnings, 1 inconclusive)
Check name
Status
Explanation
Resolution
Linked Issues check
β οΈ Warning
The PR implements core requirements from
#284: DiscordRateLimiter with exponential backoff and Redis state tracking, per-channel isolation via asyncio.Lock, automatic 429 detection/retry, and documentation; however, EnhancedDiscordClient wrapper and discord_client.py are absent.Implement EnhancedDiscordClient in backend/discord_client.py with send_message_with_retry() and edit_message_with_retry() methods as specified in
#284 Component 2, or clarify if direct integration into bot.py replaces this requirement.
Docstring Coverage
β οΈ Warning
Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%.
Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check
β Inconclusive
The PR modifies backend/integrations/discord/bot.py to integrate rate limiting and removes AsyncQueueManager dependency; while this aligns with rate limiting objectives, it represents significant architectural refactoring beyond the scope of simply adding rate limiting.
Clarify whether refactoring the entire message queue architecture was necessary for rate limiting integration, or if rate limiting could be added without removing AsyncQueueManager and ClassificationRouter.
β
Passed checks (2 passed)
Check name
Status
Explanation
Description Check
β
Passed
Check skipped - CodeRabbitβs high-level summary is enabled.
Title check
β
Passed
The title accurately describes the main change: adding Discord rate limiting with exponential backoff and Redis coordination, matching the core implementation across multiple files.
β¨ Finishing Touches
π§ͺ Generate unit tests (beta)
[!TIP] Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.