Skip to content

Add WebSocket rate limiting#17

Open
chredeur wants to merge 2 commits intopgjones:mainfrom
pastanetwork:main
Open

Add WebSocket rate limiting#17
chredeur wants to merge 2 commits intopgjones:mainfrom
pastanetwork:main

Conversation

@chredeur
Copy link
Copy Markdown

@chredeur chredeur commented Sep 29, 2025

Motivation

I often use fastapi-limiter and noticed that a similar feature was missing in quart-rate-limiter.
This PR introduces WebSocket rate limiting, inspired by fastapi-limiter, while keeping the setup simple.

Summary

Adds WebSocket rate limiting that automatically reuses the same store as your HTTP rate limiter no extra configuration required!

What’s New

  • WebSocketRateLimiter class with a fastapi-limiter-compatible API
  • WebSocketRateLimitException for handling rate limit violations
  • Automatic store sharing between HTTP and WebSocket rate limiting
  • Works with all existing backends (Memory, Redis, Valkey)

How It Works

# Set up your rate limiter as usual
redis_store = RedisStore("redis://localhost:6379/0")
RateLimiter(app, store=redis_store)

# The WebSocketRateLimiter automatically uses the same Redis store
@app.websocket("/ws")
async def websocket_endpoint():
    ratelimit = WebSocketRateLimiter(times=1, seconds=5)

    while True:
        try:
            data = await websocket.receive()
            await ratelimit(websocket, context_key=data)
            await websocket.send("Hello!")
        except WebSocketRateLimitException:
            await websocket.send("Slow down!")

No need to configure your stores twice it works out of the box and keeps HTTP and WebSocket limits in sync.

chredeur and others added 2 commits September 20, 2025 13:01
Implement WebSocketRateLimiter class compatible with fastapi-limiter API that automatically detects and uses the global RateLimiter's store configuration for consistent rate limiting across HTTP and WebSocket connections.

Features:
- WebSocketRateLimiter with times/seconds/minutes/hours parameters
- WebSocketRateLimitException for rate limit violations
- Automatic detection of global store via QUART_RATE_LIMITER_STORE config
- Support for context_key parameter to differentiate message types
- Compatible with all existing storage backends (Memory, Redis, Valkey)
- Fallback to MemoryStore when no global store or app context available
- Comprehensive test coverage with real Quart app fixtures
- Complete documentation including configuration guide and WebSocket usage

Signed-off-by: chredeur <50155089+chredeur@users.noreply.github.com>
Signed-off-by: chredeur <50155089+chredeur@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant