Skip to content

Enforce the action-items rate limit: exempt action_items:list from RATE_LIMIT_BOOST - #12258

Merged
Git-on-my-level merged 1 commit into
mainfrom
cost/c006-boost-exempt-action-items-rate-limit
Aug 26, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
cost/c006-boost-exempt-action-items-rate-limit

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

The measured problem

GET /v1/action-items is 48.8% of every billable Firestore document read in the project — ~6,600 docs/sec sustained.

The source is ~82 stale omi-windows/1.0.0 clients, each hot-looping the endpoint with a completed=false / completed=true pair roughly every 1.2s (97 req/min/uid). At the billing-measured marginal price of $0.05395 per 100k reads — a SKU with zero credits applied — that traffic costs **$328/day**.

Evidence, including the derivation of the price and the per-client cadence: omi-knowledge/projects/gcp-cost-efficiency/evidence/2026-08-26-c006-falsification.md (lever L1).

Why this lever

The correct cap already exists. #11965 shipped a (12, 60) per-uid policy for action_items:list.

It has never fired once. The serving revision carries RATE_LIMIT_BOOST=100, so get_effective_limit() resolves the policy to 1,200 requests / 60s — well above the observed ~97/min. Zero 429s in a 7,932-request observation window, and shadow mode is off, so this is not a shadow-mode artifact: the cap is deployed and inert.

This PR restores an already-approved number rather than choosing a new one. It needs no client release, touches no client code, and captures ~$290/day (~88% of the loop).

Mechanism

  • New module-level BOOST_EXEMPT_POLICIES: frozenset[str] in backend/utils/rate_limit_config.py, honored inside get_effective_limit(). An exempt policy returns its base (max_requests, window) and ignores the boost entirely — including an explicitly passed boost= argument.
  • Seeded with action_items:list and only that. The other ~40 policies keep the boost, and a test asserts it for every one of them.
  • RATE_POLICIES keeps its dict[str, tuple[int, int]] shape. A third tuple element would have broken ~15 call sites across six test files that unpack it as a 2-tuple, so the exemption is a sibling set — matching the module's existing "flat module-level knobs" style.

Rollback is an env change, not a deploy of code. The exemption list is read from RATE_LIMIT_BOOST_EXEMPT at import time, in the same style as the module's only two other knobs:

RATE_LIMIT_BOOST_EXEMPT=""      # every policy back under the boost

That returns prod byte-for-byte to today's behaviour via a Cloud Run env-var change on a new revision — no build, no image push, no revert, no merge. Unknown names are resolved against RATE_POLICIES and dropped, so a typo neither crashes the process at import nor silently exempts nothing. RATE_LIMIT_SHADOW_MODE=true remains the blunter kill switch for all enforcement.

Do not roll back by lowering RATE_LIMIT_BOOST — that silently retunes ~40 unrelated policies.

The tradeoff, stated honestly

Stale Windows clients will start receiving 429s on /v1/action-items, and most likely will not be told.

The degraded-mode banner from 53d5b9e54a requires ≥5 rate-limit hits across ≥2 distinct request paths within 60s (minDistinctKeys: 2), specifically so one endpoint's retry loop cannot trip it. This change 429s exactly one path. Users on stale builds therefore see a silently stalled task sync — the failure mode that banner exists to make visible — rather than the amber banner. That is the main thing to weigh here, and it is worse than the evidence file's blast-radius wording assumed.

Mitigating facts:

  • Data stays correct. 12 refreshes/minute is still ~150x more often than the app's own post-fix design (65249902cb: one sync per 5 minutes at limit=100). Nothing is dropped; the client just cannot poll at 97/min.
  • Enforcement runs in Depends() before the handler, so a 429 costs one Cloud Run request and zero Firestore reads — which is the entire saving.
  • Writes (action_items:write) and every other route are untouched and keep the boost.
  • Legit first-party clients (Mac/Flutter hydrate plus pagination) fit inside 12/min — the fix(backend): cap GET /v1/action-items at 12/min per uid #11965 sizing rationale, unchanged. Multiple devices on one uid share the per-uid budget.

This is a server-side backstop, not the structural fix. Getting 65249902cb into users' hands is still the real answer; this PR is what does not depend on that shipping.

Post-ship falsification bar

