Skip to content

perf(spend_tracking): cover spend in the LiteLLM_SpendLogs api_key index - #41816

Open
etiennechabert wants to merge 2 commits into
BerriAI:mainfrom
etiennechabert:litellm_spendlogs_api_key_index_cover_spend
Open

etiennechabert wants to merge 2 commits into
BerriAI:mainfrom
etiennechabert:litellm_spendlogs_api_key_index_cover_spend

Conversation

@etiennechabert

@etiennechabert etiennechabert commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • Adds spend to the index: @@index([api_key, startTime, spend])
  • Per-key spend sums become index-only scans
  • spend is a key column because Prisma @@index can't express INCLUDE

User Flow

Before: each budget-window check on a key re-reads one table page per request that key made in the window

  1. Admin issues keys with windowed budgets via POST https://litellm-domain/key/generate (budget_limits with 1h / 1d / 7d windows)
  2. Those keys serve POST https://litellm-domain/v1/chat/completions traffic
  3. Each window check sums the key's spend and touches ~1,445 pages (1,416 of them table pages) on our production data

After: the same check is answered from the index alone

  1. Admin issues the same keys via POST https://litellm-domain/key/generate
  2. Those keys serve the same POST https://litellm-domain/v1/chat/completions traffic
  3. Each window check touches ~40 pages, 2.17 ms -> 0.54 ms on the same production data (measurement)

Relevant issues

Follow-up to #37983

Affected release

Linear ticket

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 before requesting a maintainer review

Screenshots / Proof of Fix

Shared setup: Postgres 18.4, LiteLLM_SpendLogs created by prisma migrate deploy from this repo's migrations, 1.5M rows across 10k keys (64-char hashed keys, 600-byte payload per row, inserted in time order, api_key correlation 0.003), VACUUM ANALYZE. Query shape of the budget-window reseed and seeding reads:

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

Before (8fc9c46)

Per-key 7-day spend sum

  1. Index (api_key, startTime), 151 MB
  2. EXPLAIN (ANALYZE, BUFFERS):
Aggregate
  Buffers: shared hit=88
  ->  Bitmap Heap Scan on "LiteLLM_SpendLogs"  (rows=83)
        Heap Blocks: exact=83
        ->  Bitmap Index Scan on "LiteLLM_SpendLogs_api_key_startTime_idx"
              Buffers: shared hit=5

Upgrade from a stable release

  1. DB at v1.101.0 migrations, then prisma migrate deploy
  2. Applies 20260823000000, builds (api_key, startTime)

Upgrade from v1.103.0-dev.2

  1. DB already applied the original 20260823000000
  2. prisma migrate deploy: nothing pending, index stays (api_key, startTime)

Partitioned install, upgrade from a stable release

  1. DB at v1.101.0 migrations, partitioned with partition_spend_logs.sql, then prisma migrate deploy
  2. Applies 20260823000000; (api_key, startTime) on the parent and every partition

Partitioned install, upgrade from v1.103.0-dev.2

  1. Partitioned DB already applied the original 20260823000000
  2. prisma migrate deploy: nothing pending, index stays (api_key, startTime)

Partition / unpartition runbooks

  1. Both runbooks carry (api_key, startTime)

After (3df010c)

Per-key 7-day spend sum

  1. Index (api_key, startTime, spend), 163 MB
  2. EXPLAIN (ANALYZE, BUFFERS):
Aggregate
  Buffers: shared hit=8
  ->  Index Only Scan using "LiteLLM_SpendLogs_api_key_startTime_spend_idx" on "LiteLLM_SpendLogs"  (rows=83)
        Heap Fetches: 0
        Buffers: shared hit=8
  1. Same data with (api_key, startTime) INCLUDE (spend) instead: identical plan, 8 buffers, 163 MB

Upgrade from a stable release

  1. DB at v1.101.0 migrations, then prisma migrate deploy
  2. Applies 20260823000000 and 20260918120000; one index is built: (api_key, startTime, spend)
  3. prisma migrate diff --from-url ... --to-schema-datamodel schema.prisma: no LiteLLM_SpendLogs drift

Upgrade from v1.103.0-dev.2

  1. DB already applied the original 20260823000000
  2. prisma migrate deploy exits 0 and applies 20260918120000
  3. Index is now (api_key, startTime, spend); (api_key, startTime) is gone; no drift

