{"id":32178241,"url":"https://github.com/vutran1710/pyratelimiter","last_synced_at":"2026-01-22T08:12:25.333Z","repository":{"id":36368961,"uuid":"223577988","full_name":"vutran1710/PyrateLimiter","owner":"vutran1710","description":"⚔️Python Rate-Limiter using Leaky-Bucket Algorithm Family","archived":false,"fork":false,"pushed_at":"2025-10-13T13:05:06.000Z","size":726,"stargazers_count":445,"open_issues_count":23,"forks_count":43,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-10-21T20:51:58.512Z","etag":null,"topics":["leaky-bucket","python","rate-limit","rate-limiter","rate-limiting","request-rate-limit"],"latest_commit_sha":null,"homepage":"https://pyratelimiter.readthedocs.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vutran1710.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2019-11-23T11:30:56.000Z","updated_at":"2025-10-21T13:57:57.000Z","dependencies_parsed_at":"2024-06-18T13:56:29.821Z","dependency_job_id":"af309b6d-592b-44a3-81df-70431b347890","html_url":"https://github.com/vutran1710/PyrateLimiter","commit_stats":{"total_commits":179,"total_committers":14,"mean_commits":"12.785714285714286","dds":0.3296089385474861,"last_synced_commit":"c4a56878e5e91775856ed3280edf04478bd276e8"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"purl":"pkg:github/vutran1710/PyrateLimiter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vutran1710%2FPyrateLimiter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vutran1710%2FPyrateLimiter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vutran1710%2FPyrateLimiter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vutran1710%2FPyrateLimiter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vutran1710","download_url":"https://codeload.github.com/vutran1710/PyrateLimiter/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vutran1710%2FPyrateLimiter/sbom","scorecard":{"id":1237438,"data":{"date":"2025-08-25","repo":{"name":"github.com/vutran1710/PyrateLimiter","commit":"5285d37e7ae6c52fc3b4bddfba399f535824da06"},"scorecard":{"version":"v5.2.1-41-g40576783","commit":"40576783fda6698350fcbbeaea760ff827433034"},"score":5.4,"checks":[{"name":"Maintained","score":10,"reason":"24 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#maintained"}},{"name":"Code-Review","score":8,"reason":"Found 22/25 approved changesets -- score normalized to 8","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#dangerous-workflow"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/build_test.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#token-permissions"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#cii-best-practices"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build_test.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build_test.yml:50: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/build_test.yml:55: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/build_test.yml:78: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build_test.yml:82: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build_test.yml:92: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/build_test.yml:97: update your workflow using https://app.stepsecurity.io/secureworkflow/vutran1710/PyrateLimiter/build_test.yml/master?enable=pin","Info:   0 out of   4 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   3 third-party GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#pinned-dependencies"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#vulnerabilities"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#security-policy"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":0,"reason":"Project has not signed or included provenance with any releases.","details":["Warn: release artifact v3.9.0 not signed: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/236306775","Warn: release artifact v3.8.1 not signed: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/234491979","Warn: release artifact v3.8.0 not signed: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/234483129","Warn: release artifact v3.7.0 not signed: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/169681585","Warn: release artifact v3.6.2 not signed: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/169636848","Warn: release artifact v3.9.0 does not have provenance: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/236306775","Warn: release artifact v3.8.1 does not have provenance: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/234491979","Warn: release artifact v3.8.0 does not have provenance: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/234483129","Warn: release artifact v3.7.0 does not have provenance: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/169681585","Warn: release artifact v3.6.2 does not have provenance: https://api.github.com/repos/vutran1710/PyrateLimiter/releases/169636848"],"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#branch-protection"}},{"name":"Packaging","score":10,"reason":"packaging workflow detected","details":["Info: Project packages its releases by way of GitHub Actions.: .github/workflows/build_test.yml:86"],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#packaging"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 30 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/40576783fda6698350fcbbeaea760ff827433034/docs/checks.md#sast"}}]},"last_synced_at":"2025-09-11T06:04:07.268Z","repository_id":36368961,"created_at":"2025-09-11T06:04:07.269Z","updated_at":"2025-09-11T06:04:07.269Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":280333492,"owners_count":26312845,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-21T02:00:06.614Z","response_time":58,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["leaky-bucket","python","rate-limit","rate-limiter","rate-limiting","request-rate-limit"],"created_at":"2025-10-21T20:52:05.232Z","updated_at":"2026-01-22T08:12:25.325Z","avatar_url":"https://github.com/vutran1710.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg align=\"left\" width=\"95\" height=\"120\" src=\"https://raw.githubusercontent.com/vutran1710/PyrateLimiter/master/docs/_static/logo.png\"\u003e\n\n# PyrateLimiter\n\nThe request rate limiter using Leaky-bucket Algorithm.\n\nFull project documentation can be found at [pyratelimiter.readthedocs.io](https://pyratelimiter.readthedocs.io).\n\n[![PyPI version](https://badge.fury.io/py/pyrate-limiter.svg)](https://badge.fury.io/py/pyrate-limiter)\n[![PyPI - Python Versions](https://img.shields.io/pypi/pyversions/pyrate-limiter)](https://pypi.org/project/pyrate-limiter)\n[![codecov](https://codecov.io/gh/vutran1710/PyrateLimiter/branch/master/graph/badge.svg?token=E0Q0YBSINS)](https://codecov.io/gh/vutran1710/PyrateLimiter)\n[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/vutran1710/PyrateLimiter/graphs/commit-activity)\n[![PyPI license](https://img.shields.io/pypi/l/ansicolortags.svg)](https://pypi.python.org/pypi/pyrate-limiter/)\n\n\u003e **Upgrading from v3.x?** See the [Migration Guide](docs/migrating.md) for breaking changes.\n\n\u003cbr\u003e\n\n## Contents\n\n  - [Features](#features)\n  - [Installation](#installation)\n  - [Web Requests](#web-request-rate-limiting)\n    - [AIOHTTP](#aiohttp)\n    - [HTTPX](#httpx)\n    - [Requests](#requests)\n  - [Quickstart](#quickstart)\n    - [limiter_factory](#limiter_factory)\n    - [Examples](#examples)\n  - [Basic usage](#basic-usage)\n    - [Key concepts](#key-concepts)\n    - [Defining rate limits \u0026 buckets](#defining-rate-limits-and-buckets)\n    - [Defining clock \u0026 routing logic](#defining-clock--routing-logic-with-bucketfactory)\n    - [Wrapping all up with Limiter](#wrapping-all-up-with-limiter)\n    - [asyncio and event loops](#asyncio-and-event-loops)\n    - [`as_decorator()`: use limiter as decorator](#as_decorator-use-limiter-as-decorator)\n    - [Limiter API](#limiter-api)\n      - [Context Manager](#context-manager)\n    - [Weight](#weight)\n    - [Handling exceeded limits](#handling-exceeded-limits)\n      - [Bucket analogy](#bucket-analogy)\n      - [Blocking vs Non-blocking](#blocking-vs-non-blocking)\n    - [Backends](#backends)\n      - [InMemoryBucket](#inmemorybucket)\n      - [MultiprocessBucket](#multiprocessbucket)\n      - [SQLiteBucket](#sqlitebucket)\n      - [RedisBucket](#redisbucket)\n      - [PostgresBucket](#postgresbucket)\n      - [BucketAsyncWrapper](#bucketasyncwrapper)\n    - [Async or Sync or Multiprocessing](#async-or-sync-or-multiprocessing)\n  - [Advanced Usage](#advanced-usage)\n    - [Component-level Diagram](#component-level-diagram)\n    - [Time sources](#time-sources)\n    - [Leaking](#leaking)\n    - [Concurrency](#concurrency)\n    - [Custom backend](#custom-backend)\n\n## Features\n\n- Supports unlimited rate limits and custom intervals.\n- Separately tracks limits for different services or resources.\n- Manages limit breaches with configurable blocking or non-blocking behavior.\n- Offers multiple usage modes: direct calls or decorators.\n- Fully compatible with both synchronous and asynchronous workflows.\n- Provides SQLite and Redis backends for persistent limit tracking across threads or restarts.\n- Includes MultiprocessBucket and SQLite File Lock backends for multiprocessing environments.\n\n## Installation\n\n**PyrateLimiter** supports **python ^3.8**\n\nInstall using pip:\n\n```\npip install pyrate-limiter\n```\n\nOr using conda:\n\n```\nconda install --channel conda-forge pyrate-limiter\n```\n\n## Quickstart\n\nTo limit 5 requests within 2 seconds:\n\n```python\nfrom pyrate_limiter import Duration, Rate, Limiter\n\nlimiter = Limiter(Rate(5, Duration.SECOND * 2))\n\n# Blocking mode (default) - waits until permit available\nfor i in range(6):\n    limiter.try_acquire(str(i))\n    print(f\"Acquired permit {i}\")\n\n# Non-blocking mode - returns False if bucket full\nfor i in range(6):\n    success = limiter.try_acquire(str(i), blocking=False)\n    if not success:\n        print(f\"Rate limited at {i}\")\n```\n\n## limiter_factory\n[limiter_factory.py](https://github.com/vutran1710/PyrateLimiter/blob/master/pyrate_limiter/limiter_factory.py) provides several functions to simplify common cases:\n- create_sqlite_limiter(rate_per_duration: int, duration: Duration, ...)\n- create_inmemory_limiter(rate_per_duration: int, duration: Duration, ...)\n- + more to be added...\n\n## Examples\n- Rate limiting asyncio tasks: [asyncio_ratelimit.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/asyncio_ratelimit.py)\n- Rate limiting asyncio tasks w/ a decorator: [asyncio_decorator.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/asyncio_decorator.py)\n- HTTPX rate limiting - asyncio, single process and multiprocess examples [httpx_ratelimiter.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/httpx_ratelimiter.py)\n- Multiprocessing using an in-memory rate limiter - [in_memory_multiprocess.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/in_memory_multiprocess.py)\n- Multiprocessing using SQLite and a file lock - this can be used for distributed processes not created within a multiprocessing [sql_filelock_multiprocess.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/sql_filelock_multiprocess.py)\n\n\n## Web Request Rate Limiting\n\npyrate_limiter provides three extras for popular web request libraries:\n- [AIOHTTP](https://pypi.org/project/aiohttp/)\n- [HTTPX](https://pypi.org/project/httpx/)\n- [Requests](https://pypi.org/project/requests/)\n\n### AIOHTTP\n```py\nfrom pyrate_limiter import limiter_factory\nfrom pyrate_limiter.extras.aiohttp_limiter import RateLimitedSession\n\nlimiter = limiter_factory.create_inmemory_limiter(rate_per_duration=2, duration=Duration.SECOND)\nsession = RateLimitedSession(limiter)\n\n```\n\nExample: [aiohttp_ratelimiter.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/aiohttp_ratelimiter.py)\n\n### HTTPX\n\n```py\nfrom pyrate_limiter import limiter_factory\nfrom pyrate_limiter.extras.httpx_limiter import AsyncRateLimiterTransport, RateLimiterTransport\nimport httpx\n\nlimiter = limiter_factory.create_inmemory_limiter(rate_per_duration=1, duration=Duration.SECOND, max_delay=Duration.HOUR)\nurl = \"https://example.com\"\n\nwith httpx.Client(transport=RateLimiterTransport(limiter=limiter)) as client:\n    client.get(url)\n\n# or async\nasync with httpx.AsyncClient(transport=AsyncRateLimiterTransport(limiter=limiter)) as client:\n    client.get(url)\n\n...\n```\nExample: [httpx_ratelimiter.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/httpx_ratelimiter.py)\n\n### Requests\n```py\nfrom pyrate_limiter import limiter_factory\nfrom pyrate_limiter.extras.requests_limiter import RateLimitedRequestsSession\n\nlimiter = limiter_factory.create_inmemory_limiter(rate_per_duration=2, duration=Duration.SECOND)\nsession = RateLimitedRequestsSession(limiter)\n....\n```\n\nExample: [requests_ratelimiter.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/requests_ratelimiter.py)\n\n\n\n## Basic Usage\n\n### Key concepts\n\n#### Clock\n\n- Timestamps incoming items\n\n#### Bucket\n\n- Stores items with timestamps.\n- Functions as a FIFO queue.\n- Can `leak` to remove outdated items.\n\n#### BucketFactory\n\n- Manages buckets and clocks, routing items to their appropriate buckets.\n- Schedules periodic `leak` operations to prevent overflow.\n- Allows custom logic for routing, conditions, and timing.\n\n#### Limiter\n\n- Provides a simple, intuitive API by abstracting underlying logic.\n- Seamlessly supports both sync and async contexts.\n- Offers multiple interaction modes: direct calls, decorators, and (future) context managers.\n- Ensures thread-safety via RLock, and if needed, asyncio concurrency via asyncio.Lock\n\n### Defining rate limits and buckets\n\nFor example, an API (like LinkedIn or GitHub) might have these rate limits:\n\n```\n- 500 requests per hour\n- 1000 requests per day\n- 10000 requests per month\n```\n\nYou can define these rates using the `Rate` class. `Rate` class has 2 properties only: **limit** and **interval**\n\n```python\nfrom pyrate_limiter import Duration, Rate\n\nhourly_rate = Rate(500, Duration.HOUR) # 500 requests per hour\ndaily_rate = Rate(1000, Duration.DAY) # 1000 requests per day\nmonthly_rate = Rate(10000, Duration.WEEK * 4) # 10000 requests per month\n\nrates = [hourly_rate, daily_rate, monthly_rate]\n```\n\nRates must be properly ordered:\n\n- Rates' intervals \u0026 limits must be ordered from least to greatest\n- Rates' ratio of **limit/interval** must be ordered from greatest to least\n\nBuckets validate rates during initialization. If using a custom implementation, use the built-in validator:\n\n```python\nfrom pyrate_limiter import validate_rate_list\n\nassert validate_rate_list(my_rates)\n```\n\nThen, add the rates to the bucket of your choices\n\n```python\nfrom pyrate_limiter import InMemoryBucket, RedisBucket\n\nbasic_bucket = InMemoryBucket(rates)\n\n# Or, using redis\nfrom redis import Redis\n\nredis_connection = Redis(host='localhost')\nredis_bucket = RedisBucket.init(rates, redis_connection, \"my-bucket-name\")\n\n# Async Redis would work too!\nfrom redis.asyncio import Redis\n\nredis_connection = Redis(host='localhost')\nredis_bucket = await RedisBucket.init(rates, redis_connection, \"my-bucket-name\")\n```\n\nIf you only need a single Bucket for everything, and python's built-in `time()` is enough for you, then pass the bucket to Limiter then ready to roll!\n\n```python\nfrom pyrate_limiter import Limiter\n\n# Limiter constructor accepts single bucket as the only parameter,\n# the rest are 3 optional parameters with default values as following\n# Limiter(bucket, clock=MonotonicClock(), raise_when_fail=True, max_delay=None)\nlimiter = Limiter(bucket)\n\n# Limiter is now ready to work!\nlimiter.try_acquire(\"hello world\")\n```\n\nIf you want to have finer grain control with routing \u0026 clocks etc, then you should use `BucketFactory`.\n\n### Defining Clock \u0026 routing logic with BucketFactory\n\nWhen multiple bucket types are needed and items must be routed based on certain conditions, use `BucketFactory`.\n\nFirst, define your clock (time source). Most use cases work with the built-in clocks:\n\n```python\nfrom pyrate_limiter.clock import MonotonicClock, SQLiteClock\n\nbase_clock = MonotonicClock()\n```\n\nPyrateLimiter does not assume routing logic, so you implement a custom BucketFactory. At a minimum, these two methods must be defined:\n\n```python\nfrom pyrate_limiter import BucketFactory\nfrom pyrate_limiter import AbstractBucket\n\n\nclass MyBucketFactory(BucketFactory):\n    # You can use constructor here,\n    # nor it requires to make bucket-factory work!\n\n    def wrap_item(self, name: str, weight: int = 1) -\u003e RateItem:\n        \"\"\"Time-stamping item, return a RateItem\"\"\"\n        now = clock.now()\n        return RateItem(name, now, weight=weight)\n\n    def get(self, _item: RateItem) -\u003e AbstractBucket:\n        \"\"\"For simplicity's sake, all items route to the same, single bucket\"\"\"\n        return bucket\n```\n\n### Creating buckets dynamically\n\nIf more than one bucket is needed, the bucket-routing logic should go to BucketFactory `get(..)` method.\n\nWhen creating buckets dynamically, it is needed to schedule leak for each newly created buckets.\n\nTo support this, BucketFactory comes with a predefined method call `self.create(..)`. It is meant to create the bucket and schedule that bucket for leaking using the Factory's clock\n\n```python\ndef create(\n        self,\n        clock: AbstractClock,\n        bucket_class: Type[AbstractBucket],\n        *args,\n        **kwargs,\n    ) -\u003e AbstractBucket:\n        \"\"\"Creating a bucket dynamically\"\"\"\n        bucket = bucket_class(*args, **kwargs)\n        self.schedule_leak(bucket, clock)\n        return bucket\n```\n\nBy utilizing this, we can modify the code as following:\n\n```python\nclass MultiBucketFactory(BucketFactory):\n    def __init__(self, clock):\n        self.clock = clock\n        self.buckets = {}\n\n    def wrap_item(self, name: str, weight: int = 1) -\u003e RateItem:\n        \"\"\"Time-stamping item, return a RateItem\"\"\"\n        now = clock.now()\n        return RateItem(name, now, weight=weight)\n\n    def get(self, item: RateItem) -\u003e AbstractBucket:\n        if item.name not in self.buckets:\n            # Use `self.create(..)` method to both initialize new bucket and calling `schedule_leak` on that bucket\n            # We can create different buckets with different types/classes here as well\n            new_bucket = self.create(YourBucketClass, *your-arguments, **your-keyword-arguments)\n            self.buckets.update({item.name: new_bucket})\n\n        return self.buckets[item.name]\n```\n\n### Wrapping all up with Limiter\n\nPass your bucket-factory to Limiter, and ready to roll!\n\n```python\nfrom pyrate_limiter import Limiter\n\nlimiter = Limiter(\n    bucket_factory,\n    raise_when_fail=False,  # Default = True\n    max_delay=1000,         # Default = None\n)\n\nitem = \"the-earth\"\nlimiter.try_acquire(item)\n\nheavy_item = \"the-sun\"\nlimiter.try_acquire(heavy_item, weight=10000)\n```\n\n### asyncio and event loops\n\nTo ensure the event loop isn't blocked, use `try_acquire_async` with an **async bucket**, which leverages `asyncio.Lock` for concurrency control.\n\nIf your bucket isn't async, wrap it with `BucketAsyncWrapper`. This ensures `asyncio.sleep` is used instead of `time.sleep`, preventing event loop blocking:\n\n\n```python\nawait limiter.try_acquire_async(item)\n```\n\nExample: [asyncio_ratelimit.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/asyncio_ratelimit.py)\n\n\n#### `as_decorator()`: use limiter as decorator\n\n`Limiter` can be used as a decorator with `name` and `weight` parameters.\nThe decorator works with both synchronous and asynchronous functions:\n\n```python\nfrom pyrate_limiter import Rate, Duration, Limiter\n\nlimiter = Limiter(Rate(5, Duration.SECOND))\n\n@limiter.as_decorator(name=\"api_call\", weight=1)\ndef handle_something(*args, **kwargs):\n    \"\"\"function logic\"\"\"\n\n@limiter.as_decorator(name=\"background_job\", weight=2)\nasync def handle_something_async(*args, **kwargs):\n    \"\"\"async function logic\"\"\"\n```\n\nFor full example see [asyncio_decorator.py](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/asyncio_decorator.py)\n\n\n### Limiter API\n\n#### `bucket()`: get list of all active buckets\nReturn list of all active buckets with `limiter.buckets()`\n\n\n#### `dispose(bucket: int | BucketObject)`: dispose/remove/delete the given bucket\n\nMethod signature:\n```python\ndef dispose(self, bucket: Union[int, AbstractBucket]) -\u003e bool:\n    \"\"\"Dispose/Remove a specific bucket,\n    using bucket-id or bucket object as param\n    \"\"\"\n```\n\nExample of usage:\n```python\nactive_buckets = limiter.buckets()\nassert len(active_buckets) \u003e 0\n\nbucket_to_remove = active_buckets[0]\nassert limiter.dispose(bucket_to_remove)\n```\n\nIf a bucket is found and get deleted, calling this method will return **True**, otherwise **False**.\nIf there is no more buckets in the limiter's bucket-factory, all the leaking tasks will be stopped.\n\n\n#### Context Manager\n\nLimiter supports the context manager protocol for automatic cleanup:\n\n```python\nfrom pyrate_limiter import Limiter, RequestRate, Duration, InMemoryBucket\n\n# Define a simple rate and create a bucket\nrate = RequestRate(5, Duration.SECOND)\nbucket = InMemoryBucket(rate)\n\n# Use Limiter as a context manager\nwith Limiter(bucket) as limiter:\n    limiter.try_acquire(\"item\")\n# Resources automatically released\n\n# Or manually close\nlimiter = Limiter(bucket)\ntry:\n    limiter.try_acquire(\"item\")\nfinally:\n    limiter.close()\n```\n\n\n### Weight\n\nItem can have weight. By default item's weight = 1, but you can modify the weight before passing to `limiter.try_acquire`.\n\nItem with weight W \u003e 1 when consumed will be multiplied to (W) items with the same timestamp and weight = 1. Example with a big item with weight W=5, when put to bucket, it will be divided to 5 items with weight=1 + following names\n\n```\nBigItem(weight=5, name=\"item\", timestamp=100) =\u003e [\n    item(weight=1, name=\"item\", timestamp=100),\n    item(weight=1, name=\"item\", timestamp=100),\n    item(weight=1, name=\"item\", timestamp=100),\n    item(weight=1, name=\"item\", timestamp=100),\n    item(weight=1, name=\"item\", timestamp=100),\n]\n```\n\nYet, putting this big, heavy item into bucket is expected to be transactional \u0026 atomic - meaning either all 5 items will be consumed or none of them will. This is made possible as bucket `put(item)` always check for available space before ingesting. All of the Bucket's implementations provided by **PyrateLimiter** follows this rule.\n\nAny additional, custom implementation of Bucket are expected to behave alike - as we have unit tests to cover the case.\n\nSee [Advanced Usage](#advanced-usage) below for more details.\n\n### Handling exceeded limits\n\nWhen a rate limit is exceeded, you can choose between blocking and non-blocking behavior.\n\n#### Bucket analogy\n\n\u003cimg height=\"300\" align=\"right\" src=\"https://upload.wikimedia.org/wikipedia/commons/c/c4/Leaky_bucket_analogy.JPG\"\u003e\n\nAt this point it's useful to introduce the analogy of \"buckets\" used for rate-limiting. Here is a\nquick summary:\n\n- This library implements the [Leaky Bucket algorithm](https://en.wikipedia.org/wiki/Leaky_bucket).\n- It is named after the idea of representing some kind of fixed capacity -- like a network or service -- as a bucket.\n- The bucket \"leaks\" at a constant rate. For web services, this represents the **ideal or permitted request rate**.\n- The bucket is \"filled\" at an intermittent, unpredicatble rate, representing the **actual rate of requests**.\n- When the bucket is \"full\", it will overflow, representing **canceled or delayed requests**.\n- Item can have weight. Consuming a single item with weight W \u003e 1 is the same as consuming W smaller, unit items - each with weight=1, with the same timestamp and maybe same name (depending on however user choose to implement it)\n\n#### Blocking vs Non-blocking\n\nBy default, `try_acquire` blocks until a permit becomes available:\n\n```python\nfrom pyrate_limiter import Rate, Limiter, Duration\n\nrate = Rate(3, Duration.SECOND)\nlimiter = Limiter(rate)\n\n# Blocking (default) - waits until permit is available\nfor i in range(5):\n    limiter.try_acquire(\"item\")  # blocks if bucket is full\n    print(f\"Acquired {i}\")\n```\n\nFor non-blocking behavior, set `blocking=False` to return immediately:\n\n```python\n# Non-blocking - returns False immediately if bucket is full\nfor i in range(5):\n    success = limiter.try_acquire(\"item\", blocking=False)\n    if not success:\n        print(f\"Rate limited at request {i}\")\n        break\n```\n\nFor async code, use `try_acquire_async` with optional timeout:\n\n```python\n# Async with timeout (in seconds)\nsuccess = await limiter.try_acquire_async(\"item\", timeout=5)\nif not success:\n    print(\"Timed out waiting for permit\")\n```\n\nThe `buffer_ms` parameter (default 50ms) adds a small delay buffer to account for timing variations:\n\n```python\nfrom pyrate_limiter import Duration, InMemoryBucket, Limiter, RequestRate\n\nrate = RequestRate(5, Duration.SECOND)\nbucket = InMemoryBucket(rate)\nlimiter = Limiter(bucket, buffer_ms=100)  # 100ms buffer\n```\n\n### Backends\n\nA few different bucket backends are available:\n\n- **InMemoryBucket**: using python built-in list as bucket\n- **MultiprocessBucket**:  uses a multiprocessing lock for distributed concurrency with a ListProxy as the bucket\n- **RedisBucket**, using err... redis, with both async/sync support\n- **PostgresBucket**, using `psycopg2`\n- **SQLiteBucket**, using sqlite3\n- **BucketAsyncWrapper**: wraps an existing bucket with async interfaces, to avoid blocking the event loop\n\n\n#### InMemoryBucket\n\nThe default bucket is stored in memory, using python `list`\n\n```python\nfrom pyrate_limiter import InMemoryBucket, Rate, Duration\n\nrates = [Rate(5, Duration.MINUTE * 2)]\nbucket = InMemoryBucket(rates)\n```\n\nThis bucket only availabe in `sync` mode. The only constructor argument is `List[Rate]`.\n\n#### MultiprocessBucket\n\nMultiprocessBucket uses a ListProxy to store items within a python multiprocessing pool or ProcessPoolExecutor. Concurrency is enforced via a multiprocessing Lock.\n\nThe bucket is shared across instances.\n\nAn example is provided in [in_memory_multiprocess](https://github.com/vutran1710/PyrateLimiter/blob/master/examples/in_memory_multiprocess.py)\n\nWhenever multiprocessing, bucket.waiting calculations will be often wrong because of the concurrency involved. Set Limiter.retry_until_max_delay=True so that the\nitem keeps retrying rather than returning False when contention causes an extra delay.\n\n#### RedisBucket\n\nRedisBucket uses `Sorted-Set` to store items with key being item's name and score item's timestamp\nBecause it is intended to work with both async \u0026 sync, we provide a classmethod `init` for it\n\n```python\nfrom pyrate_limiter import RedisBucket, Rate, Duration\n\n# Using synchronous redis\nfrom redis import ConnectionPool\nfrom redis import Redis\n\nrates = [Rate(5, Duration.MINUTE * 2)]\npool = ConnectionPool.from_url(\"redis://localhost:6379\")\nredis_db = Redis(connection_pool=pool)\nbucket_key = \"bucket-key\"\nbucket = RedisBucket.init(rates, redis_db, bucket_key)\n\n# Using asynchronous redis\nfrom redis.asyncio import ConnectionPool as AsyncConnectionPool\nfrom redis.asyncio import Redis as AsyncRedis\n\npool = AsyncConnectionPool.from_url(\"redis://localhost:6379\")\nredis_db = AsyncRedis(connection_pool=pool)\nbucket_key = \"bucket-key\"\nbucket = await RedisBucket.init(rates, redis_db, bucket_key)\n```\n\nThe API are the same, regardless of sync/async. If AsyncRedis is being used, calling `await bucket.method_name(args)` would just work!\n\n#### SQLiteBucket\n\nIf you need to persist the bucket state, a SQLite backend is available. The SQLite bucket works in sync manner.\n\nManully create a connection to Sqlite and pass it along with the table name to the bucket class:\n\n```python\nfrom pyrate_limiter import SQLiteBucket, Rate, Duration\nimport sqlite3\n\nrates = [Rate(5, Duration.MINUTE * 2)]\nbucket = SQLiteBucket.init_from_file(rates)\n```\n\n```py\nfrom pyrate_limiter import Rate, Limiter, Duration, SQLiteBucket\n\nrequests_per_minute = 5\nrate = Rate(requests_per_minute, Duration.MINUTE)\nbucket = SQLiteBucket.init_from_file([rate], use_file_lock=False)  # set use_file_lock to True if using across multiple processes\nlimiter = Limiter(bucket, raise_when_fail=False, max_delay=max_delay)\n```\n\nYou can also pass custom arguments to the `init_from_file` following its signature:\n\n```python\nclass SQLiteBucket(AbstractBucket):\n    @classmethod\n    def init_from_file(\n        cls,\n        rates: List[Rate],\n        table: str = \"rate_bucket\",\n        db_path: Optional[str] = None,\n        create_new_table = True,\n        use_file_lock: bool = False\n    ) -\u003e \"SQLiteBucket\":\n        ...\n```\n\nOptions:\n- `db_path`: If not provided, uses `tempdir / \"pyrate-limiter.sqlite\"`\n- `use_file_lock`: Should be False for single process workloads. For multi process, uses a [filelock](https://pypi.org/project/filelock/) to ensure single access to the SQLite bucket across multiple processes, allowing multi process rate limiting on a single host.\n\nExample: [limiter_factory.py::create_sqlite_limiter()](https://github.com/vutran1710/PyrateLimiter/blob/master/pyrate_limiter/limiter_factory.py)\n\n#### PostgresBucket\n\nPostgres is supported, but you have to install `psycopg[pool]` either as an extra or as a separate package. The PostgresBucket currently does not support async.\n\nYou can use Postgres's built-in **CURRENT_TIMESTAMP** as the time source with `PostgresClock`, or use an external custom time source.\n\n```python\nfrom pyrate_limiter import PostgresBucket, Rate, PostgresClock\nfrom psycopg_pool import ConnectionPool\n\nconnection_pool = ConnectionPool('postgresql://postgres:postgres@localhost:5432')\n\nclock = PostgresClock(connection_pool)\nrates = [Rate(3, 1000), Rate(4, 1500)]\nbucket = PostgresBucket(connection_pool, \"my-bucket-table\", rates)\n```\n\n#### BucketAsyncWrapper\nThe BucketAsyncWrapper wraps a sync bucket to ensure all its methods return awaitables. This allows the Limiter to detect\nasynchronous behavior and use asyncio.sleep() instead of time.sleep() during delay handling,\npreventing blocking of the asyncio event loop.\n\nExample: [limiter_factory.py::create_inmemory_limiter()](https://github.com/vutran1710/PyrateLimiter/blob/master/pyrate_limiter/limiter_factory.py)\n\n### Async or Sync or Multiprocessing\n\nThe Limiter is basically made of a Clock backend and a Bucket backend. The backends may be async or sync, which determines the Limiters internal behavior, regardless of whether the caller enters via a sync or async function.\n\ntry_acquire_async: When calling from an async context, use try_acquire_async. This uses a thread-local asyncio lock to ensure only one asyncio task is acquiring, followed by a global RLock so that only one thread is acquiring.\n\ntry_acquire: When called directly, the global RLock enforces only one thread at a time.\n\nMultiprocessing: If using MultiprocessBucket, two locks are used in Limiter: a top level multiprocessing lock, then a thread level RLock\n\n\n## Advanced Usage\n\n### Component level diagram\n\n![](https://raw.githubusercontent.com/vutran1710/PyrateLimiter/master/docs/_static/components.jpg)\n\n### Time sources\n\nTime source can be anything from anywhere: be it python's built-in time, or monotonic clock, sqliteclock, or crawling from world time server(well we don't have that, but you can!).\n\n```python\nfrom pyrate_limiter import MonotonicClock      # use python time.monotonic()\n```\n\nClock's abstract interface only requires implementing a method `now() -\u003e int`. And it can be both sync or async.\n\n### Leaking\n\nTypically bucket should not hold items forever. Bucket's abstract interface requires its implementation must be provided with `leak(current_timestamp: Optional[int] = None)`.\n\nThe `leak` method when called is expected to remove any items considered outdated at that moment. During Limiter lifetime, all the buckets' `leak` should be called periodically.\n\n**BucketFactory** provide a method called `schedule_leak` to help deal with this matter. Basically, it will run as a background task for all the buckets currently in use, with interval between `leak` call by **default is 10 seconds**.\n\n```python\n# Runnning a background task (whether it is sync/async - doesnt matter)\n# calling the bucket's leak\nfactory.schedule_leak(bucket, clock)\n```\n\nYou can change this calling interval by overriding BucketFactory's `leak_interval` property. This interval is in **miliseconds**.\n\n```python\nclass MyBucketFactory(BucketFactory):\n    def __init__(self, *args):\n        self.leak_interval = 300\n```\n\nWhen dealing with leak using BucketFactory, the author's suggestion is, we can be pythonic about this by implementing a constructor\n\n```python\nclass MyBucketFactory(BucketFactory):\n\n    def constructor(self, clock, buckets):\n        self.clock = clock\n        self.buckets = buckets\n\n        for bucket in buckets:\n            self.schedule_leak(bucket, clock)\n\n```\n\n### Concurrency\n\nGenerally, Lock is provided at Limiter's level, except SQLiteBucket case.\n\n### Custom backends\n\nIf these don't suit your needs, you can also create your own bucket backend by implementing `pyrate_limiter.AbstractBucket` class.\n\nOne of **PyrateLimiter** design goals is powerful extensibility and maximum ease of development.\n\nIt must be not only be a ready-to-use tool, but also a guide-line, or a framework that help implementing new features/bucket free of the most hassles.\n\nDue to the composition nature of the library, it is possbile to write minimum code and validate the result:\n\n- Fork the repo\n- Implement your bucket with `pyrate_limiter.AbstractBucket`\n- Add your own `create_bucket` method in `tests/conftest.py` and pass it to the `create_bucket` fixture\n- Run the test suite to validate the result\n\nIf the tests pass through, then you are just good to go with your new, fancy bucket!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvutran1710%2Fpyratelimiter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvutran1710%2Fpyratelimiter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvutran1710%2Fpyratelimiter/lists"}