Measure 7 complete days after the change is confirmed serving (check the revision's release SHA and that RATE_LIMIT_BOOST_EXEMPT is as expected on it — merged is not serving).

Primary (money, decides it): App Engine | Cloud Firestore Read Ops net $/day, 7-day post-ship mean vs. the 7-day pre-ship baseline of $542/day (08-18…08-24).

  • ≥ $480/day → the cut is NOT supported (<12%, inside the $460–629 day-to-day range).
  • $350–480/day → partial; name which lever under-delivered.
  • ≤ $300/day → validated.

Secondary (mechanism — must also hold, or the money moved for some other reason):

  1. /v1/action-items 429 share jumps above zero. Today it is exactly zero, so any nonzero count is the proof the cap went live.
  2. action_items_list share of billed reads falls to ≤ ~15% (from 48.8%), and its docs/sec 24h median falls below 1,200 (from 6,600).
  3. Distinct remoteIp on /v1/action-items in a 60s window stays ≥ 60 — the drop must come from each client polling less, not from clients disappearing. If IP count collapses, the result is void.

Note: this lever stops the Firestore reads; it does not stop the clients from asking. Whether total request rate to /v1/action-items falls depends on how the pre-fix binary reacts to a 429, which is not determinable from the code alone. Worst case this converts an expensive Firestore bill into a much cheaper Cloud Run request bill — still the right trade, but it is not a request-rate claim.

Void conditions: serving revision changed mid-window; RATE_LIMIT_BOOST changed for an unrelated reason; any partial day in the billing export; a /v1/action-items availability incident (non-200 > 1%).

Test coverage

+10 unit tests in backend/tests/unit/test_rate_limiting.py (84 passed, 1 skipped locally; baseline without this change is 74 passed, 1 skipped).

  • Boosted policies still boost — TestBoostExemption.test_non_exempt_policies_still_boost covers every non-exempt policy at boost=100, and TestEnforceRateLimit.test_boosted_policies_still_check_the_boosted_limit pins the value actually handed to check_rate_limit.
  • The exempt policy binds at its base limit — test_exempt_policy_ignores_the_boost (boosts of 2, 100, 1000) and test_action_items_list_checks_base_limit_under_a_boost, which asserts check_rate_limit is called with (12, 60) while RATE_LIMIT_BOOST=100. Plus env-override and typo-handling tests.
  • The 429 carries the enforced limit — test_action_items_list_429_carries_the_degraded_mode_contract: status 429, Retry-After, X-RateLimit-Remaining: 0, and X-RateLimit-Limit: 12 — the cap actually enforced, not the boosted 1,200.

black --line-length 120 --skip-string-normalization --check is clean on both files.

Failure-Class: none

🤖 Generated with Claude Code

Review in cubic

The (12, 60) per-uid cap on `action_items:list` shipped in #11965, but the
serving revision carries RATE_LIMIT_BOOST=100, so get_effective_limit()
resolves it to 1,200/60s and it has never fired once. Meanwhile ~82 stale
omi-windows/1.0.0 clients hot-loop GET /v1/action-items at ~97 req/min/uid,
which is 48.8% of every billable Firestore document read in the project
(~$328/day marginal at $0.05395/100k).

Add BOOST_EXEMPT_POLICIES, honored in get_effective_limit(): an exempt
policy always serves its base limit and ignores the boost, including an
explicitly passed boost= argument. Seeded with action_items:list only;
the other ~40 policies keep the boost, and a test asserts that.

This restores an already-approved cap rather than choosing a new number,
needs no client release, and cuts the loop from ~97 to 12 req/min/uid
(~88%, ~$290/day). Enforcement runs in Depends() before the handler, so a
429 costs one Cloud Run request and zero Firestore reads.

The exemption list is env-escapable in the module's existing style:
RATE_LIMIT_BOOST_EXEMPT="" puts every policy back under the boost and
restores byte-for-byte today's behaviour via a Cloud Run env change on a
new revision -- no build, no image push, no revert. Unknown names are
resolved against RATE_POLICIES and dropped, so a typo cannot crash import.

Tradeoff: stale Windows clients will now see 429s on /v1/action-items.
Their data stays correct -- 12/min is still ~150x more often than the
app's own post-fix 5-minute sync design (6524990).

+10 unit tests: non-exempt policies still boost, the exempt policy binds
at (12, 60) under RATE_LIMIT_BOOST=100, env override and typo handling,
and the 429 carries X-RateLimit-Limit: 12 (the enforced cap, not 1,200).

Co-Authored-By: Claude Fable 5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit af8a490 into main Aug 26, 2026
15 of 19 checks passed
@Git-on-my-level
Git-on-my-level deleted the cost/c006-boost-exempt-action-items-rate-limit branch August 26, 2026 16:58
Git-on-my-level added a commit that referenced this pull request Sep 3, 2026
## What exists today (measured, not assumed)

`GET /v1/action-items` was **65.6% of all backend requests** and
**48.8% of every billable Firestore document read** (~$328/day) until
#12258 made the
`action_items:list` policy immune to `RATE_LIMIT_BOOST`, so its 12/min
per-uid cap
finally started firing. That fix worked, and it is not undone here.

I re-measured the route this afternoon before writing any code.

**Prometheus, 24h means (2026-09-02):**

| | before #12258 | now |
| --- | ---: | ---: |
| `action_items_list` docs/sec | 6,600 | **692** |
| `action_items_list` ops/sec | 121 | **3.11** |
| **docs per operation** | 54.5 | **~223** |
| `action_items_list` share of `stackdriver_..._document_read_count` |
48.8% | **~13%** |

**Cloud Run, untruncated fixed window 2026-09-02T17:46–17:49Z (545
requests, read-only capture):**

- **3.03 req/s** (was 128–132), **97 distinct remote IPs** — the drop
came from each
  client polling less, not from clients disappearing.
- **480 × 200, 64 × 429 (11.7%), 1 × 401.** 63 of the 64 429s are
`omi-windows`.
- Client mix: **490 `omi-windows`, 31 `Dart`, 23 macOS `CFNetwork`, 1
`Bun`.**
- Query mix: `limit=500&offset=0&completed=false` 223,
`...&completed=true` 194,
  `limit=50` 37, `limit=100` 31, `offset=500` 28.

Two things follow, and they are the whole design rationale:

1. **The remaining problem is fan-out, not frequency.**
Documents-per-operation went
*up*, 54.5 → ~223, because the cheap requests are exactly the ones the
cap removed.
What survives is large-backlog accounts re-reading an unchanged backlog
on every
   allowed poll — 12 full backlog reads per minute per uid, forever.
2. **The stale fleet is still the traffic.** 90% of surviving requests
are the pre-fix
`omi-windows/1.0.0` build asking for `limit=500`, two weeks after its
client-side fix
(`65249902cb`, `SYNC_THROTTLE_MS = 5 min`, `PAGE_LIMIT = 100`) merged.
Its rollout is
   still unobservable, so the backstop has to be server-side.

**Honest scoping, stated up front:** at 692 docs/sec this route is now
~**$32/day**
(marginal $0.05395/100k) out of a `App Engine | Cloud Firestore Read
Ops` line running
**$376.71/day** (mean of the six complete post-ship days 08-27…09-01).
*This route is no
longer what dominates that line.* This PR takes the rest of it and caps
the regression
path; it does not claim the other ~$340/day, which is uninstrumented
read volume and
needs its own attribution work.

## What changes

Three things, each independently disableable by one env var.

### 1. Repeat polls read zero Firestore documents
(`database/action_items_cache.py`)

A per-uid Redis response cache for the **unfiltered** listing (98.6% of
measured
traffic), plus an `ETag` / `If-None-Match` → **304** path.

- **Key** is `ail:{uid}:{version}:{param fingerprint}`. The version is a
per-uid counter
that **every action-item write bumps** — one `INCR`, no key enumeration,
no
per-mutation invalidation list to drift out of sync. Invalidation is
hooked into all
12 mutating helpers in `database/action_items.py`, plus the two writers
that touch the
collection from outside that module (`goals.transition_goal_lifecycle`'s
`detach`
  disposition and `staged_tasks.restore_legacy_conversation_items`).
- **The TTL is the safety net, not the mechanism.** If a future writer
forgets to bump,
the worst case is bounded staleness of
`ACTION_ITEMS_LIST_CACHE_TTL_SECONDS`
(default **30s**, clamped to 300), never a permanently wrong list. The
version key's
own TTL is 7 days so a version can never expire back onto a live cached
entry.
- **Truncated pages are never cached** — caching a budget-exhaustion
artifact would pin
  a partial page for the whole TTL and make a client's retry free.
- Date- and conversation-scoped reads bypass the cache entirely (rare,
high cardinality).
- Redis is **fail-open**, matching `_enforce_rate_limit`'s first-party
contract: an
outage degrades to today's behaviour (a real read), never to a wrong
answer.

**Why zero UX impact for an up-to-date client:** any write by that user
— from any
device, including the server-side conversation pipeline — bumps the
version and the next
read is fresh. The only staleness window is a write that does not go
through the hooked
paths, bounded at 30s. macOS and Flutter already reconcile at a 5-minute
cadence.

### 2. A second, stricter ceiling for the hot-loop client class
(`utils/action_items_list_guard.py`)

`action_items:list_hot_client`, default **4/60s per uid**, env-tunable
via
`ACTION_ITEMS_LIST_HOT_CLIENT_MAX` (0 disables). Returns 429 with
`Retry-After`.

**It composes with the existing limiter rather than conflicting with
it.** Two
independent Redis buckets: every client is still governed by
`action_items:list`
(12/min), charged in the auth `Depends()` before the route body; a
client *additionally*
classified as the hot-loop build is charged this second bucket inside
the route, before
any Firestore work. Both must admit. Nothing about the existing policy's
key, window, or
value changes, and the new policy is added to
`RATE_LIMIT_BOOST_EXEMPT`'s default for
the same reason as its parent — a cap chosen to stop a hot loop is not
something an
event boost should widen 100×.

Classification is deliberately narrow: only the exact
`omi-windows/1.0.0` product token
counts as `stale_windows`. An unrecognised or absent user agent is
**not** classified,
because a misclassification here degrades a real client and the 12/min
policy already
covers the general case. (The stale build sends no
`X-App-Platform`/`X-App-Version` on
this route, so the UA token is the only available discriminator.)

Blast radius: the ~90 hot-loop clients see a refresh every ~15s instead
of every ~5s.
Their data stays correct, and that build already has 429-storm handling
(`53d5b9e54a`, `observability/backendDegraded.ts`).

### 3. Metrics that prove it (`utils/metrics.py`)

- `omi_action_items_list_cache_total{outcome}` — `hit | not_modified |
miss | bypass | unavailable`.
- `omi_action_items_list_throttled_total{client,policy}` — 429s by
client class.

These exist because the last three mitigations on this route were all
*merged and inert*
in production, and nobody could tell for a week. `hit`/`not_modified`
are, by
construction, the requests that performed **zero** Firestore reads.

### What I did not build: the minimum-client-version gate

**The backend has no client-version gate pattern to reuse**, so per the
brief I am
proposing rather than inventing one. What exists is
`routers/firmware.py`'s `min_version`
(device firmware, not API clients) and `routers/desktop_chat.py:1592`'s
`426 Upgrade
Required` for a *chat contract* version — neither is a general client
gate, and there is
no `X-App-Version` header on this route to gate on. A proper version
gate would need
(a) the Windows client to send `X-App-Platform`/`X-App-Version` on
`apiFetch` as it
already does for JIT and listen, (b) a shared
`utils/client_version_gate.py` reading a
per-platform minimum from env, and (c) a client that renders "update
required" instead
of retrying. That is a cross-tree change with a client release in it; it
should be its
own PR, and it is strictly worse than this one as a *first* move because
it depends on
the same unobservable auto-update reach that made the server-side
backstop necessary.

### Can `completed=false` and `completed=true` be served from one read?

Not for these callers, and I would not change it here. The
`completed=None` path already
reads both buckets in one request (active-first, then completed,
product-sorted) — but
that returns one merged page, not the two bucket-scoped pages the
Windows client asks
for, and swapping them changes pagination semantics for every client.
The realistic wins,
both taken or already present: both buckets now share **one**
invalidation version, so a
single write invalidates the pair and a paired poll costs at most one
read per bucket per
TTL instead of two per cycle; and `GET /v1/action-items/ids?completed=`
already exists as
the projection-only reconciliation path (`action_items_visible_ids`, 67
docs/sec in prod)
for clients that only need the id census.

## Expected saving, and its basis

Basis:
`avg_over_time(sum(rate(omi_firestore_documents_per_operation_sum{family="action_items_list"}[1h]))[24h:10m])`
= **691.9 docs/sec** = 5.98e7 reads/day; marginal price
**$0.05395/100k** (OLS on 14
complete billing-export days, r = 1.00000,
`evidence/2026-08-26-c006-falsification.md`)
→ **$32.3/day** is the entire remaining prize for this family.

At a 30s TTL the cache bounds an idle user's polls to **2 Firestore
reads/min** instead of
12 — an 83% ceiling reduction — and the docs/op histogram says the hit
rate will be high
(25.7% of these requests read zero documents even before caching).
Discounting for
write-driven misses and the uncached filtered reads:

> **Expected: $20–27/day (~$7–10k/year)**, taking the line from a
$376.71/day six-day
> mean to roughly **$350–357/day**. Not a headline number — the headline
was already
> taken by #12258 (−$172.73/day, −31.4%, holding six days).

## Kill-check — the metric that decides this within 24h of deploy

Measured 24h after the revision is confirmed *serving* (revision env /
release SHA, never
merge status). Drop the newest two Cloud Monitoring buckets.

**Primary (mechanism, decides it):**

1.
`sum(rate(omi_action_items_list_cache_total{outcome=~"hit|not_modified"}[1h]))
/ sum(rate(omi_action_items_list_cache_total[1h]))`
≥ **0.5**. Below 0.3 → the cache is not being hit and the change did not
work; roll back.
2.
`avg_over_time(sum(rate(omi_firestore_documents_per_operation_sum{family="action_items_list"}[1h]))[24h:10m])`
   < **250 docs/sec** (from 691.9). ≥ 500 → not supported.
3.
`avg_over_time(sum(rate(omi_firestore_read_operations_total{family="action_items_list"}[1h]))[24h:10m])`
   < **1.2 ops/sec** (from 3.11).

**Void conditions (re-run, do not record a result):**

- Distinct `remoteIp` on `/v1/action-items` in a 60s window drops below
**60** (from 97) —
a drop that comes from clients disappearing is churn or an outage, not a
saving.
- `omi_action_items_list_throttled_total` rises for any `client` other
than
`stale_windows` — that is a misclassification, and the ceiling should be
zeroed.
- `/v1/action-items` non-200/429 rate above 1%.

**Money (confirmatory, 7 days):** `App Engine | Cloud Firestore Read
Ops` net $/day,
complete days only (verify `MAX(usage_end_time)`), against the
08-27…09-01 mean of
$376.71/day. Expect **$350–357/day**. This line is no longer dominated
by this route, so
it cannot decide the change on its own — that is what the mechanism
checks are for.

## Rollback

Both levers are env vars on the serving revision; neither needs a code
deploy:

- `ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=0` — disables the cache and the
304 path entirely;
  every read goes straight to Firestore, exactly as today.
- `ACTION_ITEMS_LIST_HOT_CLIENT_MAX=0` — disables the second ceiling;
the 12/min
  `action_items:list` policy is untouched and keeps enforcing.
- `RATE_LIMIT_BOOST_EXEMPT` still accepts an explicit list if the new
policy needs to go
  back under the global boost.

## Tests

`backend/tests/unit/test_action_items_list_read_cost.py` — 25 tests.
They assert the
*cost* property, not just the body: a cache hit and a 304 are pinned to
**zero calls to
`action_items_db.get_action_items`**, the one function that streams
documents. A test
that only checked the response would pass on a design that reads
Firestore and throws the
result away — which is exactly the failure this change exists to
prevent. Also covered:
write-driven invalidation, truncated pages never cached, filtered reads
bypassing,
TTL clamping and typo tolerance, Redis-outage fail-open on both the
cache and the ceiling,
the ceiling refusing *before* the database call, non-hot clients never
touching the second
bucket, the `0` kill switch, UA classification (including "a UA that
merely mentions
Windows is not the hot-loop build"), and RFC 9110 `If-None-Match` weak
comparison.

## Self-test — the real HTTP path, not the function

Unit tests call the handler directly, which does not exercise FastAPI's
response
handling. I also drove the router over HTTP with `TestClient` (fake
Firestore rows, fake
Redis, `ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=30`,
`ACTION_ITEMS_LIST_HOT_CLIENT_MAX=2`),
counting calls to `action_items_db.get_action_items` across the
sequence:

```
1  first        200 db_calls= 1 etag= W/"c000909dde9858350f2836fa6d929047"
2  repeat       200 db_calls= 1 same_body= True
3  If-None-Match 304 db_calls= 1 len(body)= 0
4  after write  200 db_calls= 2
5  hot 1/2/3 -> 200 200 429  retry_after= 11  db_calls= 4
6  mac after hot refusals -> 200

omi_action_items_list_cache_total{outcome="hit"} 1.0
omi_action_items_list_cache_total{outcome="not_modified"} 1.0
omi_action_items_list_cache_total{outcome="miss"} 5.0
omi_action_items_list_throttled_total{client="stale_windows",policy="action_items:list_hot_client"} 1.0
```

Line 2 and line 3 are the change: the repeat poll and the conditional
request both return
without `db_calls` moving. Line 4 shows a write invalidating. Line 5
shows the hot-loop
ceiling refusing the third request with `Retry-After` and no database
call, and line 6
shows a macOS client is unaffected by those refusals (separate bucket,
separate key).

**Gates run locally:** `make preflight` — **28/28 pass**.
`scripts/typecheck.sh` — 0
errors. `scripts/scan_async_blockers.py --dirs routers utils` — 0
blocking findings.
Backend unit suites (run per file; batching these files has a
pre-existing cross-module
import-pollution artifact on `main` as well):
`test_action_items_list_read_cost` 25
passed, `test_rate_limiting` 84 passed/1 skipped,
`test_action_items_pagination_order` 11
passed, `test_action_items_router_pagination` 4 passed,
`test_action_item_ids_endpoint` 13
passed, `test_action_items_conversation_list_malformed` 3 passed,
`test_action_item_canonical_contract` 18 passed,
`test_mcp_action_item_writes` 43 passed,
plus `test_rate_limit_cache_cap`, `test_rate_limit_json_failopen`,
`test_action_item_dedup`, `test_action_item_date_validation`,
`test_action_items_date_coercion`,
`test_action_items_due_range_index_contract`,
`test_conversation_action_items_count`, `test_action_items_timezone`,
`test_action_items_date_range_validation`,
`test_action_item_reminder_cancel_on_complete`,
`test_action_item_vector_best_effort` — all green.

Failure-Class: none

This is a cost control on a route that is behaving as designed, not a
repair of a
semantic defect. `scripts/failure-class prepare` found no definition
whose scope hints
overlap the change. (The nearest historical class,
`FC-alert-never-provably-fired`,
belongs to #12258 — a limiter that shipped and never fired — and is
already fixed; the
two new counters here exist so this change cannot repeat it.)

Line-Count-Exception: backend/database/action_items.py | 1543 -> 1562 |
one `bump_action_items_list_version(uid)` call after each of the
module's committed writes, plus the import; the module is the canonical
mutation owner for this collection, so splitting it to add cache
invalidation would move the invalidation away from the writes it must
follow

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12618?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
pull Bot pushed a commit to Mu-L/omi that referenced this pull request Sep 3, 2026
`action_items_list` was 48.8% of every billable Firestore document read
(~$328/day) until BasedHardware#12258 exempted the `action_items:list` policy from
`RATE_LIMIT_BOOST` and its 12/min per-uid cap started firing. That removed the
*frequency* half of the problem: 6,600 -> 692 docs/sec (24h mean, 2026-09-02),
121 -> 3.1 ops/sec, and a 3-minute prod capture shows the route at 3.0 req/s
with 11.7% 429s, 98% of them `omi-windows`.

What is left is fan-out, not frequency. Documents-per-operation went the other
way, 54.5 -> ~223, because the cheap requests are exactly the ones the cap
removed. The surviving traffic is large-backlog accounts, still 90% on the
pre-fix `omi-windows/1.0.0` build asking for `limit=500`, re-reading an
unchanged backlog on every allowed poll.

Three changes, all env-tunable and all off-by-one-env-var:

1. Per-uid response cache + ETag/`If-None-Match` -> 304 for the unfiltered
   listing. A cache hit and a 304 both perform zero Firestore reads. The key
   carries a per-uid version that every action-item write bumps, so a write
   invalidates every cached page for that user in one INCR — no key
   enumeration, no per-mutation invalidation list to keep in sync. The TTL
   (`ACTION_ITEMS_LIST_CACHE_TTL_SECONDS`, default 30s, 0 disables) is the
   safety net rather than the mechanism: a writer that ever forgets to bump
   costs bounded staleness, never a permanently wrong list.

2. A second, stricter ceiling for the known hot-loop client class
   (`action_items:list_hot_client`, `ACTION_ITEMS_LIST_HOT_CLIENT_MAX`,
   default 4/min, 0 disables). It composes with `action_items:list` rather
   than replacing it: every client keeps the 12/min bucket, and only the stale
   build is additionally charged the second one. Refusal happens before any
   Firestore work, so a throttled poll costs zero reads.

3. `omi_action_items_list_cache_total{outcome}` and
   `omi_action_items_list_throttled_total{client,policy}` — the metrics that
   prove within 24h of a deploy that the reads actually went away, instead of
   inferring it from the billing export a week later.

Classification is deliberately narrow: only the exact `omi-windows/1.0.0`
product token counts as hot. An unrecognised user agent is not, because a
misclassification here degrades a real client and the 12/min policy already
covers the general case. Redis is fail-open on both paths, matching
`_enforce_rate_limit`'s first-party contract.

Failure-Class: none

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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.

1 participant