Skip to main content

Leak Snek Rate Limiting

leak snek logo coverage

Leak Snek is a Python library that provides a flexible and extensible implementation of rate limiting for your applications

Table of Contents

Features

  • Asynchronous and Synchronous Support: The library provides support for both asynchronous and synchronous rate.
  • Flexible Rate Limiting Algorithms: Define your custom rate limiting algorithms by implementing the RateLimiter and AsyncRateLimiter interfaces.
  • Rate Storage: Manage rate information with the RateStorage and AsyncRateStorage interfaces.
  • Leaky Bucket Algorithm: Included implementations of the Leaky Bucket Algorithm for both asynchronous and synchronous use cases.

Getting Started

  1. Installation:

    Install Leak Snek using pip:

    pip install leak_snek
    
  2. Usage:

    You can use the provided classes and interfaces to implement rate limiting in your Python applications. Additionally, if you need the Leaky Bucket Algorithm, you can use the provided implementations.

    • Synchronous Leaky Bucket Algorithm:

      from threading import Lock
      
      from leak_snek.limiters.leaky_bucket import LeakyBucketLimiter
      from leak_snek.mutexes.memory_mutex import MemoryMutex
      from leak_snek.shortcuts.rate_limit import rl
      from leak_snek.storages.memory_storage import MemoryStorage
      
      limiter = LeakyBucketLimiter[str](
          rate_limit=rl("10/m"),
          rate_storage=MemoryStorage(),
          key_mutex=MemoryMutex(
              local_lock=Lock(),
              lock_factory=lambda: Lock(),
          ),
      )
      
      if not limiter.limit_exceeded("my_key"):
          ... # Perform the operation
      
    • Asynchronous Leaky Bucket Algorithm:

      from collections.abc import AsyncGenerator, Awaitable
      from contextlib import asynccontextmanager
      from typing import Any, Self, cast, override
      
      from redis.asyncio import Redis
      
      from leak_snek.interfaces.mutexes.aio.mutex import AsyncMutex
      from leak_snek.interfaces.storages.aio.rate_store import AsyncRateStorage
      from leak_snek.interfaces.values.rate import Rate
      from leak_snek.limiters.aio.leaky_bucket import AsyncLeakyBucketLimiter
      from leak_snek.shortcuts.rate_limit import rl
      
      
      @dataclasses.dataclass
      class RedisAsyncRateStorage(AsyncRateStorage[str]):
          redis: Redis
      
          async def read(self: Self, key: str) -> Rate:
              if not await self.redis.exists(key):
                  return Rate.default()
      
              rate_dict = await cast(Awaitable[dict[Any, Any]], self.redis.hgetall(name=key))
      
              return Rate(operations=int(rate_dict[b"operations"]), updated_at=float(rate_dict[b"updated_at"]))
      
          async def write(self: Self, key: str, value: Rate) -> None:
              await cast(
                  Awaitable[int],
                  self.redis.hset(name=key, mapping={"operations": value.operations, "updated_at": value.updated_at}),
              )
      
      
      @dataclasses.dataclass
      class RedisAsyncMutex(AsyncMutex[str]):
          redis: Redis
      
          @override
          @asynccontextmanager
          async def lock(self: Self, key: str) -> AsyncGenerator[None, None]:
              async with self.redis.lock(f"{key}_lock"):
                  yield
      
      
      async def main() -> None:
          async_limiter = AsyncLeakyBucketLimiter(
              rate_limit=rl("10/m"),
              rate_storage=RedisAsyncRateStorage(redis=Redis()),
              key_mutex=RedisAsyncMutex(redis=Redis()),
          )
      
          if not await async_limiter.limit_exceeded("my_key"):
              ...  # Perform the operation
           ```
      

In asynchronous example we implement our own async storage & mutex b/c leak_snek doesn't provide redis integration and it doesn't make much of a sense to implement asynchronous in-memory store.

License

Leak Snek Rate Limiting is released under the MIT License. See the LICENSE file for details.


Metadata

Release files for leak-snek 0.3.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for leak-snek 0.3.2
File Size Uploaded
leak_snek-0.3.2.tar.gz 12.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for leak-snek 0.3.2
File Interpreter ABI Platform
leak_snek-0.3.2-py3-none-any.whl Python 3 none any Details

Total release size: 32.2 kB

Release files / leak_snek-0.3.2.tar.gz

Download URL leak_snek-0.3.2.tar.gz
Size 12.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6b4562b4b49dc757f88330cccb317d9206e6f92ade6e5c2bf1ab7af1cf5906ff
BLAKE2b-256 checksum
How to use checksums
e6d406fc71629d823d0fceb52d10e94ee6e8f70cf85499ba698fb70c9902ff14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.6.1 CPython/3.11.5 Linux/6.5.7-arch1-1

Release files / leak_snek-0.3.2-py3-none-any.whl

Download URL leak_snek-0.3.2-py3-none-any.whl
Size 20.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f34ca3a35231dfe8cd50b51843de99f53e4a284cd4b606cd9fa33d5fc6a5f238
BLAKE2b-256 checksum
How to use checksums
b26dd6e6a0a94a687cdb8c223383763849838dcb97c693dc29a6889e180ad828
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.6.1 CPython/3.11.5 Linux/6.5.7-arch1-1

Release history Release notifications | RSS feed

This release

0.3.2 This release

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page