Skip to content

perf(spend_tracking): index LiteLLM_SpendLogs by (api_key, startTime) - #37983

Merged
yuneng-berri merged 3 commits into
BerriAI:mainfrom
etiennechabert:litellm_add_spendlogs_api_key_startTime_index
Sep 17, 2026
Merged

yuneng-berri merged 3 commits into
BerriAI:mainfrom
etiennechabert:litellm_add_spendlogs_api_key_startTime_index

Conversation

@etiennechabert

@etiennechabert etiennechabert commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • LiteLLM_SpendLogs has no api_key index
  • /spend/logs, /spend/logs/ui, /key/spend/report, /global/spend/report all filter by api_key + date range, so each call scans every logged request on the instance

How it solves it:

  • adds @@index([api_key, startTime]) + matching migration, mirroring the existing (startTime, request_id) composite

User Flow

Before: auditing one key means scanning the whole instance's history

  1. Admin calls GET https://litellm-domain/spend/logs?api_key=sk-... (or filters the UI logs page to one key)
  2. Response time grows with total instance traffic — measured 94 ms at 1.6M logged requests for a key owning 160 of them

After: the same call answers from the key's own rows

  1. Admin makes the same call
  2. Response in <1 ms at the same table size; time now tracks the key's own request count

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

  • I have added meaningful tests (index-only change — no behavioral surface to test)
  • The handful of test files covering my change pass locally (n/a — no code path changes)
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 (5/5 received)

Screenshots / Proof of Fix

Postgres 18, LiteLLM_SpendLogs with 1.6M rows across 10k keys, query shape used by the endpoints above:

SELECT COALESCE(SUM(spend),0) FROM "LiteLLM_SpendLogs"
WHERE api_key = $1 AND "startTime" >= now() - interval '7 days';

Before (aae36f4)

->  Parallel Seq Scan on "LiteLLM_SpendLogs"  (actual time=3.739..69.066 rows=53 loops=3)
Execution Time: 93.883 ms

After (555d5d5)

->  Bitmap Index Scan on "LiteLLM_SpendLogs_api_key_startTime_idx"
      Index Cond: ((api_key = $1) AND ("startTime" >= (now() - '7 days'::interval)))
Execution Time: 0.7 ms  (~140x)

Type

🚄 Infrastructure

Caveats (if any)

  • no new tests: one index, no code path; schema-sync CI covers the three prisma copies
  • plain CREATE INDEX IF NOT EXISTS (project style) briefly holds writes on very large tables — operators can pre-create the same name CONCURRENTLY and the migration no-ops

Note

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_SpendLogs schemas and applied via a new litellm_proxy_extras migration (CREATE INDEX IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx"). partition_spend_logs.sql and unpartition_spend_logs.sql are 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.

@greptile-apps

greptile-apps Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds a composite (api_key, startTime) index for spend-log queries and preserves it when converting the spend-log table between partitioned and unpartitioned forms

  • Updates all three Prisma schema copies
  • Adds the matching idempotent SQL migration
  • Updates both partition conversion scripts to rename and recreate the index

Confidence Score: 5/5

The PR appears safe to merge

No blocking failure remains

Important Files Changed

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

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing etiennechabert:litellm_add_spendlogs_api_key_startTime_index (9207c9a) with main (dc81cf5)

Open in CodSpeed

@CLAassistant

CLAassistant commented Aug 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@etiennechabert
etiennechabert force-pushed the litellm_add_spendlogs_api_key_startTime_index branch from 60af4db to 871e8a6 Compare August 23, 2026 09:49
@etiennechabert

Copy link
Copy Markdown
Contributor Author

Load-test evidence: this index is load-bearing for budget_limits windows at fleet scale

Keys with budget_limits re-check each window's spend against LiteLLM_SpendLogs on the request path (_virtual_key_multi_budget_check → get_current_spend → SpendCounterReseed.window_from_spend_logs), cached in-process for only 5 s (SPEND_DB_FLOOR_CACHE_TTL_SECONDS). Once per-key inter-request gaps exceed 5 s, every request pays one aggregate per window — measured exactly 3/request with 1h/1d/7d windows; a control fleet without budget_limits produced zero. This makes the missing api_key index a tax that scales with keys × traffic × pods.

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:

keys rows no index: per query / p95 TTFB / outcome indexed: per query / p95
1,000 161k 5.9 ms / 65 ms / ok 0.06 ms / 29 ms
2,500 392k 20 ms / 200 ms / degrading 0.12 ms / 31 ms
5,000 773k 116 ms / 1.2 s / DB-bound (8.7 AAS) 0.14 ms / 39 ms
10,000 1.53M 241 ms / 61.6 s / 49% timeouts 0.15 ms / 42 ms

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).

@etiennechabert

Copy link
Copy Markdown
Contributor Author

@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.
@etiennechabert
etiennechabert force-pushed the litellm_add_spendlogs_api_key_startTime_index branch from 29b9f3b to 1bdc1b9 Compare August 30, 2026 22:46
@etiennechabert

Copy link
Copy Markdown
Contributor Author

Hello @mateo-berri, again sorry for tagging you, I see you have been one of the most active contributor lately.
Could you please help me to get attention on this PR and potentially it merged?

This missing index is causing our database to be burning all day long 🙏

@seanyasno-af

Copy link
Copy Markdown
Contributor

