Skip to content

Token based rate limiting - #1336

Open
LDiazN wants to merge 13 commits into
2045-create-token-modelsfrom
2046-token-based-rate-limiting
Open

LDiazN wants to merge 13 commits into
2045-create-token-modelsfrom
2046-token-based-rate-limiting

Conversation

@LDiazN

@LDiazN LDiazN commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

This PR implements token based rate limiting for the API, for users providing a token. For most users the API stays the same as always has been. We haven't defined a quota for token users, so for now they have free access, but this PR aims to leave everything in place for creating these quotas.

This builds upon #1335

  • Postgres is now a dependency of oonimeasurements
  • Tokens are fetched from Postgres and cached in memory to reduce DB hits. We don't expect to have many token users, so this shouldn't take too much memory. A consequence of this is that tokens might get up to 1 minute extra of quota after being revoked.
  • Usage bound to a token is recorded in Clickhouse, as it's more fitted for analytics.
  • Usage stats are recorded after the request is sent back to the client, to avoid slowing down the API
  • More rate limiting stats are added to Prometheus, we now distinguish between token usage and ip usage
  • Unknown or expired tokens get 401
  • On a failing Postgres DB, the API works as usual for most users, but returns 503 to token users.
  • /health checks Postgres health, but it only triggers a warning if it fails to avoid taking down the API for most users

Deployment

This PR requires some infrastructure changes before being deployed:

  1. Deploy the api_token_usage table to Clickhouse, make sure this user is able to set async_insert and wait_for_async_insert
  2. Allow write access to this table from the oonimeasurements user
  3. Allow access to the Postgres database from oonimeasurements
  4. Setup postgres_url for oonimeasurements

@LDiazN
LDiazN added this pull request to stack #1337 November 20, 2026 12:16
@LDiazN LDiazN self-assigned this Nov 20, 2026
@LDiazN
LDiazN requested a review from aagbsn November 20, 2026 12:21
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.06%. Comparing base (6364442) to head (d8ab1c8).

Additional details and impacted files
@@                     Coverage Diff                      @@
##           2045-create-token-models    #1336      +/-   ##
============================================================
+ Coverage                     94.03%   94.06%   +0.03%     
============================================================
  Files                            77       77              
  Lines                         10038    10140     +102     
  Branches                        599      616      +17     
============================================================
+ Hits                           9439     9538      +99     
- Misses                          471      474       +3     
  Partials                        128      128              
Flag Coverage Δ
ooniauth 100.00% <ø> (ø)
oonifindings 97.37% <ø> (ø)
oonimeasurements 92.49% <ø> (+0.28%) ⬆️
ooniprobe 91.88% <ø> (ø)
oonirun 98.73% <ø> (-0.01%) ⬇️
testlists 92.46% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

try:
insert_click(
db,
"INSERT INTO api_token_usage "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: we'll need to make the oonimeasurements user readonly=0 (or add another clickhouse user) and add a grant for this table

@aagbsn aagbsn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good. just a few issues - failed authentication requests skip the per-IP limits, we need to remember to change the oonimeasurements db user settings to allow writes or add another user for this table grant, and using an async driver for postgres avoids sharing the threadpool with clickhouse (which isn't so straightforward to change)

log.exception("Failed to look up API token")
API_TOKEN_LOOKUP_ERRORS.inc()
response = JSONResponse({"error": "could not validate token"}, 503)
return await response(scope, receive, send)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add consume_rate_limits on failed authentication

if entry is None or not entry.is_valid():
API_TOKEN_REJECTED.inc()
response = JSONResponse({"error": "invalid token"}, 401)
return await response(scope, receive, send)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consume_rate_limits like above at this exit point

# would make the load balancer take down the API for everyone
warnings = []
try:
await run_in_threadpool(check_postgresql, settings.postgresql_url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider using create_async_engine to avoid threadpool starvation

# workers.
# pool_pre_ping replaces dead connections
self.engine = create_engine(
postgresql_url, pool_pre_ping=True, connect_args={"connect_timeout": 2}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add statement_timeout, pool_timeout, keepalives_idle

  • a hung query can otherwise block the API

use create_async_engine - run_in_threadpool stays blocked until socket times out on a hung connection

return entry

try:
row = await run_in_threadpool(self._fetch, token_hash)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see above re: create_async_engine

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants