Repository navigation
perf(db): index SpendLogs on (user, startTime), (api_key, startTime) - #39301
michelligabriele wants to merge 1 commit into
Conversation
Greptile SummaryThe PR adds composite descending-time indexes for user- and API-key-filtered spend-log queries, keeping all Prisma schema copies and migration SQL aligned.
Confidence Score: 5/5The PR appears safe to merge, with the operational cost of blocking index builds explicitly documented and supported by a pre-creation escape hatch. The schema copies, migration definitions, and partition conversion scripts agree on index names, column order, and sort direction, while the added tests exercise both ordinary and partitioned table shapes; no actionable defect remains.
|
| Filename | Overview |
|---|---|
| litellm-proxy-extras/litellm_proxy_extras/migrations/20260902000000_add_spend_logs_user_start_time_idx/migration.sql | Adds an idempotent composite user/time index and documents the intentional blocking-build tradeoff. |
| litellm-proxy-extras/litellm_proxy_extras/migrations/20260902000100_add_spend_logs_api_key_start_time_idx/migration.sql | Adds the matching idempotent API-key/time index with the same deployment constraints. |
| db_scripts/partition_spend_logs.sql | Renames prior canonical indexes and recreates both composite indexes on the partitioned replacement table. |
| db_scripts/unpartition_spend_logs.sql | Preserves both composite indexes while converting the partitioned table back to a plain table. |
| schema.prisma | Declares both composite indexes in the root Prisma schema, consistently with the migration SQL. |
| tests/proxy_migration_tests/test_db_schema_migration.py | Adds isolated PostgreSQL tests validating migration applicability, partitioned-parent support, and expected index-backed plans. |
Reviews (1): Last reviewed commit: "perf(db): index SpendLogs on (user, star..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
e414c8f to
94b6d06
Compare
|
this is a duplicate of this #37983 |
TLDR
Problem this solves:
LiteLLM_SpendLogshas no index led by"user"orapi_keyHow it solves it:
("user", "startTime" DESC)and("api_key", "startTime" DESC)User Flow
Before: an admin filtering the Logs page by one user over a week gets an error instead of results
https://litellm-domain/ui/?page=logs, set the user filter to a single user id and the date range to 1 day — the table loads normallyGET https://litellm-domain/spend/logs/v2?user_id=<id>&start_date=2026-08-01&end_date=2026-08-08&page=1&page_size=50, returns500with a database read timeoutAfter: the same 7-day filter returns the page
https://litellm-domain/ui/?page=logs, set the user filter to a single user id and the date range to 1 day — the table loads normallyGET https://litellm-domain/spend/logs/v2?user_id=<id>&start_date=2026-08-01&end_date=2026-08-08&page=1&page_size=50returns200with the first 50 rows and a total count200, and takes about as long as the 1-day request didRelevant issues
Same class of gap,
api_keyhalf only, all still unmerged: #37983, #37167, #37379.Linear ticket
Pre-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 more@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
This one is not visible through a response body — the endpoint returns the same JSON either way, it
just stops timing out — so the proof is the query plan, same framing as #37379. Plan shape and buffer
counts are hardware-independent; the millisecond figures come from a small test box and are there for
scale only.
Shared setup, identical on both sides: Postgres 16.12, a
LiteLLM_SpendLogsclone seeded with 400,000rows over a 30-day window across 1,200 users, then
ANALYZE. One user (user-0) holds 75 rows insidethe 7-day window measured; a second (
whale) holds 13,421, i.e. above the query'sLIMIT 10001cap.The statement measured is exactly what
ui_view_spend_logsemits forGET /spend/logs/v2?user_id=…&start_date=…&end_date=…&page=1&page_size=50, run throughEXPLAIN (ANALYZE, BUFFERS)withplan_cache_mode = force_custom_plan.Before (31ca4dd)
Count, one user, window widened 1 → 30 days
EXPLAIN (ANALYZE, BUFFERS)the bounded count at each window width:startTime_idx+FilterThe 7-day plan, in full:
Filter, after the fact — 93,519 rows read to return 75.LIMIT 10001neverfires because the user does not have that many rows, so nothing stops the scan early.
Control: the same window for a user above the LIMIT cap
user = 'whale'(13,421 rows in range):user-0and costs less — 7,853 buffers vs 10,501 — because theLIMITshort-circuits for it. Table size and DB health are the same in both runs; the onlyvariable is how selective the filter is.
Page fetch, one user
Sort(quicksort,Sort Key: "startTime" DESC) over the same Bitmap Heap Scan —Buffers: shared hit=10504, 47.3 ms.Index Scan Backward using "LiteLLM_SpendLogs_startTime_idx"+Filter: ("user" = 'user-0'),Rows Removed by Filter: 70291,Buffers: shared hit=70820, 60.9 ms.Count, one API key
api_key = 'key-7'(461 rows in range): Bitmap Heap Scan onstartTime_idx,Filter: (api_key = 'key-7'::text),Rows Removed by Filter: 93058,Buffers: shared hit=10501,40.2 ms.
Buffers: shared hit=10215, 31.8 ms.After (94b6d06)
ANALYZE:Both build plainly, no
CONCURRENTLY. Index sizes against an 80 MB heap: 18 MB for theuserindex, 16 MB for the
api_keyindex — about 47 and 42 bytes per row.Count, one user, window widened 1 → 30 days
Same
EXPLAIN (ANALYZE, BUFFERS)at each window width:Index Only ScanonLiteLLM_SpendLogs_user_startTime_idxThe 7-day plan, in full:
Index Cond. There is noFilternode and no heap access at all(
Heap Fetches: 0). Cost is flat from 1 day to 30 days, which is the actual fix: the query stopscaring how wide the window is.
Control: the same window for a user above the LIMIT cap
user = 'whale':Index Only Scanon the new index, 54 buffers, 5.6 ms(from 7,853 buffers / 39.9 ms). It still stops at 10,001 rows; it just reaches them through
the index now.
Page fetch, one user
Index Scan using "LiteLLM_SpendLogs_user_startTime_idx", noSortnode,Buffers: shared hit=53, 0.24 ms (from 10,504 buffers / 47.3 ms).DESCsecondcolumn is what removes the sort — the index already delivers
ORDER BY "startTime" DESC.Count, one API key
Index Only Scan using "LiteLLM_SpendLogs_api_key_startTime_idx",Buffers: shared hit=7, 0.21 ms (from 10,501 buffers / 40.2 ms).Test suite
DATABASE_URL=… uv run pytest tests/proxy_migration_tests/test_db_schema_migration.py tests/proxy_migration_tests/test_replica_identity_full.py -v→12 passed.test_schema_migration_in_syncis the definition pin: it deploys all 165 migrations andprisma migrate diffs the result againstschema.prisma, so it fails if the migration SQL and the@@indexdeclarations ever disagree on name, column order, orDESC.expected exactly one migration creating LiteLLM_SpendLogs_user_startTime_idx, found 0.One caveat on reading the Before table honestly: buffer counts plateau at ~10,215 from 7 days on
because that is the entire heap of a 400k-row test table — the scan saturates and cannot grow further.
The linear term is in rows examined (13k → 40k → 93k) and time (16.9 → 26.9 → 46.6 ms) over 1–7 days.
On a real deployment nothing saturates, and rows there are far fatter than these seeded ones, so this
is a floor on the effect rather than a ceiling. #37167 measured 96.7 s → 0.37 s for the
api_keyhalfat 10^7 rows.
Type
🐛 Bug Fix
🚄 Infrastructure
Caveats (if any)
Severe
CONCURRENTLY— deliberate, see belowSHARElock onLiteLLM_SpendLogsLiteLLM_SpendLogs_user_startTime_idx,LiteLLM_SpendLogs_api_key_startTime_idx.IF NOT EXISTSthen makes both migrations no-ops.CREATE INDEX CONCURRENTLYATTACH PARTITION INDEXCONCURRENTLYin the migration: Postgres rejects it on a partitioned parent, and inside thetransaction
prisma migrate deployruns each migration in. This is what forced a revision of perf(db): index LiteLLM_SpendLogs on (api_key, startTime) #37379.Medium
api_keyhalf hereLow
already applied it. Harmless; drop by hand if unwanted.
db_scripts/partition_spend_logs.sqlandunpartition_spend_logs.sqlhad to learn both index namestoo —
LIKE … INCLUDING DEFAULTSdoes not copy indexes, and index names are unique per schema, sowithout the rename-aside the recreate would be silently skipped by
IF NOT EXISTSFinal Attestation