limits


Namelimits JSON
Version 5.5.0 PyPI version JSON
download
home_pagehttps://limits.readthedocs.org
SummaryRate limiting utilities
upload_time2025-08-05 18:23:54
maintainerNone
docs_urlNone
authorAli-Akber Saifee
requires_python>=3.10
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            .. |ci| image:: https://github.com/alisaifee/limits/actions/workflows/main.yml/badge.svg?branch=master
    :target: https://github.com/alisaifee/limits/actions?query=branch%3Amaster+workflow%3ACI
.. |codecov| image:: https://codecov.io/gh/alisaifee/limits/branch/master/graph/badge.svg
   :target: https://codecov.io/gh/alisaifee/limits
.. |pypi| image:: https://img.shields.io/pypi/v/limits.svg?style=flat-square
    :target: https://pypi.python.org/pypi/limits
.. |pypi-versions| image:: https://img.shields.io/pypi/pyversions/limits?style=flat-square
    :target: https://pypi.python.org/pypi/limits
.. |license| image:: https://img.shields.io/pypi/l/limits.svg?style=flat-square
    :target: https://pypi.python.org/pypi/limits
.. |docs| image:: https://readthedocs.org/projects/limits/badge/?version=latest
   :target: https://limits.readthedocs.org

######
limits
######
|docs| |ci| |codecov| |pypi| |pypi-versions| |license|


**limits** is a python library for rate limiting via multiple strategies
with commonly used storage backends (Redis, Memcached & MongoDB).

The library provides identical APIs for use in sync and
`async <https://limits.readthedocs.io/en/stable/async.html>`_ codebases.


Supported Strategies
====================

All strategies support the follow methods:

- `hit <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.hit>`_: consume a request.
- `test <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.test>`_: check if a request is allowed.
- `get_window_stats <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.get_window_stats>`_: retrieve remaining quota and reset time.

Fixed Window
------------
`Fixed Window <https://limits.readthedocs.io/en/latest/strategies.html#fixed-window>`_

This strategy is the most memory‑efficient because it uses a single counter per resource and
rate limit. When the first request arrives, a window is started for a fixed duration
(e.g., for a rate limit of 10 requests per minute the window expires in 60 seconds from the first request).
All requests in that window increment the counter and when the window expires, the counter resets.

Burst traffic that bypasses the rate limit may occur at window boundaries.

For example, with a rate limit of 10 requests per minute:

- At **00:00:45**, the first request arrives, starting a window from **00:00:45** to **00:01:45**.
- All requests between **00:00:45** and **00:01:45** count toward the limit.
- If 10 requests occur at any time in that window, any further request before **00:01:45** is rejected.
- At **00:01:45**, the counter resets and a new window starts which would allow 10 requests
  until **00:02:45**.

Moving Window
-------------
`Moving Window <https://limits.readthedocs.io/en/latest/strategies.html#moving-window>`_

This strategy adds each request’s timestamp to a log if the ``nth`` oldest entry (where ``n``
is the limit) is either not present or is older than the duration of the window (for example with a rate limit of
``10 requests per minute`` if there are either less than 10 entries or the 10th oldest entry is at least
60 seconds old). Upon adding a new entry to the log "expired" entries are truncated.

For example, with a rate limit of 10 requests per minute:

- At **00:00:10**, a client sends 1 requests which are allowed.
- At **00:00:20**, a client sends 2 requests which are allowed.
- At **00:00:30**, the client sends 4 requests which are allowed.
- At **00:00:50**, the client sends 3 requests which are allowed (total = 10).
- At **00:01:11**, the client sends 1 request. The strategy checks the timestamp of the
  10th oldest entry (**00:00:10**) which is now 61 seconds old and thus expired. The request
  is allowed.
- At **00:01:12**, the client sends 1 request. The 10th oldest entry's timestamp is **00:00:20**
  which is only 52 seconds old. The request is rejected.

Sliding Window Counter
------------------------
`Sliding Window Counter <https://limits.readthedocs.io/en/latest/strategies.html#sliding-window-counter>`_

This strategy approximates the moving window while using less memory by maintaining
two counters:

- **Current bucket:** counts requests in the ongoing period.
- **Previous bucket:** counts requests in the immediately preceding period.

When a request arrives, the effective request count is calculated as::

    weighted_count = current_count + floor(previous_count * weight)

The weight is based on how much time has elapsed in the current bucket::

    weight = (bucket_duration - elapsed_time) / bucket_duration

If ``weighted_count`` is below the limit, the request is allowed.

For example, with a rate limit of 10 requests per minute:

Assume:

- The current bucket (spanning **00:01:00** to **00:02:00**) has 8 hits.
- The previous bucket (spanning **00:00:00** to **00:01:00**) has 4 hits.

Scenario 1:

- A new request arrives at **00:01:30**, 30 seconds into the current bucket.
- ``weight = (60 - 30) / 60 = 0.5``.
- ``weighted_count = floor(8 + (4 * 0.5)) = floor(8 + 2) = 10``.
- Since the weighted count equals the limit, the request is rejected.

Scenario 2:

- A new request arrives at **00:01:40**, 40 seconds into the current bucket.
- ``weight = (60 - 40) / 60 ≈ 0.33``.
- ``weighted_count = floor(8 + (4 * 0.33)) = floor(8 + 1.32) = 9``.
- Since the weighted count is below the limit, the request is allowed.


Storage backends
================

- `Redis <https://limits.readthedocs.io/en/latest/storage.html#redis-storage>`_
- `Memcached <https://limits.readthedocs.io/en/latest/storage.html#memcached-storage>`_
- `MongoDB <https://limits.readthedocs.io/en/latest/storage.html#mongodb-storage>`_
- `In-Memory <https://limits.readthedocs.io/en/latest/storage.html#in-memory-storage>`_

Dive right in
=============

Initialize the storage backend

.. code-block:: python

   from limits import storage
   backend = storage.MemoryStorage()
   # or memcached
   backend = storage.MemcachedStorage("memcached://localhost:11211")
   # or redis
   backend = storage.RedisStorage("redis://localhost:6379")
   # or mongodb
   backend = storage.MongoDbStorage("mongodb://localhost:27017")
   # or use the factory
   storage_uri = "memcached://localhost:11211"
   backend = storage.storage_from_string(storage_uri)

Initialize a rate limiter with a strategy

.. code-block:: python

   from limits import strategies
   strategy = strategies.MovingWindowRateLimiter(backend)
   # or fixed window
   strategy = strategies.FixedWindowRateLimiter(backend)
   # or sliding window
   strategy = strategies.SlidingWindowCounterRateLimiter(backend)


Initialize a rate limit

.. code-block:: python

    from limits import parse
    one_per_minute = parse("1/minute")

Initialize a rate limit explicitly

.. code-block:: python

    from limits import RateLimitItemPerSecond
    one_per_second = RateLimitItemPerSecond(1, 1)

Test the limits

.. code-block:: python

    import time
    assert True == strategy.hit(one_per_minute, "test_namespace", "foo")
    assert False == strategy.hit(one_per_minute, "test_namespace", "foo")
    assert True == strategy.hit(one_per_minute, "test_namespace", "bar")

    assert True == strategy.hit(one_per_second, "test_namespace", "foo")
    assert False == strategy.hit(one_per_second, "test_namespace", "foo")
    time.sleep(1)
    assert True == strategy.hit(one_per_second, "test_namespace", "foo")

Check specific limits without hitting them

.. code-block:: python

    assert True == strategy.hit(one_per_second, "test_namespace", "foo")
    while not strategy.test(one_per_second, "test_namespace", "foo"):
        time.sleep(0.01)
    assert True == strategy.hit(one_per_second, "test_namespace", "foo")

Query available capacity and reset time for a limit

