← Back to all products
$9
Rate Limiter
Four production-ready rate limiting algorithms in a single Python module, zero dependencies.
JSONMarkdownPython
📄 Product Preview
Try the interactive reader and demo tools below, or get the full product with all content unlocked.
📖 Interactive Reader (Free Preview) ⚙ Try Demo Tools 📦 Download Free Sample📁 File Structure 9 files
rate-limiter/
├── LICENSE
├── README.md
├── examples/
│ └── config.example.json
├── free-sample.zip
├── guide/
│ ├── 01_rate-limiter.md
│ ├── 02_features.md
│ └── 03_quick-start.md
├── index.html
└── src/
└── main.py
📖 Documentation Preview README excerpt
Rate Limiter
Four production-ready rate limiting algorithms in a single Python module. Zero dependencies.
Part of the API Launchpad toolkit by [CodeVault](https://codevault.dev).
Features
- Four algorithms: Token Bucket, Sliding Window Log, Sliding Window Counter, Fixed Window
- Three key extractors: IP address, API key, per-path rate limits
- HTTP middleware with
X-RateLimit-*response headers (IETF draft standard) - Thread-safe with stdlib threading locks
- Automatic cleanup of expired rate limit entries
- Demo server included — see rate limiting in action
- Zero dependencies — runs on Python stdlib only
Quick Start
# Start demo server with Token Bucket (10 req/min)
python3 src/main.py --algo token-bucket --limit 10 --window 60
# Test rate limiting
for i in $(seq 1 15); do
curl -s http://localhost:8000/ | python3 -m json.tool
done
Algorithm Comparison
| Algorithm | Burst Handling | Memory | Accuracy | Best For |
|---|---|---|---|---|
| Token Bucket | Allows bursts | Low | Good | APIs with bursty traffic |
| Sliding Window Log | No bursts | High | Exact | When precision matters |
| Sliding Window Counter | Minimal bursts | Low | Good | High-volume APIs |
| Fixed Window | 2x at boundary | Low | Approximate | Simple use cases |
Token Bucket
Tokens refill at a constant rate. Allows short bursts (up to bucket capacity) while maintaining a long-term rate.
Sliding Window Log
Stores every request timestamp. Precise but memory grows with request count.
Sliding Window Counter
Interpolates between current and previous fixed windows. Good balance of accuracy and memory.
Fixed Window
Simple counter per time window. Clients can send 2x the limit at window boundaries.
Usage as a Library
from main import TokenBucketLimiter, RateLimitMiddleware, ip_key_extractor
# Create a limiter: 100 requests per 60 seconds
limiter = TokenBucketLimiter(capacity=100, refill_rate=100/60)
# Check a request
result = limiter.check("192.168.1.1")
if result.allowed:
*... continues with setup instructions, usage examples, and more.*
📄 Code Sample .py preview
src/main.py
#!/usr/bin/env python3
"""
Rate Limiter — Production-Ready Rate Limiting Library
======================================================
Four rate limiting algorithms in a single Python module:
Token Bucket, Sliding Window Log, Sliding Window Counter, and Fixed Window.
Supports IP-based, API-key-based, and custom key extraction. Includes
HTTP middleware integration and X-RateLimit-* response headers.
Zero dependencies. Import or run standalone.
Part of the API Launchpad toolkit by DataNest.
License: MIT
"""
from __future__ import annotations
import json
import logging
import threading
import time
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from typing import Any, Callable
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULT_HOST = "0.0.0.0"
DEFAULT_PORT = 8000
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("rate-limiter")
# ---------------------------------------------------------------------------
# Rate Limit Result
# ---------------------------------------------------------------------------
@dataclass
# ... 489 more lines ...