Repository navigation
perf(proxy): split aggregated usage query into key-free rollups and bounded top-N keys - #41293
Conversation
…ounded top-N keys Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
|
|
|
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
… statement Both arms now run in a single query_raw call so totals and per-key breakdowns come from the same snapshot. USAGE_TOP_API_KEYS_LIMIT can be raised via env for deployments that need every key in the response. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… endpoint docstring Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…e_aggregate_split Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> # Conflicts: # litellm/proxy/management_endpoints/common_daily_activity.py
…e_aggregate_split
…query path Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…d of SQL text Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… reached Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ated as truncated Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ere loaded Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit cf07ee1. Configure here.
…e_aggregate_split
|
@greptileai please review 3d29133, the branch now carries a fresh merge of main with no code changes of its own |
|
@veria-ai please review 3d29133, the head now includes a fresh merge of main with no functional changes of its own |
|
bugbot run |
Bugbot is paused — on-demand spend limit reachedBugbot uses usage-based billing for this team and has hit its on-demand spend limit. A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue. |
…e_aggregate_split
… global spend rollup code from rc/1.104.0 (#43385) * Revert "feat(proxy): server-side Team Usage export beyond the top-N key cap (#42996)" This reverts commit 77eccac. * Revert "feat(usage): search team keys beyond the top-N in the Team usage view (#42857)" This reverts commit c2eb549. * Revert "feat(usage): search keys beyond the top-N usage subset (#42827)" This reverts commit 5a8ec13. * Revert "Merge pull request #41324 from BerriAI/litellm_daily_global_spend_table" Removes the daily global spend rollup job and its reads. Keeps the LiteLLM_DailyGlobalSpend model and migration so databases that already applied it are untouched and no new proxy-extras version is needed. This reverts commit 87694c2, reversing changes made to its first parent. * Revert "Merge pull request #41293 from BerriAI/litellm_usage_key_free_aggregate_split" Restores the aggregated usage query without the top-N key cap, so the Usage pages, per-key widgets and exports cover every key again. CacheLeakageCard keeps the date picker removal from #42055. This reverts commit 2e46b10, reversing changes made to its first parent. * chore: update Next.js build artifacts (2026-09-27 00:33 UTC, node v24.19.0)
…_aggregate_split"
…_aggregate_split" (#43596) Co-authored-by: yassin <yassin@berri.ai>
…r the usage dashboard (#41324)" (#43595) * Revert "Merge pull request #41324 from BerriAI/litellm_daily_global_spend_table" * Revert "Merge pull request #41293 from BerriAI/litellm_usage_key_free_aggregate_split" (#43596) Co-authored-by: yassin <yassin@berri.ai> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…)" (#43378) * Revert "feat(usage): search keys beyond the top-N usage subset (#42827)" * revert: "feat(proxy): add LiteLLM_DailyGlobalSpend key-free rollup for the usage dashboard (#41324)" (#43595) * Revert "Merge pull request #41324 from BerriAI/litellm_daily_global_spend_table" * Revert "Merge pull request #41293 from BerriAI/litellm_usage_key_free_aggregate_split" (#43596) Co-authored-by: yassin <yassin@berri.ai> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…sage view (#42857)" (#43377) * Revert "feat(usage): search team keys beyond the top-N in the Team usage view (#42857)" * revert: "feat(usage): search keys beyond the top-N usage subset (#42827)" (#43378) * Revert "feat(usage): search keys beyond the top-N usage subset (#42827)" * revert: "feat(proxy): add LiteLLM_DailyGlobalSpend key-free rollup for the usage dashboard (#41324)" (#43595) * Revert "Merge pull request #41324 from BerriAI/litellm_daily_global_spend_table" * Revert "Merge pull request #41293 from BerriAI/litellm_usage_key_free_aggregate_split" (#43596) Co-authored-by: yassin <yassin@berri.ai> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
How it solves it:
metadata.api_key_limitandmetadata.total_api_keysUser Flow
Before: an admin with a few thousand API keys waits minutes for the Usage page and watches partial totals
{"detail":{"error":"Failed to fetch analytics: "}}while the database sidecar climbs past 15 GB of memory (on larger deployments it is OOM-killed)After: the same page loads in a few seconds with every dollar accounted for
metadata.total_spendandmetadata.total_api_requestsmatch the database exactly, including keys that are not listed individually.metadata.api_key_limitis100andmetadata.total_api_keysis3000USAGE_TOP_API_KEYS_LIMITas the knob. Deployments with 100 keys or fewer see no note and can export as beforeRelevant issues
Affected release
Reported by the customer on v1.96.2. The aggregated query has grouped by
api_keysince it was introduced, so this is a scaling limit that every release since then shares rather than a regression in a specific release, and nobackport-stablelabel is requestedLinear ticket
Resolves LIT-7203
Part of LIT-7818 (parent). The follow-up in that ticket adds a key-free
LiteLLM_DailyGlobalSpendrollup table so the key-free query stops scanning the user x key fact table at all. This PR is the query-shape halfPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moredocumentationand thetest_env_keys.pystep ofcode-quality, both of which fail only becauseUSAGE_TOP_API_KEYS_LIMITis documented in docs(proxy): document USAGE_TOP_API_KEYS_LIMIT env var litellm-docs#1484 and that PR has not merged yet. Once it merges, a re-run turns both green@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Live proxy on localhost:4000 (
python litellm/proxy/proxy_cli.py --config litellm/proxy/dev_config.yaml --num_workers 2 --use_v2_migration_resolver) against a local Postgres, Admin UI dev server (npm run dev) on localhost:3000. Same DB, same curls and same browser steps on both sides. Each leg restarts the proxy on its own tree and waits for/health/livelinessto return 200 firstThe user rollup table was seeded with the shape the linked ticket reports (3,000 keys), 30 days, 3 models, 270,000 rows. The team rollup table got 2 teams with 3 keys each for 2 days, so the team case can hit the cap with
USAGE_TOP_API_KEYS_LIMIT=3Sampler used for the sidecar memory numbers, started right before each curl:
while true; do ps -eo rss,args | rg query-engine-debian | rg -v rg | awk '{s+=$1} END {print int(s/1024)}'; sleep 1; doneBefore (a8979fe)
Global Usage, 3,000 keys, 30 days
curl -s -m 120 -H 'Authorization: Bearer sk-1234' -o before.json -w "HTTP %{http_code} in %{time_total}s\n" 'http://localhost:4000/user/daily/activity/aggregated?start_date=2026-08-01&end_date=2026-08-30'HTTP 500 in 30.054310s,cat before.jsongives{"detail":{"error":"Failed to fetch analytics: "}}15797MB of query-engine RSS. Proxy log:LiteLLM Proxy:ERROR: common_daily_activity.py:1453 - Error fetching aggregated daily activity:Team Usage, cap set to 3 with 6 keys
USAGE_TOP_API_KEYS_LIMIT=3(ignored on this side, the variable does not exist yet)curl -s -H 'Authorization: Bearer sk-1234' -o team_before.json -w "HTTP %{http_code}\n" 'http://localhost:4000/team/daily/activity/aggregated?start_date=2026-08-01&end_date=2026-08-02'HTTP 200.python3 -c "import json; d=json.load(open('team_before.json')); m=d['metadata']; print(m['total_spend'], m['total_api_requests'], m.get('api_key_limit'), m.get('total_api_keys'), sorted({k for r in d['results'] for k in r['breakdown']['api_keys']}))"prints0.72 480 None None ['tkey-1-1', 'tkey-1-2', 'tkey-1-3', 'tkey-2-1', 'tkey-2-2', 'tkey-2-3']Cost Optimization, cache leakage by virtual key
One extra key was seeded for this leg only: 30 rows of
key-cheap-nanoongpt-5-nanowith 400,000 prompt tokens and $0.0001 spend each, so it is the biggest uncached-input key (12,000,000 tokens) and the lowest-spend one (ranked 3,001 of 3,001 by spend). Deleted again afterwardskey-chea...on top at 7,200,000 uncached input tokens and the rest at 54,000After (3d29133)
Global Usage, 3,000 keys, 30 days
HTTP 200 in 4.043630s(3.81 s on the earlier head b74733d, the current head is that code plus two merges of main)python3 -c "import json; d=json.load(open('after.json')); m=d['metadata']; keys={k for r in d['results'] for k in r['breakdown']['api_keys']}; print(len(d['results']), round(m['total_spend'],3), m['total_api_requests'], m['api_key_limit'], m['total_api_keys'], len(keys))"prints30 13201.65 1350000 100 3000 100, so the totals equal thepsqlsums above even though only 100 of the 3,000 keys are listed612MB of query-engine RSSpsqlon the same predicate.model=gpt-5givesHTTP 200 in 1.78swith spend 4400.55 and 450,000 requests.api_key=key-0096givesHTTP 200 in 0.065swith spend 8.73, 450 requests andtotal_api_keys1, and the same key's owner through/user/daily/activity/aggregated?user_id=user-96gives the same 8.73 and 450.timezone_offset_minutes=-120givesHTTP 200 in 3.72swith unchanged totals, and/team/daily/activity/aggregatedgivesHTTP 200 in 0.081sUsage page, before and after
Before, 75 seconds after Apply: the aggregated call has failed and the page is paging the per-user endpoint, $1,661.53 of $13,201.65 loaded so far
After, about 4 seconds after Apply: the Cost tab shows the full $13,201.65 and 324,000,000 tokens off the single aggregated call
After, Key Activity tab: "Showing 100 of 100 keys" and the note that only the 100 highest-spend keys of 3,000 are loaded, Export Data disabled
The Total Requests, Successful Requests and Failed Requests cards on the Cost tab read the gateway request log (
/spend/logsbasedgatewayDailyActivityCall), not the daily rollup tables, so they show 0 on both sides with this seeded fixture. Model Activity and Endpoint Activity, which read the rollups, show 1,350,000 on the after sideTeam Usage, cap set to 3 with 6 keys
USAGE_TOP_API_KEYS_LIMIT=3HTTP 200. Same python line prints0.72 480 3 6 ['tkey-1-2', 'tkey-1-3', 'tkey-2-3'], so team totals and per-team spend (team-10.36,team-20.36, matchingpsql) still cover all 6 keys while only the 3 highest-spend keys are listedCost Optimization, cache leakage by virtual key
key-cheap-nanois no longer in the table because it is outside the 100 highest-spend keys, so the card now says "Only the 100 highest-spend keys of 3,001 are loaded, so a lower-spend key that leaks more is not listed here. Raise USAGE_TOP_API_KEYS_LIMIT on the proxy to load more keys." The By model view has no such gap and shows no noteType
🐛 Bug Fix
Caveats (if any)
Medium
Low
USAGE_TOP_API_KEYS_LIMITdefaults to 100 and can be raised with the env var of the same name for deployments that need every key listed. Documented in docs(proxy): document USAGE_TOP_API_KEYS_LIMIT env var litellm-docs#1484, which has to merge before thedocumentationcheck here goes greenUNION ALLstatement, so the response is one snapshot and the DB does two passes over the filtered rowsmetadata.total_api_keyscounts keys with rows in range and excludes the PTU placeholder key. The placeholder's spend stays in the totalsai_usage_chat.py) reads the same aggregated response but only summarises totals, models, providers and entities, none of which are cappedPR risk: N/10overview comment only when it has at least one finding, so a clean run leaves no overview comment (checked against every Veria overview in the repo since 2026-09-12, all of which carryFixed/addressedof 1 or more). On cf07ee1 theVeria AI - PR Reviewcheck completed withNo security issues found, zero inline findings and zero open Veria threadsno new issueson cf07ee1 stays valid for this head because that commit is an ancestor of it. Thebugbot runposted for 3d29133 was answered withBugbot is paused, on-demand spend limit reached, so no fresh Bugbot verdict exists for the merge commit itself. On 3d29133 Greptile scored 5/5 with no outstanding finding, theVeria AI - PR ReviewandCodeQLchecks completed with no findings, and there are 0 opengithub-advanced-securitythreads and 0 unresolved review threadsFinal Attestation
ran /live-pr-risk and found no regressions/backward incompatible risks
Link to Devin session: https://app.devin.ai/sessions/09ed50d5f86a4716931d706cbd7148f2
Open in Devin Desktop: https://app.devin.ai/desktop/session/09ed50d5f86a4716931d706cbd7148f2?variant=devin
Requested by: @yassin-berriai