Rate Limiter API Reference¶
Auto-generated API documentation for the rate limiter module.
ratelimit
¶
Multi-algorithm rate limiter with zero dependencies.
Provides four in-memory rate-limiting algorithms behind a common
RateLimiter protocol, plus convenience wrappers (decorator, context
manager, async support, string quota notation).
Algorithms:
- Token bucket — smooth rate with configurable burst tolerance.
- Fixed window — simplest counter-per-window, lowest overhead.
- Sliding window counter — accurate without boundary-burst artifacts.
- GCRA (Generic Cell Rate Algorithm) — constant-rate shaping via a single TAT (Theoretical Arrival Time) timestamp.
Typical usage::
limiter = TokenBucketLimiter(rate=10.0, capacity=20)
result = limiter.acquire("client-ip")
if not result.allowed:
return 429, {"Retry-After": str(result.retry_after)}
# Or with convenience API
@ratelimit("10/s", algorithm="sliding_window")
def handle_request(): ...
Thread safety: individual limiter classes are not thread-safe.
For concurrent access from multiple threads, wrap with
:class:ThreadSafeLimiter or pass a pre-wrapped instance via the
limiter parameter of :class:ratelimit.
Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.
RateLimitResult
¶
Outcome of a rate-limit check.
Instances are not hashable (mutable __slots__ class).
Attributes:
| Name | Type | Description |
|---|---|---|
allowed |
Whether the request is permitted. |
|
limit |
Total quota (bucket capacity or window limit). |
|
remaining |
Remaining quota (>= 0). May be |
|
reset_at |
Monotonic timestamp when quota fully replenishes or the current window ends. |
|
retry_after |
Seconds to wait before retrying (raw |
Source code in ratelimit/ratelimit.py
RateLimiter
¶
Bases: Protocol
Common interface for all rate-limiter implementations.
Source code in ratelimit/ratelimit.py
TokenBucketLimiter
¶
Bases: _AsyncMixin, _EvictionMixin
Token-bucket rate limiter.
Tokens are replenished lazily on each acquire call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate
|
float
|
Tokens added per second. |
required |
capacity
|
int
|
Maximum tokens the bucket can hold (burst size). |
required |
clock
|
Callable[[], float] | None
|
Callable returning current monotonic time. |
None
|
Source code in ratelimit/ratelimit.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
peek(key)
¶
Return current quota state without consuming.
Note: initializes internal state for previously unseen keys (the bucket starts full, so the result is correct).
Source code in ratelimit/ratelimit.py
FixedWindowLimiter
¶
Bases: _AsyncMixin, _EvictionMixin
Fixed-window rate limiter.
Divides time into non-overlapping windows. Each key gets at most
limit requests per window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum requests per window. |
required |
window_seconds
|
float
|
Window duration in seconds. |
required |
clock
|
Callable[[], float] | None
|
Callable returning current monotonic time. |
None
|
Source code in ratelimit/ratelimit.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
SlidingWindowLimiter
¶
Bases: _AsyncMixin, _EvictionMixin
Sliding-window counter rate limiter.
Blends the previous window's count with the current window's count weighted by overlap fraction, eliminating boundary-burst artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum requests per window. |
required |
window_seconds
|
float
|
Window duration in seconds. |
required |
clock
|
Callable[[], float] | None
|
Callable returning current monotonic time. |
None
|
Source code in ratelimit/ratelimit.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 | |
GCRALimiter
¶
Bases: _AsyncMixin, _EvictionMixin
GCRA (Generic Cell Rate Algorithm) rate limiter.
Maintains a single TAT (Theoretical Arrival Time) per key. Mathematically equivalent to a leaky bucket but with simpler state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate
|
float
|
Requests allowed per second. |
required |
burst
|
int
|
Maximum burst size above the steady rate. |
0
|
clock
|
Callable[[], float] | None
|
Callable returning current monotonic time. |
None
|
Source code in ratelimit/ratelimit.py
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 | |
RateLimitExceeded
¶
Bases: Exception
Raised when a rate limit is exceeded in decorator/context-manager mode.
Source code in ratelimit/ratelimit.py
ratelimit
¶
Rate-limit decorator and context manager.
Can be used as a decorator::
@ratelimit("10/s")
def handle(): ...
Or as a sync/async context manager::
with ratelimit("5/m", key="user-1"):
do_work()
async with ratelimit("5/m", key="user-1"):
await do_work()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quota
|
str | None
|
Quota string (e.g. |
None
|
algorithm
|
str
|
Algorithm name (default: |
'token_bucket'
|
key
|
str
|
Rate-limit key (default: |
'__default__'
|
timeout
|
float | None
|
If set, wait up to timeout seconds for quota instead of raising immediately. |
None
|
limiter
|
RateLimiter | None
|
Pre-built limiter instance (overrides quota and algorithm). |
None
|
Source code in ratelimit/ratelimit.py
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 | |
ThreadSafeLimiter
¶
Wraps any :class:RateLimiter with per-key threading.Lock instances.
Different keys are fully concurrent; only requests to the same key
serialize. Uses threading.Lock (not asyncio.Lock) so the
wrapper is safe for mixed sync+async access. For pure-async
high-contention scenarios on a single key, the lock may briefly
block the event loop; in practice the hold time is negligible
(microseconds of in-memory computation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiter
|
RateLimiter
|
The underlying rate limiter. |
required |
Source code in ratelimit/ratelimit.py
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
limiter
property
¶
The wrapped rate limiter.
CompositeLimiter
¶
Bases: _AsyncMixin
Enforces multiple rate limiters, returning the strictest result.
Useful for multi-window rate limiting — for example, enforcing both
RPM (requests per minute) and RPD (requests per day) simultaneously.
All sub-limiters are checked on every call; if any denies, the
composite result is denied with the longest retry_after.
Note
A peek-then-acquire strategy is used: all sub-limiters are
peeked first, and tokens are only consumed when all would
allow. Under concurrent access without external locking
there is a small TOCTOU window between peek and acquire;
wrap with :class:ThreadSafeLimiter to eliminate it.
Thread safety
Wrap the composite itself for atomic multi-limiter checks::
ThreadSafeLimiter(CompositeLimiter([a, b]))
Composing individually-wrapped sub-limiters protects each sub-limiter but does not make the composite acquire sequence atomic — two threads can interleave across sub-limiters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiters
|
Sequence[RateLimiter]
|
One or more :class: |
required |
Source code in ratelimit/ratelimit.py
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 | |
parse_quota(quota)
¶
Parse a quota string like "100/s" or "10 per minute burst 20".
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with keys |
dict[str, Any]
|
and |
Source code in ratelimit/ratelimit.py
create_limiter(algorithm, quota, *, clock=None)
¶
Create a rate limiter from an algorithm name and quota string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
algorithm
|
str
|
One of |
required |
quota
|
str
|
Quota string like |
required |
clock
|
Callable[[], float] | None
|
Optional clock override for testing. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RateLimiter
|
class: |
How burst maps per algorithm:
- token_bucket:
burstsets bucket capacity directly (default:limit). - fixed_window / sliding_window:
burstis ignored. - gcra:
burstis total capacity, so internal burst parameter =burst - 1(extra slots above steady rate).
Note
The timeout parameter for wait-and-retry always uses
wall-clock time (time.monotonic), even when the limiter
has an injected clock.