blockguard
A circuit breaker for rate limits the other server imposes on you — not a client-side throttle for your own call rate.
The problem
Libraries like ratelimit or django-ratelimit cap how fast you call
out ("no more than 10 requests/second"). That's a different problem from
what this solves: a remote server — often one with an undocumented,
time-varying, IP-scoped rate limit (scraping targets, flaky
third-party APIs, anything without a published SLA) — has already told
you "no" with a 429 or a silent block, and now every retry you make
while it's still blocking you risks extending the block instead of
clearing it.
This happened for real, repeatedly, building a tool against the Steam
Community Market: a single user action could fire dozens of requests at
an already-flagged endpoint, turning a minutes-long block into one that
lasted hours. blockguard is the fix that came out of that, generalized.
Install
pip install blockguard
Usage
from blockguard import CircuitBreaker
breaker = CircuitBreaker(base_cooldown_s=60.0, max_cooldown_s=1800.0)
if breaker.in_cooldown("some_api"):
return cached_result # don't even try -- we already know it'll fail
resp = call_flaky_api()
if resp.status_code == 429:
breaker.trip("some_api") # next cooldown doubles: 60s, 120s, 240s, ... capped
else:
breaker.clear("some_api") # back to a clean slate after a real success
Or with the context-manager shortcut, which raises instead of letting you forget the check:
from blockguard import CircuitBreaker, InCooldownError
breaker = CircuitBreaker()
try:
with breaker.guard("some_api"):
resp = call_flaky_api()
except InCooldownError as e:
print(f"skipping call, {e.seconds_remaining:.0f}s left")
Keys ("families") are independent: tripping "inventory" never affects
"search". Use one key per logical endpoint/rate-limit budget, not one
global key for your whole app.
Using it inside an AI agent's tools
Agents retry. When a tool call fails, the model tends to call the same tool again, several times in a row and faster than a person would. If the API behind the tool is already rate-limiting you, every retry can extend the block. Check the breaker inside the tool and give the model a plain answer instead of sending the request:
from blockguard import CircuitBreaker
breaker = CircuitBreaker()
def get_price(item: str) -> str:
"""Tool exposed to the agent. Never raises; always returns text."""
if breaker.in_cooldown("prices_api"):
wait = breaker.seconds_remaining("prices_api")
return f"Rate limited. Don't call get_price again for {wait:.0f}s."
resp = call_prices_api(item)
if resp.status_code == 429:
breaker.trip("prices_api")
return "The prices API returned 429. Don't retry yet."
breaker.clear("prices_api")
return resp.text
The message helps a model that reads it, and the check protects you from one that doesn't: no request reaches the API until the cooldown ends, however many times the agent calls the tool. Since the tool is a plain function that returns text, it fits frameworks that expose Python functions as tools.
examples/agent_tool_demo.py runs this against a local toy server with a
fake agent loop that retries every failure three times. No LLM or API key is
needed. In that run, the agent makes 12 tool calls and 4 reach the API.
Testing with blockguard in your own test suite
A breaker that lives at module/app scope persists across your whole test
session by default — a test that simulates a real block leaves a real
cooldown that leaks into the next test. blockguard ships a pytest
plugin that fixes this automatically once installed:
from blockguard import CircuitBreaker
from blockguard.pytest_plugin import track
breaker = track(CircuitBreaker()) # now reset between every test, automatically
What this is not (yet)
v0.1 is deliberately small: an in-memory, single-process breaker, no async API, no hosted dashboard, no Redis backend for multi-process sharing. If you need any of that, open an issue — it'll ship if there's real demand, not before.
License
MIT
Metadata
Release files for blockguard 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| blockguard-0.1.2.tar.gz | 8.7 kB | Without provenance | Details for blockguard-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| blockguard-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for blockguard-0.1.2-py3-none-any.whl |
Total release size: 16.4 kB
Release files / blockguard-0.1.2.tar.gz
| Download URL | blockguard-0.1.2.tar.gz |
|---|---|
| Size | 8.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
42dfea1bb67b55aea7ee6580c43e276d93f9ce7341b01753ecec9778500faca9
|
|
BLAKE2b-256 checksum How to use checksums |
b88222fb1ef0c3384c97f179abe454f6b4f968d858b9e5cda7e7b23d31ac6a81
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.13
|
Release files / blockguard-0.1.2-py3-none-any.whl
| Download URL | blockguard-0.1.2-py3-none-any.whl |
|---|---|
| Size | 7.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
02a9dd27b66c9582f123264d6175f597f00be7955fa0e638880b404a85fec73f
|
|
BLAKE2b-256 checksum How to use checksums |
808ab636142bf802ed286c967d1ab839873b112734151797b33c947ac751424d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.13
|
Security for blockguard 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.