Skip to content

fix(schema): index LiteLLM_SpendLogs on (api_key, startTime) - #37167

Closed
Neznakomec16 wants to merge 11 commits into
BerriAI:mainfrom
Neznakomec16:add-spendlogs-api-key-starttime-index
Closed

Neznakomec16 wants to merge 11 commits into
BerriAI:mainfrom
Neznakomec16:add-spendlogs-api-key-starttime-index

Conversation

@Neznakomec16

@Neznakomec16 Neznakomec16 commented Aug 17, 2026 •

Copy link
Copy Markdown

Status

main already contains this index via 1bdc1b9b17. The branch is synced with main and has no remaining diff

Problem

SpendCounterReseed.window_from_spend_logs() (litellm/proxy/db/spend_counter_reseed.py) recomputes a budget-window spend counter straight from the raw spend logs:

await SpendLogsRepository(prisma_client).table.group_by(
    by=[group_field],                       # "api_key"
    where=where,                            # {"api_key": ..., "startTime": {"gte": window_start}}
    sum={"spend": True},
)

which reaches Postgres as:

SELECT api_key, SUM(spend) FROM "LiteLLM_SpendLogs"
WHERE api_key = $1 AND "startTime" >= $2
GROUP BY api_key

LiteLLM_SpendLogs has no index that covers this predicate — the closest is @@index([startTime]). So Postgres scans the entire time window and drops every row that belongs to a different key. Cost therefore scales with total traffic in the window rather than with the key's own traffic, and grows with the length of the budget window.

On a deployment with a spend-log table in the 10^7-row range and a 30-day window, we measured a single such call at ~97 seconds, discarding >99% of the rows it read. Because the Prisma Python client's default HTTP timeout is 30s (prisma/http_abstract.py), calls past that threshold surface as httpx.ReadTimeout instead of slow-but-successful queries, and the retries make the user-visible latency land on multiples of ~30s.

Fix

Add @@index([api_key, startTime]) to LiteLLM_SpendLogs (both schema.prisma copies) plus the corresponding migration.

Measurements

Same query, same 30-day window, same key, before and after (identifiers parameterised, absolute call counts omitted):

-- Before
GroupAggregate  (actual time=96692.790..96693.024 rows=1 loops=1)
  Buffers: shared hit=3559452 read=945268
  ->  Parallel Index Scan using "LiteLLM_SpendLogs_startTime_idx" on "LiteLLM_SpendLogs"
        Index Cond: ("startTime" >= $2)
        Filter: (api_key = $1)
        Rows Removed by Filter: 3844217
Execution Time: 96693.124 ms

-- After
GroupAggregate  (actual time=369.557..369.559 rows=1 loops=1)
  Buffers: shared hit=67236 read=12103
  ->  Index Only Scan using "LiteLLM_SpendLogs_api_key_startTime_idx" on "LiteLLM_SpendLogs"
        Index Cond: ((api_key = $1) AND ("startTime" >= $2))
        Heap Fetches: 63040
Execution Time: 369.592 ms

Roughly three orders of magnitude in execution time and ~57x fewer buffers touched. Index size was ~780 MB for that table.

To be precise about what was measured: the "After" plan comes from a local variant of the index that adds INCLUDE (spend), which is why it reports Index Only Scan. Prisma cannot express covering indexes, so this PR ships the plain two-column index. That one produces the same key-bounded index scan — the win here is not reading rows of other keys — with a heap fetch per matched row instead of the covering shortcut.

Note for operators of large tables

The migration uses plain CREATE INDEX (matching the convention of the existing migrations, and required because Prisma runs migrations inside a transaction where CONCURRENTLY is not allowed). On a large, busy LiteLLM_SpendLogs that takes a write lock for the duration of the build. Operators can avoid it by creating the index ahead of the upgrade:

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

The migration's IF NOT EXISTS then makes it a no-op.

Related, not addressed here

