Policies
Defining rate limits using Policy objects.
A Policy defines the rules for rate limiting. It specifies the limit, window, algorithm, and optional burst capacity.
Anatomy of a Policy
interface Policy {
name: string; // Unique identifier for the policy
limit: number; // Max requests allowed
window: number; // Time window in seconds
algorithm: Algorithm; // Rate limiting algorithm
burst?: number; // Optional burst capacity (Token Bucket only)
slidingPrecision?: number; // Optional sub-window count (Sliding Window only, default 10)
blockDuration?: number; // Optional blocking duration in seconds
}Sliding-window precision
New in v0.5.0. When you use the Sliding Window algorithm, you can tune how finely the rolling window is subdivided with slidingPrecision (TypeScript) / sliding_precision (Python). It defaults to 10 and must be a positive integer.
- Higher precision → more accurate rolling-window behavior, more state / memory overhead.
- Lower precision → coarser approximation, lower state / memory overhead.
Pythonpython
from halt import Policy, Algorithm
policy = Policy(
name="precise_limit",
limit=100,
window=60,
algorithm=Algorithm.SLIDING_WINDOW,
sliding_precision=20, # finer than the default 10
)TypeScripttypescript
import { Algorithm } from 'halt-rate';
const policy = {
name: 'precise_limit',
limit: 100,
window: 60,
algorithm: Algorithm.SLIDING_WINDOW,
slidingPrecision: 20, // finer than the default 10
};Scope: this setting affects the in-process sliding-window path (e.g. the in-memory store). The Redis atomic sliding-window is unchanged — its precision is fixed by the Lua script.
Creating Policies
You can create custom policies or use presets.
Custom Policy
from halt import Policy, Algorithm
custom_policy = Policy(
name="custom_limit",
limit=500,
window=3600,
algorithm=Algorithm.SLIDING_WINDOW
)Using Presets
Halt comes with built-in presets for common scenarios.
import { presets } from 'halt-rate';
// presets.PUBLIC_API: 100 req/min (Token Bucket)
// presets.AUTH_ENDPOINTS: 5 req/min (Fixed Window)
// presets.EXPENSIVE_OPS: 10 req/min (Sliding Window)