Add Discord rate limiting with exponential backoff retry mechanism

Abierto
#284 1 comentario 0 reacciones 0 asignados Ver en GitHub

@mahek2016 ya está trabajando en esto.

Desde el 22/2/2026.

  • #288 de @mahek2016 — abierto
  • #289 de @anshulchikhale30-p — abierto
  • #302 de @Shevilll — abierto

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
25/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
python, redis
Área
api, backend

Línea de trabajo

Empieza leyendo backend/bot.py y la documentación de Discord sobre límites de tasa a la que se hace referencia, y después revisa el backend/rate_limiter.py propuesto, backend/discord_client.py y los archivos de pruebas del issue. Valida el diseño según los requisitos indicados de reintentos, Redis, registro, colas, rendimiento y cobertura. La tarea estará terminada cuando el bot existente use el cliente mejorado y todas las pruebas y criterios de aceptación indicados pasen.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Is your feature request related to a problem?
  • Yes, it is related to a problem
Describe the feature you'd like

Problem

The Discord bot lacks proper rate limit handling:

  • 429 errors occur when hitting Discord API rate limits
  • No recovery mechanism - errors just propagate to user
  • Poor user experience - message send failures without auto-retry
  • Silent failures - no logging of rate limit incidents

Current Behavior

User command → Bot tries to send → 429 Error → User sees "something went wrong"

Desired Behavior

User command → Bot tries to send → 429 Error → Auto-retry with exponential backoff → Success

Solution Overview

Implement a robust rate limiting system with:

  1. Rate limit tracking per Discord endpoint/bucket
  2. Exponential backoff retry logic (2^n + jitter)
  3. Command queueing during rate limits
  4. Comprehensive logging and metrics
  5. Graceful degradation with user-friendly messages

Implementation Details

Component 1: Rate Limiter Core
  • Create backend/rate_limiter.py
  • Implement DiscordRateLimiter class with:
    • wait_if_rate_limited() - Check if endpoint is rate limited
    • execute_with_retry() - Execute with automatic retry
    • Exponential backoff: 2^attempt × retry_after + jitter
    • Maximum 3 retry attempts
Component 2: Discord Client Wrapper
  • Create backend/discord_client.py
  • Implement EnhancedDiscordClient class with:
    • send_message_with_retry() - Send with rate limit handling
    • edit_message_with_retry() - Edit with rate limit handling
    • Error handling for 429 responses
    • User-friendly error messages
Component 3: Redis Integration
  • Use Redis to track rate limit state across bot instances
  • Store: discord_ratelimit:bucket:remaining, discord_ratelimit_reset:bucket
  • Per-endpoint tracking (channels, reactions, etc.)

Files to Create

backend/
├── rate_limiter.py (180 lines) - Core rate limiting logic
├── discord_client.py (250 lines) - Enhanced Discord client
└── discord_utils.py (80 lines) - Helper utilities
tests/
├── test_rate_limiter.py (200 lines) - Rate limiter tests
├── test_discord_client.py (150 lines) - Client tests
└── fixtures/discord_mocks.py (100 lines) - Test fixtures
docs/
└── DISCORD_RATE_LIMITING.md (150 lines) - Usage documentation

Integration Points

  • Update backend/bot.py to use enhanced client (+45 lines)
  • Add redis>=4.0.0 to requirements.txt
  • Set environment: REDIS_URL=redis://localhost:6379

Testing

  • 12+ unit tests for rate limiter logic
  • Integration tests with mock Discord API
  • Exponential backoff calculation verification
  • Retry exhaustion handling
  • Performance tests (minimal overhead when not rate limited)

Acceptance Criteria

  • Rate limits properly detected and handled
  • Automatic retry with exponential backoff
  • Maximum 3 retry attempts configurable
  • Command queueing during rate limits
  • Rate limit incidents logged with details
  • Zero performance impact when not rate limited
  • 90%+ test coverage
  • No merge conflicts
  • All existing tests still pass
  • Documentation included

Performance Requirements

  • Overhead when NOT rate limited: <1ms per request
  • Successful retry adds latency only when rate limited
  • Redis operations are async and non-blocking
  • No impact on normal message flow

Migration Guide

For deployments using this:

  1. Install Redis: pip install redis>=4.0.0
  2. Set REDIS_URL environment variable
  3. Start Redis service
  4. Update code to use EnhancedDiscordClient
  5. Test in staging first
  6. Deploy with monitoring

References

Related Issues

Fixes: Bot resilience failures when hitting Discord limits
Related to: #48 (general bot reliability)

Nice to Have (Future)

  • Prometheus metrics for rate limit tracking
  • Rate limit prediction using historical data
  • Per-guild rate limiting
  • Analytics dashboard
Record
  • I agree to follow this project's Code of Conduct
  • I want to work on implementing this feature
Lenguaje dominante
Python
Estrellas
103
Forks
143
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

  • Sin Dockerfile ni archivo de Docker Compose
  • Tiene una plantilla de pull request
  • Sin guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de AOSSIE-Org/Devr.AI

Todos los issues de AOSSIE-Org/Devr.AI

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.