← Back to all products
$19
API Rate Controller
API rate limiting with per-tenant and per-plan rate limits using sliding windows.
PythonMarkdown
📄 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 10 files
api-rate-controller/
├── LICENSE
├── README.md
├── examples/
│ └── basic_example.py
├── free-sample.zip
├── guide/
│ ├── 01_features.md
│ ├── 02_quick-start.md
│ ├── 03_rate-limit-headers.md
│ └── 04_license.md
├── index.html
└── src/
└── main.py
📖 Documentation Preview README excerpt
API Rate Controller
A Python API rate limiting system for SaaS applications. Provides per-tenant and per-plan rate limiting with sliding window counters, quota management, throttling, overage handling, and real-time limit headers — all built on Python's standard library.
Features
- Per-tenant limits — Different rate limits for each tenant based on their plan
- Sliding window — Accurate rate limiting using sliding window counters (not just fixed windows)
- Multiple windows — Enforce per-second, per-minute, per-hour, and per-day limits simultaneously
- Plan-based tiers — Define rate limit tiers (free, starter, pro, enterprise) with different limits
- Quota management — Monthly/daily quotas separate from burst rate limits
- Throttling — Gradual slowdown near limits instead of hard cutoff (optional)
- Overage handling — Allow overage with tracking, or hard-block at limit
- Rate limit headers — Standard
X-RateLimit-*headers for every response - IP-based fallback — Rate limit by IP when tenant is unknown (login, public endpoints)
- Analytics — Track limit hits, throttle events, and blocked requests per tenant
- Middleware pattern — Wrap any HTTP handler with rate limiting via decorator
Requirements
- Python 3.10+
- No external dependencies (stdlib only)
Quick Start
python src/main.py --init-demo
# Check rate limit status for a tenant
curl http://localhost:8009/api/limits/tenant_acme
# Simulate an API request (consumes 1 unit)
curl -X POST http://localhost:8009/api/check \
-H "Content-Type: application/json" \
-d '{"tenant_id": "tenant_acme", "endpoint": "/api/data", "cost": 1}'
# Get quota status
curl http://localhost:8009/api/quota/tenant_acme
# View rate limit analytics
curl http://localhost:8009/api/analytics/tenant_acme
# Manage plans
curl http://localhost:8009/api/plans
# Create a custom plan
curl -X POST http://localhost:8009/api/plans \
-H "Content-Type: application/json" \
-d '{"name": "custom", "requests_per_second": 50, "requests_per_minute": 2000, "requests_per_hour": 50000, "daily_quota": 500000}'
# Assign plan to tenant
curl -X PUT http://localhost:8009/api/tenants/tenant_acme/plan \
-H "Content-Type: application/json" \
-d '{"plan_id": "custom"}'
API Endpoints
... continues with setup instructions, usage examples, and more.
📄 Code Sample .py preview
src/main.py
#!/usr/bin/env python3
"""
API Rate Controller — Per-Tenant Rate Limiting & Quota Management
==================================================================
A complete API rate limiting system for SaaS applications. Provides
sliding-window counters, per-tenant and per-plan rate limits, multiple
time windows (second/minute/hour/day), daily and monthly quotas,
throttling, overage handling, IP-based fallback, and standard
rate-limit headers.
Zero dependencies. Just run: python3 main.py
Part of the SaaS Starter collection by DataNest.
License: MIT
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import time
import uuid
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone, timedelta
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any, Optional
from urllib.parse import parse_qs, urlparse
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULT_HOST = "0.0.0.0"
DEFAULT_PORT = 8009
DATA_DIR = Path("./ratelimit-data")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("api-rate-controller")
# ---------------------------------------------------------------------------
# ... 699 more lines ...