backoff-headers
backoff-headers

how backoff-headers fits in

Install

consolepip install backoff-headers

API

pythonfrom backoff_headers import (
    format_retry_after, parse_rate_limit, parse_retry_after, wait_time,
)

parse_retry_after("120")                            # 120.0
parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT")  # seconds until then, 0.0 if past

limit = parse_rate_limit(response.headers)
limit.limit, limit.remaining, limit.window, limit.policy
limit.exhausted                  # remaining == 0
limit.seconds_until_reset()

wait_time(headers, cap=60, jitter=2.0)   # never longer than 60s, spread by up to 2s
format_retry_after(1.2)                  # "2", rounded up so you never retry early

reset_style on parse_rate_limit is "auto" (an implausibly large reset is treated as a timestamp), "delta" or "epoch" when you know what your server sends. now is accepted everywhere a clock is needed, which is what makes the behaviour testable.

Both header families are read case-insensitively, and RFC 9331 wins when a server sends both.

Design notes

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.