Partitioned install, upgrade from a stable release

  1. DB at v1.101.0 migrations, partitioned with partition_spend_logs.sql, then prisma migrate deploy
  2. Applies 20260823000000 and 20260918120000; (api_key, startTime, spend) on the parent and LiteLLM_SpendLogs_pdefault

Partitioned install, upgrade from v1.103.0-dev.2

  1. Partitioned DB already applied the original 20260823000000
  2. prisma migrate deploy exits 0 and applies 20260918120000
  3. Parent and LiteLLM_SpendLogs_pdefault now carry (api_key, startTime, spend); the old index is gone

Partition / unpartition runbooks

  1. partition_spend_logs.sql: covering index on the parent, LiteLLM_SpendLogs_pdefault, and the renamed legacy table
  2. unpartition_spend_logs.sql: covering index on the rebuilt table, all rows kept

Type

🚄 Infrastructure

Caveats (if any)

Severe

CREATE INDEX CONCURRENTLY IF NOT EXISTS "LiteLLM_SpendLogs_api_key_startTime_spend_idx"
    ON "LiteLLM_SpendLogs" (api_key, "startTime", spend);
DROP INDEX CONCURRENTLY IF EXISTS "LiteLLM_SpendLogs_api_key_startTime_idx";

Medium

  • 20260823000000 is edited after merge, so stable upgrades pay one build, not two
    • it has only shipped in v1.103.0-dev.2 (proxy-extras 0.4.99), no stable release
    • prisma migrate deploy doesn't re-check applied files; verified above
    • prisma migrate dev on a contributor DB that applied it will flag it as modified

Low

  • Index grows ~8% (151 -> 163 MB here, 25 -> 27 MB on our production data)
  • Only spend is covered: token sums in /global/spend/report also group by model
  • A hand-built INCLUDE (spend) index under the new name is kept; Prisma reports no drift for it

The per-key window aggregates that the (api_key, startTime) index from
BerriAI#37983 was added for all read SUM(spend) WHERE api_key = ... AND
"startTime" >= ... (budget-window reseed, BudgetWindowSpend seeding, the
spend-logs fallback). api_key has ~zero physical correlation, so a key's
rows sit about one per heap page and the plain index still pays one heap
page per matching row just to read spend. Carrying spend in the index
makes those sums index-only scans.

spend is a trailing key column rather than INCLUDE (spend) because
Prisma's @@index cannot express INCLUDE. Postgres answers the same query
from either shape with an identical plan and index size.

20260823000000 has not reached a stable release yet, so it now builds the
covering index directly: installs upgrading from a stable release pay for
one index build on LiteLLM_SpendLogs, not two. 20260918120000 moves
installs that already applied the original file (v1.103.0-dev.2) over,
creating the covering index before dropping the old one, and is a no-op
everywhere else. The partition runbooks carry the new name and columns.

Verified on Postgres 18 with `prisma migrate deploy`:
  * stable upgrade: both migrations apply, one covering index, no drift
  * dev.2 upgrade: deploy accepts the edited 20260823000000, the new
    migration swaps the plain index for the covering one, no drift
  * partition/unpartition runbooks keep the covering index on the parent,
    the DEFAULT partition, and the round-tripped table

1.5M rows / 10k keys / 64-char hashed keys: 88 -> 8 buffers per key
aggregate, index 151 MB -> 163 MB.
@codspeed

codspeed Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing etiennechabert:litellm_spendlogs_api_key_index_cover_spend (3df010c) with main (8fc9c46)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no actionable new issue remains, and the previously reported blocking-build concern was manually resolved after its compatibility constraint and mitigation were documented.

Summary

This PR extends the LiteLLM_SpendLogs API-key/time index with spend, allowing windowed per-key spend aggregation to use an index-only scan.

  • Keeps all three Prisma schema copies aligned.
  • Updates fresh-install, previously migrated, partition, and unpartition paths to use the covering index.
  • Documents why the compatibility migration cannot use CONCURRENTLY for partitioned installations and how operators can pre-create the index.

Reviews (2) · Last reviewed commit: "docs(migrations): explain why the spend ..."

Postgres rejects CREATE INDEX CONCURRENTLY on a partitioned table even
with IF NOT EXISTS and the index already present (verified on 18.4), so a
concurrent build would fail 20260918120000 on every partitioned install,
including stable upgrades where 20260823000000 already built the index.
Record that, and the pre-create escape hatch, next to the statement.
@codecov

codecov Bot commented Sep 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@etiennechabert

Copy link
Copy Markdown
Contributor Author

@greptileai

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.

1 participant