.. code-block:: python

   assert True == strategy.hit(one_per_minute, "test_namespace", "foo")
   window = strategy.get_window_stats(one_per_minute, "test_namespace", "foo")
   assert window.remaining == 0
   assert False == strategy.hit(one_per_minute, "test_namespace", "foo")
   time.sleep(window.reset_time - time.time())
   assert True == strategy.hit(one_per_minute, "test_namespace", "foo")


Links
=====

* `Documentation <http://limits.readthedocs.org/en/latest>`_
* `Benchmarks <http://limits.readthedocs.org/en/latest/performance.html>`_
* `Changelog <http://limits.readthedocs.org/en/stable/changelog.html>`_


            

Raw data

            {
    "_id": null,
    "home_page": "https://limits.readthedocs.org",
    "name": "limits",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": "Ali-Akber Saifee",
    "author_email": "ali@indydevs.org",
    "download_url": "https://files.pythonhosted.org/packages/76/17/7a2e9378c8b8bd4efe3573fd18d2793ad2a37051af5ccce94550a4e5d62d/limits-5.5.0.tar.gz",
    "platform": null,
    "description": ".. |ci| image:: https://github.com/alisaifee/limits/actions/workflows/main.yml/badge.svg?branch=master\n    :target: https://github.com/alisaifee/limits/actions?query=branch%3Amaster+workflow%3ACI\n.. |codecov| image:: https://codecov.io/gh/alisaifee/limits/branch/master/graph/badge.svg\n   :target: https://codecov.io/gh/alisaifee/limits\n.. |pypi| image:: https://img.shields.io/pypi/v/limits.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/limits\n.. |pypi-versions| image:: https://img.shields.io/pypi/pyversions/limits?style=flat-square\n    :target: https://pypi.python.org/pypi/limits\n.. |license| image:: https://img.shields.io/pypi/l/limits.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/limits\n.. |docs| image:: https://readthedocs.org/projects/limits/badge/?version=latest\n   :target: https://limits.readthedocs.org\n\n######\nlimits\n######\n|docs| |ci| |codecov| |pypi| |pypi-versions| |license|\n\n\n**limits** is a python library for rate limiting via multiple strategies\nwith commonly used storage backends (Redis, Memcached & MongoDB).\n\nThe library provides identical APIs for use in sync and\n`async <https://limits.readthedocs.io/en/stable/async.html>`_ codebases.\n\n\nSupported Strategies\n====================\n\nAll strategies support the follow methods:\n\n- `hit <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.hit>`_: consume a request.\n- `test <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.test>`_: check if a request is allowed.\n- `get_window_stats <https://limits.readthedocs.io/en/stable/api.html#limits.strategies.RateLimiter.get_window_stats>`_: retrieve remaining quota and reset time.\n\nFixed Window\n------------\n`Fixed Window <https://limits.readthedocs.io/en/latest/strategies.html#fixed-window>`_\n\nThis strategy is the most memory\u2011efficient because it uses a single counter per resource and\nrate limit. When the first request arrives, a window is started for a fixed duration\n(e.g., for a rate limit of 10 requests per minute the window expires in 60 seconds from the first request).\nAll requests in that window increment the counter and when the window expires, the counter resets.\n\nBurst traffic that bypasses the rate limit may occur at window boundaries.\n\nFor example, with a rate limit of 10 requests per minute:\n\n- At **00:00:45**, the first request arrives, starting a window from **00:00:45** to **00:01:45**.\n- All requests between **00:00:45** and **00:01:45** count toward the limit.\n- If 10 requests occur at any time in that window, any further request before **00:01:45** is rejected.\n- At **00:01:45**, the counter resets and a new window starts which would allow 10 requests\n  until **00:02:45**.\n\nMoving Window\n-------------\n`Moving Window <https://limits.readthedocs.io/en/latest/strategies.html#moving-window>`_\n\nThis strategy adds each request\u2019s timestamp to a log if the ``nth`` oldest entry (where ``n``\nis the limit) is either not present or is older than the duration of the window (for example with a rate limit of\n``10 requests per minute`` if there are either less than 10 entries or the 10th oldest entry is at least\n60 seconds old). Upon adding a new entry to the log \"expired\" entries are truncated.\n\nFor example, with a rate limit of 10 requests per minute:\n\n- At **00:00:10**, a client sends 1 requests which are allowed.\n- At **00:00:20**, a client sends 2 requests which are allowed.\n- At **00:00:30**, the client sends 4 requests which are allowed.\n- At **00:00:50**, the client sends 3 requests which are allowed (total = 10).\n- At **00:01:11**, the client sends 1 request. The strategy checks the timestamp of the\n  10th oldest entry (**00:00:10**) which is now 61 seconds old and thus expired. The request\n  is allowed.\n- At **00:01:12**, the client sends 1 request. The 10th oldest entry's timestamp is **00:00:20**\n  which is only 52 seconds old. The request is rejected.\n\nSliding Window Counter\n------------------------\n`Sliding Window Counter <https://limits.readthedocs.io/en/latest/strategies.html#sliding-window-counter>`_\n\nThis strategy approximates the moving window while using less memory by maintaining\ntwo counters:\n\n- **Current bucket:** counts requests in the ongoing period.\n- **Previous bucket:** counts requests in the immediately preceding period.\n\nWhen a request arrives, the effective request count is calculated as::\n\n    weighted_count = current_count + floor(previous_count * weight)\n\nThe weight is based on how much time has elapsed in the current bucket::\n\n    weight = (bucket_duration - elapsed_time) / bucket_duration\n\nIf ``weighted_count`` is below the limit, the request is allowed.\n\nFor example, with a rate limit of 10 requests per minute:\n\nAssume:\n\n- The current bucket (spanning **00:01:00** to **00:02:00**) has 8 hits.\n- The previous bucket (spanning **00:00:00** to **00:01:00**) has 4 hits.\n\nScenario 1:\n\n- A new request arrives at **00:01:30**, 30 seconds into the current bucket.\n- ``weight = (60 - 30) / 60 = 0.5``.\n- ``weighted_count = floor(8 + (4 * 0.5)) = floor(8 + 2) = 10``.\n- Since the weighted count equals the limit, the request is rejected.\n\nScenario 2:\n\n- A new request arrives at **00:01:40**, 40 seconds into the current bucket.\n- ``weight = (60 - 40) / 60 \u2248 0.33``.\n- ``weighted_count = floor(8 + (4 * 0.33)) = floor(8 + 1.32) = 9``.\n- Since the weighted count is below the limit, the request is allowed.\n\n\nStorage backends\n================\n\n- `Redis <https://limits.readthedocs.io/en/latest/storage.html#redis-storage>`_\n- `Memcached <https://limits.readthedocs.io/en/latest/storage.html#memcached-storage>`_\n- `MongoDB <https://limits.readthedocs.io/en/latest/storage.html#mongodb-storage>`_\n- `In-Memory <https://limits.readthedocs.io/en/latest/storage.html#in-memory-storage>`_\n\nDive right in\n=============\n\nInitialize the storage backend\n\n.. code-block:: python\n\n   from limits import storage\n   backend = storage.MemoryStorage()\n   # or memcached\n   backend = storage.MemcachedStorage(\"memcached://localhost:11211\")\n   # or redis\n   backend = storage.RedisStorage(\"redis://localhost:6379\")\n   # or mongodb\n   backend = storage.MongoDbStorage(\"mongodb://localhost:27017\")\n   # or use the factory\n   storage_uri = \"memcached://localhost:11211\"\n   backend = storage.storage_from_string(storage_uri)\n\nInitialize a rate limiter with a strategy\n\n.. code-block:: python\n\n   from limits import strategies\n   strategy = strategies.MovingWindowRateLimiter(backend)\n   # or fixed window\n   strategy = strategies.FixedWindowRateLimiter(backend)\n   # or sliding window\n   strategy = strategies.SlidingWindowCounterRateLimiter(backend)\n\n\nInitialize a rate limit\n\n.. code-block:: python\n\n    from limits import parse\n    one_per_minute = parse(\"1/minute\")\n\nInitialize a rate limit explicitly\n\n.. code-block:: python\n\n    from limits import RateLimitItemPerSecond\n    one_per_second = RateLimitItemPerSecond(1, 1)\n\nTest the limits\n\n.. code-block:: python\n\n    import time\n    assert True == strategy.hit(one_per_minute, \"test_namespace\", \"foo\")\n    assert False == strategy.hit(one_per_minute, \"test_namespace\", \"foo\")\n    assert True == strategy.hit(one_per_minute, \"test_namespace\", \"bar\")\n\n    assert True == strategy.hit(one_per_second, \"test_namespace\", \"foo\")\n    assert False == strategy.hit(one_per_second, \"test_namespace\", \"foo\")\n    time.sleep(1)\n    assert True == strategy.hit(one_per_second, \"test_namespace\", \"foo\")\n\nCheck specific limits without hitting them\n\n.. code-block:: python\n\n    assert True == strategy.hit(one_per_second, \"test_namespace\", \"foo\")\n    while not strategy.test(one_per_second, \"test_namespace\", \"foo\"):\n        time.sleep(0.01)\n    assert True == strategy.hit(one_per_second, \"test_namespace\", \"foo\")\n\nQuery available capacity and reset time for a limit\n\n.. code-block:: python\n\n   assert True == strategy.hit(one_per_minute, \"test_namespace\", \"foo\")\n   window = strategy.get_window_stats(one_per_minute, \"test_namespace\", \"foo\")\n   assert window.remaining == 0\n   assert False == strategy.hit(one_per_minute, \"test_namespace\", \"foo\")\n   time.sleep(window.reset_time - time.time())\n   assert True == strategy.hit(one_per_minute, \"test_namespace\", \"foo\")\n\n\nLinks\n=====\n\n* `Documentation <http://limits.readthedocs.org/en/latest>`_\n* `Benchmarks <http://limits.readthedocs.org/en/latest/performance.html>`_\n* `Changelog <http://limits.readthedocs.org/en/stable/changelog.html>`_\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Rate limiting utilities",
    "version": "5.5.0",
    "project_urls": {
        "Homepage": "https://limits.readthedocs.org",
        "Source": "https://github.com/alisaifee/limits"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "bf68ee314018c28da75ece5a639898b4745bd0687c0487fc465811f0c4b9cd44",
                "md5": "c5f384fb205d9100f16987c9e3883934",
                "sha256": "57217d01ffa5114f7e233d1f5e5bdc6fe60c9b24ade387bf4d5e83c5cf929bae"
            },
            "downloads": -1,
            "filename": "limits-5.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c5f384fb205d9100f16987c9e3883934",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 60948,
            "upload_time": "2025-08-05T18:23:53",
            "upload_time_iso_8601": "2025-08-05T18:23:53.335145Z",
            "url": "https://files.pythonhosted.org/packages/bf/68/ee314018c28da75ece5a639898b4745bd0687c0487fc465811f0c4b9cd44/limits-5.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "76177a2e9378c8b8bd4efe3573fd18d2793ad2a37051af5ccce94550a4e5d62d",
                "md5": "96ece35d80cb486b2ae25daee7fa42d6",
                "sha256": "ee269fedb078a904608b264424d9ef4ab10555acc8d090b6fc1db70e913327ea"
            },
            "downloads": -1,
            "filename": "limits-5.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "96ece35d80cb486b2ae25daee7fa42d6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 95514,
            "upload_time": "2025-08-05T18:23:54",
            "upload_time_iso_8601": "2025-08-05T18:23:54.771781Z",
            "url": "https://files.pythonhosted.org/packages/76/17/7a2e9378c8b8bd4efe3573fd18d2793ad2a37051af5ccce94550a4e5d62d/limits-5.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-05 18:23:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alisaifee",
    "github_project": "limits",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "limits"
}
        
Elapsed time: 1.58484s