The user wants a "rate limiter service".
The specific requirements are:
Quotas: Users/tenants have limits.
Tokens: Likely refers to the Token Bucket algorithm (or maybe just authentication tokens, but in the context of rate limiting, it usually implies the algorithm).
Sliding Windows: An algorithm to ensure limits are strictly enforced over a time window.
Per-tenant isolation: Data and limits for one tenant shouldn't affect another.
Architecture & Tech Stack:
Language: Python is great for explaining concepts, but Go or Java are often preferred for high-performance systems. I'll stick to Python (FastAPI) for readability and ease of understanding the logic, but I'll mention that Redis is crucial for distribution.
Storage: In-memory is bad for distributed systems. Redis is the industry standard for rate limiting due to atomic operations (Lua scripts) and low latency.
Algorithm Selection:
Token Bucket: Good for handling bursts.
Sliding Window (Log or Precise): Good for strict limits.
The prompt asks for "Sliding Windows", so I should probably implement a Sliding Window Log or a Fixed Window with Sliding Window approximation (often called "Sliding Window Counter"). The "Pure Sliding Window" usually requires storing every request timestamp (expensive), while the "Approximation" uses two fixed windows. I will implement the most common and robust one: Redis-based Sliding Window Log (stores timestamps) or Token Bucket.
Wait, the prompt asks for "tokens" AND "sliding windows".
Interpretation A: Use Token Bucket algorithm.
Interpretation B: Use Sliding Window algorithm.
Interpretation C: Support both or clarify. Usually, when people say "tokens" in this context, they mean "Token Bucket". When they say "Sliding Windows", they mean "Sliding Window".
I will implement a Flexible Rate Limiter that supports Token Bucket (for bursts) and Sliding Window (for strict limits). I'll build a generic interface.
Actually, to keep it concise and production-oriented, I'll implement the Sliding Window Counter algorithm using Redis, as it's efficient. But since "Tokens" is explicitly mentioned, I will implement Token Bucket as the primary logic, as it allows "saving up" capacity (tokens).
Self-correction: The prompt lists "quotas, tokens, sliding windows" as a list of features. It likely means:
Quotas: The limit configuration.
Tokens: The implementation mechanism (Token Bucket) OR API Tokens. Let's assume Token Bucket logic.
Sliding Windows: An alternative implementation mechanism.
Decision: I will provide a Python implementation using Redis. I will implement Token Bucket logic because it handles bursts better, which is usually desirable, and I'll also show how to do a Sliding Window implementation for comparison, or combine them.
Let's stick to the Sliding Window Log approach for strict enforcement, or Token Bucket for efficiency.
Actually, the "Standard" robust solution is usually the Generic Cell Rate Algorithm (GCRA) or Token Bucket.
Let's implement a Token Bucket algorithm stored in Redis. It's the most standard interpretation of "tokens".
However, "Sliding Window" is a distinct requirement. I will implement a Sliding Window Log (sorted sets in Redis) to satisfy the "Sliding Window" specific requirement, as it provides the smoothest rate limiting.
Key Components:
API: FastAPI.
Database: Redis (for atomic state).
Models: Tenant, Quota (Limit, Window).
Logic:
allow_request(tenant_id): checks Redis.
Lua scripts for atomicity.
Step-by-Step Plan:
Define the Data Model: What does a "Quota" look like? (e.g., 100 requests per minute).
Design the Redis Structure:
Sliding Window: ZSET (Sorted Set) with timestamps as scores. Remove old timestamps, count remaining. If count < limit, add new timestamp.
Token Bucket: Hash or String holding tokens and last_refill.
Implementation Details:
I'll provide a Python class RateLimiter.
I'll use redis-py.
I will implement Sliding Window using Sorted Sets (ZSET). This effectively covers "Sliding Window".
To cover "Tokens", I'll explain how Token Bucket differs and maybe provide that as an option, or implement Token Bucket. Let's do Token Bucket because "Tokens" is in the prompt title.
Actually, I'll provide the Sliding Window Log implementation. It is conceptually the "purest" sliding window. It removes old "tokens" (timestamps) and adds new ones.
Let's refine the "Tokens" part. If the user meant API Tokens (authentication), that's trivial middleware. If they meant "Token Bucket", that's the algorithm. Given the grouping ("quotas, tokens, sliding windows"), they likely mean the Token Bucket Algorithm AND Sliding Window Algorithm.
I will implement a service that allows choosing between them. Or, to be practical, I will implement Token Bucket (standard, handles bursts) and Sliding Window (strict).
Let's go with Sliding Window Log using Redis Sorted Sets. It's a very common interview/production pattern. It keeps "tokens" (request timestamps) in a window.
Wait, let's look at the prompt again: "quotas, tokens, sliding windows, and per-tenant isolation."
"Tokens" might just mean "API Keys" to identify the tenant. But usually, in a rate limiter context, "Token Bucket" is the algorithm.
I will assume the user wants a robust Rate Limiter Service that handles:
Tenants (identified by API Key/Token).
Quotas (Configurable limits per tenant).
Mechanism: Sliding Window (preferred for strict limits) or Token Bucket.
I will code the Sliding Window Counter (Approximation) or Sliding Window Log. The Log is precise but memory heavy. The Counter is lighter.
Let's write a Token Bucket implementation because it is efficient and uses the word "Token". It fits the "Tokens" requirement literally.
Actually, I will implement Generic Cell Rate Algorithm (GCRA) or just standard Token Bucket.
Let's stick to Token Bucket with Redis Lua scripting. It's fast and covers the "Tokens" keyword nicely. I will also explain the "Sliding Window" approach.
Actually, looking at the combination "Tokens" + "Sliding Windows", maybe they want a service that supports both strategies.
Let's build a Python class structure that supports:
In-memory storage (for testing) vs Redis (for prod).
Strategy Pattern: Swap between Sliding Window and Token Bucket.
FastAPI wrapper.
The Plan:
Concept: Use Redis.
Strategy 1 (Token Bucket): Fill tokens over time, consume on request.
Strategy 2 (Sliding Window): Keep timestamps, count in window.
Middleware: FastAPI Depends.
Let's focus on the Sliding Window Log using Redis Sorted Sets. Why?
It creates a strict sliding window.
It technically stores "tokens" (timestamps) in a set.
It handles per-tenant isolation easily (key prefix).
It's a very strong answer for "sliding window".
However, Token Bucket is also requested ("tokens").
I will provide a Hybrid or Configurable approach.
Let's write a solution that implements Token Bucket (it's generally better for APIs to allow bursts) but mention how to do Sliding Window.
Correction: The prompt lists "sliding windows" as a specific requirement. I must implement a sliding window logic.
I will implement the Sliding Window Log algorithm using Redis Sorted Sets. It's the most "correct" implementation of a sliding window.
Code Structure:
RateLimiter (Abstract Base Class)
TokenBucketLimiter (Implementation)
SlidingWindowLimiter (Implementation)
TenantManager (Handles quotas/keys)
FastAPI App demonstrating usage.
Refined Plan:
I will build a complete, runnable Python example using Redis.
I will implement the Sliding Window algorithm using Sorted Sets (ZSET) because it perfectly matches "Sliding Window" and implicitly handles "tokens" (as active request timestamps).
I will also provide the code for Token Bucket because it was explicitly asked for.
The "Service" aspect:
FastAPI entry point.
Dependency Injection for the limiter.
Configuration for tenants (Hardcoded dictionary for simplicity, but structure for DB).
Lua Scripting:
Crucial for Race Conditions. If two requests come in at the same time, Python logic might fail. The check-and-decrement must be atomic. I will write Lua scripts for the Redis operations.
I will provide both, selectable via config. This is a "premium" answer.
Implementation details:
Use redis library.
Use asyncio (FastAPI is async).
Dataclass for Tenant.
Safety check: Are there any security concerns?
Input validation on Tenant IDs.
Redis injection (handled by using library params).
Resource exhaustion: The sliding window log stores every request. If limit is 1,000,000, it stores 1M items. I should mention this or use the "Approximation" (counter) method for high limits.
Decision: I'll stick to the Log method for demonstration as it's conceptually pure, but add a comment about memory.