@greptile review

@seanyasno-af

Copy link
Copy Markdown
Contributor

@cursor review

Comment thread schema.prisma Resolved
…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.
@yassin-berriai

Copy link
Copy Markdown
Contributor

bugbot run

@yassin-berriai

Copy link
Copy Markdown
Contributor

@greptileai

@cursor cursor Bot 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.

✅ 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.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Reviewed for LIT-6616, with focus on the migration path for installs that partitioned LiteLLM_SpendLogs via db_scripts/partition_spend_logs.sql (the LIT-6138 interaction). Verified live at head 4c18f55 on Postgres 14, seeded tables:

Scenario A — existing partitioned install, then this migration (the risky path): applied the pre-PR partition runbook (composite PK (request_id, startTime)), backfilled, then ran 20260823000000_add_spend_logs_api_key_starttime_index/migration.sql. CREATE INDEX IF NOT EXISTS succeeds on the partitioned parent and cascades to partitions; planner uses LiteLLM_SpendLogs_pdefault_api_key_startTime_idx (bitmap index scan, Index Cond on both columns). The migration never touches the PK, so it does not trip the LIT-6138 failure mode; prisma migrate deploy remains the supported path and this hand-written idempotent SQL applies cleanly on partitioned installs.

Scenario B — index already applied, then the updated partition runbook: the new rename-aside (..._legacy_api_key_startTime_idx) prevents the IF NOT EXISTS silent-skip trap, and the canonical index is recreated on the partitioned parent. Confirmed the Bugbot finding from 1bdc1b9 is fully addressed in 4c18f55.

Scenario C — updated unpartition_spend_logs.sql round-trip: completes cleanly, all rows preserved, canonical index present on the plain table.

Also checked: all three schema.prisma copies carry the identical @@index([api_key, startTime]); index name (39 chars) is within Postgres's 63-char limit including the runbooks' renamed variants; migration folder timestamp 20260823000000 sorts before already-shipped 20260824000000+ migrations, which is fine since migrate deploy applies any pending migration regardless of name ordering.

One non-blocking doc nit: the "pre-create CONCURRENTLY" escape hatch in the PR body does not work as-is on already-partitioned installs (CREATE INDEX CONCURRENTLY is not supported on a partitioned parent) — operators there would need per-partition concurrent builds + ATTACH. Not worth blocking an index-only change over.

LGTM — no blocking issues found; recommend merge.

@yuneng-berri yuneng-berri 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.

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

@yassin-berriai

Copy link
Copy Markdown
Contributor

@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.

@etiennechabert

Copy link
Copy Markdown
Contributor Author

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 CREATE INDEX CONCURRENTLY fails on a partitioned parent (cannot create index on partitioned table ... concurrently, still true on PG 18), and IF NOT EXISTS doesn't rescue it — the partition check fires first. Since partition_spend_logs.sql means some installs are partitioned, a CONCURRENTLY migration would be unapplicable there rather than just slow.

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.
TL;DR: the rework helps a lot but the index still makes sense IMO.

@etiennechabert

Copy link
Copy Markdown
Contributor Author

Prod follow-up. The plain index fixed the CPU but left most of the work in the heap — api_key correlation ≈ −0.007, so a key's rows sit ~1 per page:

Bitmap Heap Scan   Heap Blocks: exact=1416   Buffers: shared hit=1445
  Bitmap Index Scan on "..._api_key_startTime_idx"   Buffers: shared hit=29
Execution Time: 2.171 ms

29 buffers to find the rows, 1,416 to read spend. Adding the payload makes it index-only:

CREATE INDEX CONCURRENTLY "LiteLLM_SpendLogs_api_key_startTime_spend_idx"
    ON "LiteLLM_SpendLogs" (api_key, "startTime") INCLUDE (spend);
Index Only Scan   Heap Fetches: 8   Buffers: shared hit=40
Execution Time: 0.539 ms

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 @@index can't express INCLUDE, and the payload only helps the budget aggregate while the plain index serves every api_key consumer.

@yuneng-berri

Copy link
Copy Markdown
Contributor

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

@etiennechabert

Copy link
Copy Markdown
Contributor Author

These users with a 1TB DB probably don't use the virtual-keys windows budget otherwise their DB would explode ;)
But I understand the concerns, on our side it's not an emergency anymore, we created the index by hand and our DB is now very chill.
Thanks for the great product you built 🚀

@yuneng-berri yuneng-berri 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.

I think this is good to merge, the long term benefits of this would outweigh the one time index creation

@yuneng-berri
yuneng-berri changed the base branch from litellm_internal_staging to main September 17, 2026 19:14
…_api_key_startTime_index

# Conflicts:
#	litellm-proxy-extras/litellm_proxy_extras/schema.prisma
#	litellm/proxy/schema.prisma
#	schema.prisma
@yuneng-berri
yuneng-berri merged commit dbc6c1c into BerriAI:main Sep 17, 2026
95 checks passed
@etiennechabert

etiennechabert commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@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:
#41816

etiennechabert pushed a commit to etiennechabert/litellm that referenced this pull request Sep 18, 2026
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
@Neznakomec16

Copy link
Copy Markdown

For attribution, I reported and implemented this same index in #37167 on August 17, five days before this PR was opened

@etiennechabert

Copy link
Copy Markdown
Contributor Author

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.

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.

6 participants