The reseed is described as coalesced and cache-backed, yet in our deployment it ran often enough to dominate total database time — so the counter cache appears not to hold in a multi-worker setup. There is also a broader question of why the budget window is recomputed from raw spend logs at all when daily aggregate tables (LiteLLM_DailyUserSpend, LiteLLM_DailyTeamSpend, ...) are maintained alongside. Both feel like separate issues; happy to open one if maintainers agree.

milan-berri and others added 2 commits July 28, 2026 14:14
…ticated requests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…stency

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds a composite (api_key, startTime) index to accelerate spend-log budget-window aggregation

  • Adds the index to the root and proxy-extras Prisma schemas
  • Adds a PostgreSQL migration using CREATE INDEX IF NOT EXISTS
  • Omits the runtime proxy schema copy, leaving the repository schemas inconsistent

Confidence Score: 4/5

The missing runtime schema update should be fixed before merging so schema generation and drift checks agree with the migration

The database migration creates the index, but litellm/proxy/schema.prisma remains out of sync with both changed schema copies

Files Needing Attention: litellm/proxy/schema.prisma, schema.prisma

Important Files Changed

Filename Overview
schema.prisma Adds the intended composite index, but the corresponding runtime proxy schema was not synchronized
litellm-proxy-extras/litellm_proxy_extras/schema.prisma Correctly adds the composite index to the migration-generation schema, while exposing inconsistency with the unchanged proxy schema
litellm-proxy-extras/litellm_proxy_extras/migrations/20260817120000_add_spendlogs_api_key_starttime_idx/migration.sql Adds the matching PostgreSQL index with an idempotent CREATE INDEX statement

Reviews (1): Last reviewed commit: "fix(schema): index LiteLLM_SpendLogs on ..." | Re-trigger Greptile

Comment thread schema.prisma Resolved
@codecov

codecov Bot commented Aug 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@Neznakomec16
Neznakomec16 changed the base branch from main to litellm_internal_staging August 17, 2026 11:13
@Neznakomec16
Neznakomec16 requested a review from a team August 17, 2026 11:13
The budget-window spend counter is recomputed from raw spend logs in
SpendCounterReseed.window_from_spend_logs (litellm/proxy/db/spend_counter_reseed.py),
which issues

    SELECT api_key, SUM(spend) FROM "LiteLLM_SpendLogs"
    WHERE api_key = $1 AND "startTime" >= $2 GROUP BY api_key

No index covers this predicate: the only usable one is on startTime alone, so the
scan reads the whole time window and discards every row belonging to another key.
Cost therefore scales with total traffic in the window rather than with the key's
own traffic. On a table in the 10^7-row range this takes tens of seconds, and past
the Prisma client's 30s default timeout it surfaces as httpx.ReadTimeout plus
retries rather than a slow query.

Adding (api_key, startTime) turns it into an index scan bounded by the key.
@Neznakomec16
Neznakomec16 force-pushed the add-spendlogs-api-key-starttime-index branch from fcb832c to e96d4a0 Compare August 17, 2026 11:19
@CLAassistant

CLAassistant commented Aug 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
3 out of 4 committers have signed the CLA.

✅ Neznakomec16
✅ ryan-crabbe-berri
✅ milan-berri
❌ yassin-berriai
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing Neznakomec16:add-spendlogs-api-key-starttime-index (d1a108d) with litellm_internal_staging (252c71c)

Open in CodSpeed

milan-berri and others added 2 commits August 21, 2026 02:41
…nd Model Hub UI

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…mutation

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
yassin-berriai and others added 5 commits September 13, 2026 09:44
…ow read fails

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…iption

feat(model_hub): surface model_info.description in Model Hub
…ip_save_on_failed_read

fix(health): skip background health check DB writes when the latest-row read fails
feat(dd_span_tagger): emit litellm.user_email span tag for JWT-authenticated requests
…arttime-index

Keep both new SpendLogs indexes: upstream's litellm_call_id and this
branch's composite (api_key, startTime).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:04
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