Repository navigation
perf(spend_tracking): index LiteLLM_SpendLogs by (api_key, startTime) - #37983
yuneng-berri merged 3 commits into
Conversation
Greptile SummaryAdds a composite
Confidence Score: 5/5The PR appears safe to merge No blocking failure remains
|
| Filename | Overview |
|---|---|
| litellm-proxy-extras/litellm_proxy_extras/migrations/20260823000000_add_spend_logs_api_key_starttime_index/migration.sql | Adds the matching index migration; no follow-up-eligible defect was identified |
| schema.prisma | Adds the composite index declaration consistently with the migration and mirrored schemas |
| litellm/proxy/schema.prisma | Keeps the proxy Prisma schema aligned with the canonical schema |
| litellm-proxy-extras/litellm_proxy_extras/schema.prisma | Keeps the packaged migration schema aligned with the canonical schema |
| db_scripts/partition_spend_logs.sql | Preserves the composite index while replacing the spend-log table with its partitioned form |
| db_scripts/unpartition_spend_logs.sql | Preserves the composite index while restoring a non-partitioned spend-log table |
Reviews (3): Last reviewed commit: "fix(db_scripts): carry the new spend ind..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
60af4db to
871e8a6
Compare
|
Load-test evidence: this index is load-bearing for Keys with A/B on a clean rig (litellm-database:1.97.0, Postgres 18): N keys × 3 windows, 150 spend rows/key over 7 d, 25 RPS, paired probes on identical data:
At 10k keys the proxy is effectively down from its own budget bookkeeping; building this index under that load took 3.1 s and restored 42 ms p95 with zero errors. Plans: parallel seq scan (1.53M rows filtered, 95k buffers, ~740 ms) → bitmap index scan (101 buffers, 0.61 ms). Index cost at 1.53M rows / 5.7 GB: 162 MB (2.8% of table), build 1.5 s quiet, inserts +3.5–4.3% — and live batched INSERTs got faster with the index at scale (seq scans no longer evict the buffer cache). |
|
@yuneng-jiang @ryan-crabbe-berri I am aware of the backlog of PRs but I belive this one should be prioritized because of simplicity and performance impact it solves |
Every per-key spend read filters WHERE api_key = ... AND startTime in a range (/spend/logs?api_key=..., the key-filtered UI logs page, external billing readers), but LiteLLM_SpendLogs carries no api_key index, so each such query scans every logged request on the instance. Composite with startTime to match the query shape, mirroring the existing (startTime, request_id) composite. Measured on Postgres 18 with 1.6M spend rows: one key's 7-day SUM goes from a 93.9ms parallel seq scan to a 0.7ms bitmap index scan (~140x); a batch job reading per-key spend for 10k keys went from 20.5s to 1.7s.
29b9f3b to
1bdc1b9
Compare
|
Hello @mateo-berri, again sorry for tagging you, I see you have been one of the most active contributor lately. This missing index is causing our database to be burning all day long 🙏 |
|
@greptile review |
|
@cursor review |
…ooks
partition_spend_logs.sql and unpartition_spend_logs.sql hardcode every
index Prisma defines on LiteLLM_SpendLogs, because `LIKE ... INCLUDING
DEFAULTS INCLUDING GENERATED` copies columns but not indexes. They also
rename the old table's indexes aside first, since index names are unique
per schema and a surviving name makes `CREATE INDEX IF NOT EXISTS` a
silent no-op.
The new (api_key, startTime) index was in neither list, so an operator who
partitions (or unpartitions) after this migration lands gets a replacement
table without it, and Prisma will not recreate it: the migration is already
recorded as applied, and `migrate deploy` skips its drift sanity check when
there is nothing pending.
Verified on Postgres 18 against the shipped migration statements:
* unpatched partition script -> parent table has no api_key index, and
re-running the migration's own `CREATE INDEX IF NOT EXISTS` reports
success while being skipped, because the legacy table still owns the
name. The recovery an operator would reach for silently does nothing.
* patched -> index survives partitioning, propagates to every partition
(LiteLLM_SpendLogs_p*_api_key_startTime_idx) and to DEFAULT, is chosen
by the planner for the key+date-range query shape the endpoints use,
and survives the unpartition round-trip with all rows intact.
|
bugbot run |
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 4c18f55. Configure here.
|
Reviewed for LIT-6616, with focus on the migration path for installs that partitioned Scenario A — existing partitioned install, then this migration (the risky path): applied the pre-PR partition runbook (composite PK Scenario B — index already applied, then the updated partition runbook: the new rename-aside ( Scenario C — updated Also checked: all three One non-blocking doc nit: the "pre-create CONCURRENTLY" escape hatch in the PR body does not work as-is on already-partitioned installs ( LGTM — no blocking issues found; recommend merge. |
yuneng-berri
left a comment
There was a problem hiding this comment.
CREATE INDEX IF NOT EXISTS takes a SHARE lock on LiteLLM_SpendLogs for the entire build, which blocks every insert. The build also costs a full scan, which can take 30+ mins for large spend logs
|
@yuneng-berri this is unavoidable for this kind of indexing, we can make it up to end-user discretion by having it enabled by default & have a flag that is temporarily available for them to avoid this indexing (e.g. DB_MIGRATION_SKIP_INDEXING). This can be highlighted in release notes. Worst-case is that db migration is slow / fails without causing data loss. |
|
Hello @yuneng-berri @yassin-berriai, thanks for the attention on this PR. Our database was averaging 80% CPU today. We created the index ourselves to mitigate it, and it worked. @yuneng-berri you're right about the lock. The reason the migration uses the plain form is that So the lock only affects installs that let the migration build it. Both topologies can avoid it by pre-creating, after which the migration no-ops: Not partitioned: CREATE INDEX CONCURRENTLY IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx"
ON "LiteLLM_SpendLogs" (api_key, "startTime");Partitioned: CREATE INDEX "LiteLLM_SpendLogs_api_key_startTime_idx"
ON ONLY "LiteLLM_SpendLogs" (api_key, "startTime");
CREATE INDEX CONCURRENTLY "<partition>_api_key_startTime_idx"
ON "<partition>" (api_key, "startTime"); -- repeat per partition
ALTER INDEX "LiteLLM_SpendLogs_api_key_startTime_idx"
ATTACH PARTITION "<partition>_api_key_startTime_idx";The parent index becomes valid once every partition is attached. That's what we did — we're not partitioned, so ours was built concurrently, no lock. Happy to document both in the migration header. FYI there's a parallel Discord thread with @ryan-crabbe-berri on whether this is still needed after his rework. |
|
Prod follow-up. The plain index fixed the CPU but left most of the work in the heap — 29 buffers to find the rows, 1,416 to read CREATE INDEX CONCURRENTLY "LiteLLM_SpendLogs_api_key_startTime_spend_idx"
ON "LiteLLM_SpendLogs" (api_key, "startTime") INCLUDE (spend);1,445 → 40 buffers, 2.171 → 0.539 ms, index 25 → 27 MB. (PG 18, 240k rows / 175 MB heap, 276 keys.) Not sure what we should do for the PR: Prisma |
|
Thanks for the context, but I am still hesitant in merging the PR in its current state. Your database is 5.7GB, but we have users with Spend Logs exceeding 1 TB. We received pushback in the past about adding an index on Spend Logs, which is why I am being cautious. I will check internally with the user |
|
These users with a 1TB DB probably don't use the virtual-keys windows budget otherwise their DB would explode ;) |
yuneng-berri
left a comment
There was a problem hiding this comment.
I think this is good to merge, the long term benefits of this would outweigh the one time index creation
…_api_key_startTime_index # Conflicts: # litellm-proxy-extras/litellm_proxy_extras/schema.prisma # litellm/proxy/schema.prisma # schema.prisma
|
@yuneng-berri thanks for the merge. I am bringing a follow-up in emergency, the index need to have the INCLUDE part otherwise postgres optimizer might ignore it (see my comment above) This is my bad for not having keep my PR up to do with it after making this finding I apologize for it. Edit: Here is the follow-up: |
BerriAI#37983 added (api_key, startTime) so budget seeds and the spend report endpoints stop scanning every logged request. The seed in budget_window_spend_writer reads api_key, startTime and spend, so stopping at two columns leaves the payload in the heap, and api_key correlates at ~0 there: a key's rows sit roughly one per page. The planner answers with a bitmap heap scan that reads a page per matched row Carrying spend as a trailing key column makes the same seed an index-only scan. Measured on Postgres 16 over 1.5M rows and 300 keys, a 7 day window went from 1,695 buffers and 4.38 ms to 18 buffers and 0.56 ms INCLUDE (spend) reaches the same plan, but Prisma cannot express it: migrate diff reports the payload as drift and prisma db push strips it back off. A trailing key column measures identically, 71 MB either way, 26 MB of growth over 300k inserts, 63 MB of WAL, and the same 12,372 leaf and 59 internal pages, because suffix truncation keeps spend out of the pivot tuples BerriAI#37983 is unreleased, so no tagged version has built the two column index yet, and the migration drops it before building the replacement
|
For attribution, I reported and implemented this same index in #37167 on August 17, five days before this PR was opened |
|
Sorry @Neznakomec16, I did searched for an already opened PR before creating mine, and missed yours... Out of the 3k opened PR this was not intentional. I also reached to the maintainers via discord to get this prioritized maybe something you haven't done. |
TLDR
Problem this solves:
LiteLLM_SpendLogshas noapi_keyindex/spend/logs,/spend/logs/ui,/key/spend/report,/global/spend/reportall filter byapi_key+ date range, so each call scans every logged request on the instanceHow it solves it:
@@index([api_key, startTime])+ matching migration, mirroring the existing(startTime, request_id)compositeUser Flow
Before: auditing one key means scanning the whole instance's history
After: the same call answers from the key's own rows
Relevant issues
None found — surfaced while batch-reading per-key spend for 10,000 keys (that job: 20.5s -> 1.7s with this index).
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
Screenshots / Proof of Fix
Postgres 18,
LiteLLM_SpendLogswith 1.6M rows across 10k keys, query shape used by the endpoints above:Before (aae36f4)
After (555d5d5)
Type
🚄 Infrastructure
Caveats (if any)
CREATE INDEX IF NOT EXISTS(project style) briefly holds writes on very large tables — operators can pre-create the same nameCONCURRENTLYand the migration no-opsNote
Low Risk
Schema and migration-only; no application logic changes. Large tables may see brief write locking during index creation unless operators pre-build the index
CONCURRENTLY.Overview
Adds a composite database index on
LiteLLM_SpendLogs(api_key,startTime) so spend endpoints that filter by key and date range can use an index instead of scanning the full table.The change is declared in all three Prisma
LiteLLM_SpendLogsschemas and applied via a newlitellm_proxy_extrasmigration (CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx").partition_spend_logs.sqlandunpartition_spend_logs.sqlare updated to rename any existing index during table swap and recreate it on the rebuilt table, keeping partitioned installs in sync with Prisma-defined indexes.Reviewed by Cursor Bugbot for commit 4c18f55. Bugbot is set up for automated code reviews on this repo. Configure here.