fastapi-sql-limiter 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_sql_limiter-0.3.0/CHANGELOG.md +81 -0
- fastapi_sql_limiter-0.3.0/CONTRIBUTING.md +44 -0
- fastapi_sql_limiter-0.3.0/LICENSE +21 -0
- fastapi_sql_limiter-0.3.0/MANIFEST.in +9 -0
- fastapi_sql_limiter-0.3.0/PKG-INFO +300 -0
- fastapi_sql_limiter-0.3.0/README.md +257 -0
- fastapi_sql_limiter-0.3.0/SECURITY.md +36 -0
- fastapi_sql_limiter-0.3.0/benchmarks/postgres_benchmark.py +257 -0
- fastapi_sql_limiter-0.3.0/benchmarks/python_benchmark.py +76 -0
- fastapi_sql_limiter-0.3.0/docs/architecture.md +77 -0
- fastapi_sql_limiter-0.3.0/docs/benchmark-results/postgresql-18.4-windows-python-3.12.md +49 -0
- fastapi_sql_limiter-0.3.0/docs/benchmarks.md +41 -0
- fastapi_sql_limiter-0.3.0/docs/deployment.md +118 -0
- fastapi_sql_limiter-0.3.0/docs/release-notes/v0.3.0.md +39 -0
- fastapi_sql_limiter-0.3.0/docs/releasing.md +43 -0
- fastapi_sql_limiter-0.3.0/examples/authenticated_identity.py +59 -0
- fastapi_sql_limiter-0.3.0/examples/basic_app.py +36 -0
- fastapi_sql_limiter-0.3.0/examples/existing_pool.py +29 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/__init__.py +35 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/_init_.py +5 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/exception.py +20 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/exceptions.py +51 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/limiter.py +456 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/py.typed +1 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter/storage.py +312 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter.egg-info/PKG-INFO +300 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter.egg-info/SOURCES.txt +37 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter.egg-info/dependency_links.txt +1 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter.egg-info/requires.txt +12 -0
- fastapi_sql_limiter-0.3.0/fastapi_sql_limiter.egg-info/top_level.txt +1 -0
- fastapi_sql_limiter-0.3.0/pyproject.toml +87 -0
- fastapi_sql_limiter-0.3.0/setup.cfg +4 -0
- fastapi_sql_limiter-0.3.0/test/_init_.py +0 -0
- fastapi_sql_limiter-0.3.0/test/installed_smoke.py +55 -0
- fastapi_sql_limiter-0.3.0/test/test_fastapi_compatibility.py +195 -0
- fastapi_sql_limiter-0.3.0/test/test_limiter.py +420 -0
- fastapi_sql_limiter-0.3.0/test/test_postgres_integration.py +405 -0
- fastapi_sql_limiter-0.3.0/test/test_public_api.py +29 -0
- fastapi_sql_limiter-0.3.0/test/test_storage.py +211 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and releases use
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.3.0] - 2026-11-27
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Database-clock fixed windows and reset/retry metadata in one UPSERT.
|
|
14
|
+
- Success response headers, sanitized 503 storage failures, optional observer
|
|
15
|
+
events, configurable pool/command timeouts, and a 4096-byte identity bound.
|
|
16
|
+
- Bounded `SKIP LOCKED` cleanup and administrator-managed schema mode.
|
|
17
|
+
- FastAPI compatibility, distributed PostgreSQL concurrency, lifecycle,
|
|
18
|
+
failure, security, and regression tests.
|
|
19
|
+
- PostgreSQL and Python benchmark harnesses plus architecture, deployment,
|
|
20
|
+
benchmark, release, and advanced-example documentation.
|
|
21
|
+
- MIT licensing, public project metadata, release notes, and manual Trusted
|
|
22
|
+
Publishing workflows for TestPyPI and PyPI.
|
|
23
|
+
- Real-database tests for window transitions, concurrent cleanup, caller-owned
|
|
24
|
+
pools, pool/command timeouts, namespace isolation, outages, and least privilege.
|
|
25
|
+
- Strict mypy, branch coverage threshold, dependency audit, wheel-install
|
|
26
|
+
verification, Python 3.11–3.15, and PostgreSQL 15/19 CI jobs.
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
|
|
30
|
+
- Automatic namespaces now include HTTP method and route template, preventing
|
|
31
|
+
collisions when one callable is mounted at several routes.
|
|
32
|
+
- `RateLimiter.check` scopes storage keys by window duration, preventing direct
|
|
33
|
+
callers and endpoint namespaces from mixing policies at aligned boundaries.
|
|
34
|
+
- PostgreSQL cleanup uses database time by default and deletes bounded batches.
|
|
35
|
+
- Hot-path conflicts update only the counter, avoiding redundant expiry-index
|
|
36
|
+
writes and enabling PostgreSQL HOT updates when page space permits.
|
|
37
|
+
- The PostgreSQL benchmark now performs warm-ups and repeated runs, samples
|
|
38
|
+
pool utilization, and captures analyzed increment and cleanup plans.
|
|
39
|
+
- PostgreSQL integration tests and benchmark runs now use isolated,
|
|
40
|
+
invocation-specific tables that are removed automatically.
|
|
41
|
+
- Supported Python versions are now 3.11–3.15; 3.8–3.10 are end-of-life.
|
|
42
|
+
|
|
43
|
+
### Fixed
|
|
44
|
+
|
|
45
|
+
- Removed persistent PostgreSQL state leakage between integration-test and
|
|
46
|
+
benchmark executions.
|
|
47
|
+
- Kept exact fixed-window concurrency assertions away from wall-clock window
|
|
48
|
+
boundaries without changing rate limits or production behavior.
|
|
49
|
+
|
|
50
|
+
### Security
|
|
51
|
+
|
|
52
|
+
- Infrastructure errors no longer become ambiguous generic server failures;
|
|
53
|
+
endpoint clients receive a sanitized fail-closed 503.
|
|
54
|
+
- Identity size, database acquisition duration, and command duration are bounded.
|
|
55
|
+
- Rule values are bounded to PostgreSQL `BIGINT` rather than failing inside SQL.
|
|
56
|
+
- Documentation clarifies proxy spoofing and the privacy limits of plain SHA-256.
|
|
57
|
+
|
|
58
|
+
## [0.2.0] - 2026-11-27
|
|
59
|
+
|
|
60
|
+
### Added
|
|
61
|
+
|
|
62
|
+
- Atomic PostgreSQL fixed-window counters backed by `asyncpg`.
|
|
63
|
+
- FastAPI endpoint decorator with direct-client and custom-key support.
|
|
64
|
+
- HTTP 429 retry metadata, explicit lifecycle APIs, cleanup, and pool injection.
|
|
65
|
+
- Unit, API, storage, packaging, and public-API tests.
|
|
66
|
+
- CI, contribution guidance, and a security policy.
|
|
67
|
+
|
|
68
|
+
### Changed
|
|
69
|
+
|
|
70
|
+
- Redis is no longer installed; PostgreSQL is the package's only backend.
|
|
71
|
+
- Examples use FastAPI lifespan management rather than deprecated events.
|
|
72
|
+
- Package version is now `0.2.0` because `0.1.0` shipped without a usable API.
|
|
73
|
+
|
|
74
|
+
### Fixed
|
|
75
|
+
|
|
76
|
+
- Added the missing `__init__.py`, limiter module, exception implementation,
|
|
77
|
+
and valid package exports.
|
|
78
|
+
|
|
79
|
+
## [0.1.0] - 2026-06-26
|
|
80
|
+
|
|
81
|
+
- Initial incomplete project skeleton.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Thank you for improving `fastapi-sql-limiter`.
|
|
4
|
+
|
|
5
|
+
## Local setup
|
|
6
|
+
|
|
7
|
+
Use a supported Python version and create a fresh virtual environment; do not
|
|
8
|
+
reuse an environment committed or copied from another machine.
|
|
9
|
+
|
|
10
|
+
```console
|
|
11
|
+
python -m venv .venv
|
|
12
|
+
.venv\Scripts\python -m pip install -e ".[dev]" # Windows
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
On POSIX systems, use `.venv/bin/python` instead.
|
|
16
|
+
|
|
17
|
+
## Checks
|
|
18
|
+
|
|
19
|
+
Run these before submitting a change:
|
|
20
|
+
|
|
21
|
+
```console
|
|
22
|
+
python -m pytest
|
|
23
|
+
python -m coverage run -m pytest
|
|
24
|
+
python -m coverage report
|
|
25
|
+
ruff check .
|
|
26
|
+
python -m mypy
|
|
27
|
+
python -m pip_audit
|
|
28
|
+
python -m build
|
|
29
|
+
python -m twine check dist/*
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Tests must not require a developer's production database. Storage behavior
|
|
33
|
+
should be tested with an isolated PostgreSQL service or an explicit fake.
|
|
34
|
+
Set `TEST_DATABASE_URL` to a dedicated test database to run integration tests.
|
|
35
|
+
Database benchmarks have an additional test-database name guard; see
|
|
36
|
+
`docs/benchmarks.md`.
|
|
37
|
+
|
|
38
|
+
## Changes
|
|
39
|
+
|
|
40
|
+
- Keep public APIs backward compatible where practical.
|
|
41
|
+
- Add regression tests for bug fixes and user-visible behavior.
|
|
42
|
+
- Update the README and changelog when behavior changes.
|
|
43
|
+
- Never commit credentials, database URLs, virtual environments, or build
|
|
44
|
+
artifacts.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ragavan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-sql-limiter
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Distributed PostgreSQL-backed rate limiting for FastAPI. Atomic counters, simple integration and no Redis required.
|
|
5
|
+
Author: Ragavan
|
|
6
|
+
Maintainer: Ragavan
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/ragavanasde/fastapi-sql-limiter
|
|
9
|
+
Project-URL: Documentation, https://github.com/ragavanasde/fastapi-sql-limiter/tree/main/docs
|
|
10
|
+
Project-URL: Repository, https://github.com/ragavanasde/fastapi-sql-limiter
|
|
11
|
+
Project-URL: Issues, https://github.com/ragavanasde/fastapi-sql-limiter/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/ragavanasde/fastapi-sql-limiter/blob/main/CHANGELOG.md
|
|
13
|
+
Project-URL: Security, https://github.com/ragavanasde/fastapi-sql-limiter/security/policy
|
|
14
|
+
Keywords: asyncpg,distributed,fastapi,postgresql,rate-limit,throttle
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Framework :: FastAPI
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.11
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Requires-Dist: asyncpg>=0.28.0
|
|
32
|
+
Requires-Dist: fastapi>=0.100.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
35
|
+
Requires-Dist: coverage[toml]>=7.6; extra == "dev"
|
|
36
|
+
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
37
|
+
Requires-Dist: mypy>=1.11; extra == "dev"
|
|
38
|
+
Requires-Dist: pip-audit>=2.7; extra == "dev"
|
|
39
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
40
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
41
|
+
Requires-Dist: twine>=5.1; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
# fastapi-sql-limiter
|
|
45
|
+
|
|
46
|
+
`fastapi-sql-limiter` is a lightweight, PostgreSQL-backed fixed-window rate
|
|
47
|
+
limiter for FastAPI. It gives every application process the same atomic request
|
|
48
|
+
counter, so limits remain consistent across workers and hosts without adding
|
|
49
|
+
Redis to a PostgreSQL-based stack.
|
|
50
|
+
|
|
51
|
+
**Distributed FastAPI rate limiting using PostgreSQL. No Redis required.**
|
|
52
|
+
|
|
53
|
+
The package is intended for FastAPI services that already operate PostgreSQL
|
|
54
|
+
and need straightforward endpoint throttling rather than a full API gateway.
|
|
55
|
+
|
|
56
|
+
Project links: [source](https://github.com/ragavanasde/fastapi-sql-limiter),
|
|
57
|
+
[documentation](https://github.com/ragavanasde/fastapi-sql-limiter/tree/main/docs),
|
|
58
|
+
[issues](https://github.com/ragavanasde/fastapi-sql-limiter/issues), and
|
|
59
|
+
[changelog](CHANGELOG.md).
|
|
60
|
+
|
|
61
|
+
## Features
|
|
62
|
+
|
|
63
|
+
- Atomic distributed counters using one PostgreSQL UPSERT and database-clock
|
|
64
|
+
window calculation per request.
|
|
65
|
+
- Async `asyncpg` connection pooling or integration with a caller-owned pool.
|
|
66
|
+
- Per-client, per-user, per-tenant, or per-API-key limits.
|
|
67
|
+
- HTTP 429 responses with standard `Retry-After`; successful and rejected
|
|
68
|
+
responses include conventional `X-RateLimit-*` metadata.
|
|
69
|
+
- Explicit startup, shutdown, and expired-bucket cleanup APIs.
|
|
70
|
+
- Hashed identities in storage and no implicit trust of proxy headers.
|
|
71
|
+
- Sanitized HTTP 503 fail-closed behavior for storage failures.
|
|
72
|
+
- Bounded concurrent cleanup, configurable timeouts, and optional observers.
|
|
73
|
+
- Typed public API with no Redis dependency.
|
|
74
|
+
|
|
75
|
+
## Requirements
|
|
76
|
+
|
|
77
|
+
- Python 3.11 or newer (CI covers 3.11–3.15).
|
|
78
|
+
- FastAPI 0.100 or newer and asyncpg 0.28 or newer.
|
|
79
|
+
- A supported PostgreSQL release (CI covers PostgreSQL 15 and 19).
|
|
80
|
+
|
|
81
|
+
## Installation
|
|
82
|
+
|
|
83
|
+
Install the current source checkout with:
|
|
84
|
+
|
|
85
|
+
```console
|
|
86
|
+
python -m pip install .
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
After a release is published to PyPI, the package can be installed with:
|
|
90
|
+
|
|
91
|
+
```console
|
|
92
|
+
python -m pip install fastapi-sql-limiter
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
For development tools, use `python -m pip install -e ".[dev]"` in a fresh
|
|
96
|
+
virtual environment.
|
|
97
|
+
|
|
98
|
+
## Quick start
|
|
99
|
+
|
|
100
|
+
Store the connection string in an environment variable rather than source
|
|
101
|
+
control:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import os
|
|
105
|
+
from contextlib import asynccontextmanager
|
|
106
|
+
|
|
107
|
+
from fastapi import FastAPI
|
|
108
|
+
from fastapi_sql_limiter import RateLimiter, rate_limit
|
|
109
|
+
|
|
110
|
+
limiter = RateLimiter(
|
|
111
|
+
dsn=os.environ["DATABASE_URL"],
|
|
112
|
+
set_as_default=False,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@asynccontextmanager
|
|
117
|
+
async def lifespan(app: FastAPI):
|
|
118
|
+
await limiter.init_db()
|
|
119
|
+
yield
|
|
120
|
+
await limiter.close()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
app = FastAPI(lifespan=lifespan)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.get("/items")
|
|
127
|
+
@rate_limit(limit=5, window=60, limiter=limiter)
|
|
128
|
+
async def read_items():
|
|
129
|
+
return {"items": ["one", "two"]}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The sixth request from the same direct client within a fixed 60-second window
|
|
133
|
+
returns `429 Too Many Requests`. The decorator must remain below the FastAPI
|
|
134
|
+
route decorator, as shown above.
|
|
135
|
+
|
|
136
|
+
For compatibility with the original `0.1.0` example, constructing a limiter
|
|
137
|
+
sets it as the process default, so `@rate_limit(limit=5, window=60)` also works.
|
|
138
|
+
Passing `limiter=` explicitly is recommended when a process can host more than
|
|
139
|
+
one FastAPI application or storage configuration.
|
|
140
|
+
|
|
141
|
+
## Choosing a request identity
|
|
142
|
+
|
|
143
|
+
The default key is the direct network peer IP (`request.client.host`). It does
|
|
144
|
+
not use `X-Forwarded-For`, because trusting that header without a correctly
|
|
145
|
+
configured proxy lets clients evade limits.
|
|
146
|
+
|
|
147
|
+
Authenticated services should normally limit a stable internal identity:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
from fastapi import HTTPException, Request
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def authenticated_account(request: Request) -> str:
|
|
154
|
+
account_id = getattr(request.state, "account_id", None)
|
|
155
|
+
if account_id is None:
|
|
156
|
+
raise HTTPException(status_code=401, detail="Authentication required")
|
|
157
|
+
return str(account_id)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@app.get("/reports")
|
|
161
|
+
@rate_limit(
|
|
162
|
+
limit=20,
|
|
163
|
+
window=60,
|
|
164
|
+
limiter=limiter,
|
|
165
|
+
key_func=authenticated_account,
|
|
166
|
+
namespace="reports",
|
|
167
|
+
)
|
|
168
|
+
async def reports():
|
|
169
|
+
return {"status": "ready"}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Key functions may be synchronous or asynchronous and must return a non-empty
|
|
173
|
+
string of at most 4096 UTF-8 bytes. Identities are SHA-256 hashed before they
|
|
174
|
+
enter PostgreSQL. Hashing a low-entropy value such as an IP address is
|
|
175
|
+
pseudonymization, not anonymization: it may remain guessable. Never return a
|
|
176
|
+
raw API key; use its internal record ID or an application-side keyed digest.
|
|
177
|
+
A namespace separates independent policies; by default it includes the
|
|
178
|
+
endpoint, HTTP method, and FastAPI route template.
|
|
179
|
+
Separate applications that reuse the same database should use different table
|
|
180
|
+
names or explicit application-prefixed namespaces; identical code, methods,
|
|
181
|
+
and route templates intentionally produce identical automatic namespaces.
|
|
182
|
+
|
|
183
|
+
## Existing asyncpg pool
|
|
184
|
+
|
|
185
|
+
Applications that already manage a pool can share it:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from fastapi_sql_limiter import PostgresStorage, RateLimiter
|
|
189
|
+
|
|
190
|
+
storage = PostgresStorage(pool=application_pool)
|
|
191
|
+
limiter = RateLimiter(storage=storage, set_as_default=False)
|
|
192
|
+
await limiter.init_db()
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`limiter.close()` never closes a caller-owned pool, but it does mark the
|
|
196
|
+
limiter storage closed. Call `init_db()` again before reuse.
|
|
197
|
+
|
|
198
|
+
## Direct checks and cleanup
|
|
199
|
+
|
|
200
|
+
The lower-level API can enforce limits outside a route decorator:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
result = await limiter.check("jobs:tenant-42", limit=100, window=60)
|
|
204
|
+
if not result.allowed:
|
|
205
|
+
print(result.retry_after)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Expired buckets do not affect correctness, but they consume table space.
|
|
209
|
+
Schedule cleanup at an interval appropriate for the service:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
deleted_rows = await limiter.cleanup()
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Cleanup deletes at most 1,000 rows by default. Use `batch_size=`, loop until it
|
|
216
|
+
returns zero, and keep PostgreSQL autovacuum enabled. Concurrent cleaners use
|
|
217
|
+
`FOR UPDATE SKIP LOCKED` rather than waiting on the same rows.
|
|
218
|
+
|
|
219
|
+
## Production schema and failures
|
|
220
|
+
|
|
221
|
+
Production applications should install `PostgresStorage.schema_statements`
|
|
222
|
+
with an administrative role, then construct the limiter with
|
|
223
|
+
`create_schema=False`. The runtime role needs `SELECT`, `INSERT`, and `UPDATE`;
|
|
224
|
+
only the cleanup role needs `DELETE`. Connection creation, pool acquisition,
|
|
225
|
+
and commands have configurable timeouts.
|
|
226
|
+
|
|
227
|
+
Database failures do not silently disable protection. Decorated requests get
|
|
228
|
+
a sanitized `503 Rate limiting service unavailable`; quota violations alone
|
|
229
|
+
use 429. Checks are not automatically retried because a lost database response
|
|
230
|
+
can leave an already-committed increment.
|
|
231
|
+
|
|
232
|
+
Pass a sync or async `observer(event)` to `RateLimiter` for allowed, rejected,
|
|
233
|
+
and database-error counts and latency. Events omit identities and error text,
|
|
234
|
+
and observer failures cannot change enforcement.
|
|
235
|
+
|
|
236
|
+
## API reference
|
|
237
|
+
|
|
238
|
+
- `RateLimiter(dsn, ...)`: owns PostgreSQL storage and optionally registers as
|
|
239
|
+
the default limiter.
|
|
240
|
+
- `RateLimiter.init_db()`: creates the pool, table, and expiry index.
|
|
241
|
+
- `RateLimiter.check(key, limit=, window=)`: returns `RateLimitInfo`.
|
|
242
|
+
- `RateLimiter.cleanup(expired_before=None, batch_size=1000)`: deletes one
|
|
243
|
+
bounded batch.
|
|
244
|
+
- `RateLimiter.close()`: releases owned database resources.
|
|
245
|
+
- `rate_limit(limit=, window=, limiter=, key_func=, namespace=)`: decorates a
|
|
246
|
+
FastAPI endpoint.
|
|
247
|
+
- `PostgresStorage(pool=...)`: adapts an existing asyncpg-compatible pool.
|
|
248
|
+
- `RateLimitExceeded`: the HTTP 429 exception raised by the decorator.
|
|
249
|
+
- `RateLimiterUnavailable`: the sanitized HTTP 503 exception.
|
|
250
|
+
- `RateLimitEvent`: the optional observer payload.
|
|
251
|
+
|
|
252
|
+
## How it works
|
|
253
|
+
|
|
254
|
+
Each request maps to `(namespace, hashed identity, fixed window)`. The window,
|
|
255
|
+
reset time, and retry delay use PostgreSQL `statement_timestamp()` in the same
|
|
256
|
+
statement as `INSERT ... ON CONFLICT DO UPDATE ... RETURNING`. The request is
|
|
257
|
+
accepted while the returned count is at most the configured limit. This avoids
|
|
258
|
+
lost updates, process-local races, application clock drift, and extra queries.
|
|
259
|
+
|
|
260
|
+
## Troubleshooting
|
|
261
|
+
|
|
262
|
+
- **`storage is not initialized`**: call `await limiter.init_db()` in FastAPI's
|
|
263
|
+
lifespan before serving requests.
|
|
264
|
+
- **Database permission error at startup**: create the table once with a role
|
|
265
|
+
allowed to run DDL or grant the application role the required schema access.
|
|
266
|
+
- **Every request has the proxy IP**: use an authenticated identity or a custom
|
|
267
|
+
key function that reads forwarding headers only from a trusted proxy setup.
|
|
268
|
+
- **Unexpectedly shared limits**: pass distinct `namespace=` values or explicit
|
|
269
|
+
limiter instances.
|
|
270
|
+
- **Database outage**: decorated checks return sanitized 503 responses. The
|
|
271
|
+
package intentionally does not fail open and silently remove protection.
|
|
272
|
+
|
|
273
|
+
## Known limitations
|
|
274
|
+
|
|
275
|
+
- Fixed windows can permit a burst around a window boundary.
|
|
276
|
+
- Every check performs a database round trip; extremely high-volume public APIs
|
|
277
|
+
may be better served by a gateway or an in-memory distributed store.
|
|
278
|
+
- Cleanup must be scheduled by the application or database operator.
|
|
279
|
+
- Every protected request performs a PostgreSQL write; a hot identity is
|
|
280
|
+
serialized at one row.
|
|
281
|
+
- Multiple simultaneous policies are deferred because partial counter updates
|
|
282
|
+
and atomic rejection semantics require additional design work.
|
|
283
|
+
- Real PostgreSQL tests exist and run in CI, but require `TEST_DATABASE_URL`
|
|
284
|
+
locally.
|
|
285
|
+
|
|
286
|
+
## Development and security
|
|
287
|
+
|
|
288
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for local checks and
|
|
289
|
+
[SECURITY.md](SECURITY.md) for vulnerability reporting and operational advice.
|
|
290
|
+
Release changes are recorded in [CHANGELOG.md](CHANGELOG.md).
|
|
291
|
+
|
|
292
|
+
Operational details are in [deployment](docs/deployment.md), architecture and
|
|
293
|
+
API semantics in [architecture](docs/architecture.md), reproducible performance
|
|
294
|
+
work in [benchmarks](docs/benchmarks.md), and release steps in
|
|
295
|
+
[releasing](docs/releasing.md).
|
|
296
|
+
|
|
297
|
+
## License
|
|
298
|
+
|
|
299
|
+
Copyright (c) 2026 Ragavan. This project is distributed under the
|
|
300
|
+
[MIT License](LICENSE).
|