Skip to content

perf(db): index SpendLogs on (user, startTime), (api_key, startTime) - #39301

Closed
michelligabriele wants to merge 1 commit into
litellm_internal_stagingfrom
litellm_spendlogs_user_api_key_index
Closed

michelligabriele wants to merge 1 commit into
litellm_internal_stagingfrom
litellm_spendlogs_user_api_key_index

Conversation

@michelligabriele

@michelligabriele michelligabriele commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • LiteLLM_SpendLogs has no index led by "user" or api_key
  • Filtering spend logs by one user scans the whole date range
  • Cost grows with the window width, not the result size
  • Wide windows blow the DB read timeout and return 500
  • Same gap makes the Logs tab's key filter slow

How it solves it:

  • Adds ("user", "startTime" DESC) and ("api_key", "startTime" DESC)
  • Declared in the schema, shipped as two migrations
  • Count becomes an index-only scan, flat across window widths
  • Page query also loses its sort step
  • Partition and unpartition runbooks carry both indexes

User Flow

Before: an admin filtering the Logs page by one user over a week gets an error instead of results

  1. They open 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 normally
  2. They widen the same filter to 7 days
  3. The page fails to load; the request behind it, GET https://litellm-domain/spend/logs/v2?user_id=<id>&start_date=2026-08-01&end_date=2026-08-08&page=1&page_size=50, returns 500 with a database read timeout
  4. Narrowing back to 1–2 days works again, so what breaks it is how wide the date range is, not how many rows that user actually has
  5. The same widening breaks the API-key filter on the same page

After: the same 7-day filter returns the page

  1. They open 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 normally
  2. They widen the same filter to 7 days
  3. GET https://litellm-domain/spend/logs/v2?user_id=<id>&start_date=2026-08-01&end_date=2026-08-08&page=1&page_size=50 returns 200 with the first 50 rows and a total count
  4. Widening further to 30 days still returns 200, and takes about as long as the 1-day request did
  5. The API-key filter on the same page behaves the same way

Relevant issues

Same class of gap, api_key half 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • 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 (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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_SpendLogs clone seeded with 400,000
rows over a 30-day window across 1,200 users, then ANALYZE. One user (user-0) holds 75 rows inside
the 7-day window measured; a second (whale) holds 13,421, i.e. above the query's LIMIT 10001 cap.
The statement measured is exactly what ui_view_spend_logs emits for
GET /spend/logs/v2?user_id=…&start_date=…&end_date=…&page=1&page_size=50, run through
EXPLAIN (ANALYZE, BUFFERS) with plan_cache_mode = force_custom_plan.

Before (31ca4dd)

Count, one user, window widened 1 → 30 days

  1. EXPLAIN (ANALYZE, BUFFERS) the bounded count at each window width:

    Window Plan Rows discarded Rows returned Buffers Time
    1 day Bitmap Heap Scan on startTime_idx + Filter 13,325 16 7,557 16.9 ms
    3 days same 40,352 31 10,189 26.9 ms
    7 days same 93,444 75 10,501 46.6 ms
    14 days Parallel Seq Scan 133,286 /worker 48 10,215 36.8 ms
    30 days Parallel Seq Scan 133,238 /worker 95 10,215 38.0 ms
  2. The 7-day plan, in full:

 Aggregate  (actual time=46.6..46.6 rows=1 loops=1)
   ->  Limit  (actual time=10.001..46.556 rows=75 loops=1)
         ->  Bitmap Heap Scan on "LiteLLM_SpendLogs"  (actual time=10.001..46.556 rows=75 loops=1)
               Recheck Cond: (("startTime" >= '2026-08-01') AND ("startTime" <= '2026-08-08'))
               Filter: ("user" = 'user-0'::text)
               Rows Removed by Filter: 93444
               Buffers: shared hit=10501
               ->  Bitmap Index Scan on "LiteLLM_SpendLogs_startTime_idx"  (rows=93519 loops=1)
  1. The work is done by Filter, after the fact — 93,519 rows read to return 75. LIMIT 10001 never
    fires 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

  1. Same statement, same 7-day window, user = 'whale' (13,421 rows in range):
 Aggregate  (actual time=39.9 rows=1 loops=1)
   ->  Limit  (actual time=9.229..38.102 rows=10001 loops=1)
         ->  Bitmap Heap Scan on "LiteLLM_SpendLogs"  (rows=10001 loops=1)
               Filter: ("user" = 'whale'::text)
               Rows Removed by Filter: 59508
               Buffers: shared hit=7853
  1. It matches 179× more rows than user-0 and costs less — 7,853 buffers vs 10,501 — because the
    LIMIT short-circuits for it. Table size and DB health are the same in both runs; the only
    variable is how selective the filter is.

Page fetch, one user

  1. 7-day window: Sort (quicksort, Sort Key: "startTime" DESC) over the same Bitmap Heap Scan —
    Buffers: shared hit=10504, 47.3 ms.
  2. 30-day window: 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

  1. 7-day window, api_key = 'key-7' (461 rows in range): Bitmap Heap Scan on startTime_idx,
    Filter: (api_key = 'key-7'::text), Rows Removed by Filter: 93058, Buffers: shared hit=10501,
    40.2 ms.
  2. 30-day window: Parallel Seq Scan, Buffers: shared hit=10215, 31.8 ms.

After (94b6d06)

  1. Apply this PR's two migration files verbatim to the same seeded table, then ANALYZE:
CREATE INDEX
Time: 1169.627 ms (00:01.170)
CREATE INDEX
Time: 764.474 ms

Both build plainly, no CONCURRENTLY. Index sizes against an 80 MB heap: 18 MB for the user
index, 16 MB for the api_key index — about 47 and 42 bytes per row.

Count, one user, window widened 1 → 30 days

  1. Same EXPLAIN (ANALYZE, BUFFERS) at each window width:

    Window Plan Buffers Time Before → After buffers
    1 day Index Only Scan on LiteLLM_SpendLogs_user_startTime_idx 4 0.049 ms 7,557 → 4
    3 days same 4 0.089 ms 10,189 → 4
    7 days same 4 0.078 ms 10,501 → 4
    14 days same 5 0.109 ms 10,215 → 5
    30 days same 5 0.183 ms 10,215 → 5
  2. The 7-day plan, in full:

 Aggregate  (cost=6.73..6.74 rows=1 width=8) (actual time=0.059..0.059 rows=1 loops=1)
   ->  Limit  (cost=0.42..5.91 rows=66 width=4) (actual time=0.025..0.050 rows=75 loops=1)
         ->  Index Only Scan using "LiteLLM_SpendLogs_user_startTime_idx" on "LiteLLM_SpendLogs"
               Index Cond: (("user" = 'user-0'::text)
                            AND ("startTime" >= '2026-08-01') AND ("startTime" <= '2026-08-08'))
               Heap Fetches: 0
               Buffers: shared hit=4
 Execution Time: 0.078 ms
  1. Both predicates are now inside Index Cond. There is no Filter node 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 stops
    caring how wide the window is.

Control: the same window for a user above the LIMIT cap

  1. Same statement, user = 'whale': Index Only Scan on 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

  1. 7-day window: Index Scan using "LiteLLM_SpendLogs_user_startTime_idx", no Sort node,
    Buffers: shared hit=53, 0.24 ms (from 10,504 buffers / 47.3 ms).
  2. 30-day window: same plan, 53 buffers, 0.23 ms (from 70,820 buffers / 60.9 ms). The DESC second
    column is what removes the sort — the index already delivers ORDER BY "startTime" DESC.

Count, one API key

  1. 7-day window: Index Only Scan using "LiteLLM_SpendLogs_api_key_startTime_idx",
    Buffers: shared hit=7, 0.21 ms (from 10,501 buffers / 40.2 ms).
  2. 30-day window: same plan, 14 buffers, 0.81 ms (from 10,215 buffers / 31.8 ms).

Test suite

  1. 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.
  2. test_schema_migration_in_sync is the definition pin: it deploys all 165 migrations and
    prisma migrate diffs the result against schema.prisma, so it fails if the migration SQL and the
    @@index declarations ever disagree on name, column order, or DESC.
  3. With the two migration directories removed, the three new tests fail with
    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_key half
at 10^7 rows.

Type

🐛 Bug Fix
🚄 Infrastructure

Caveats (if any)

Severe

  • Both indexes build during the migration step of an upgrade
  • Build is plain, not CONCURRENTLY — deliberate, see below
  • Each build holds a SHARE lock on LiteLLM_SpendLogs
  • Reads continue; inserts to that table block for the build
  • Measured 1.2 s per 400k rows; minutes per index on a large table
  • Rolling deploys keep old pods inserting, so those inserts stall
  • Escape hatch: pre-create both indexes before upgrading, same names —
    LiteLLM_SpendLogs_user_startTime_idx, LiteLLM_SpendLogs_api_key_startTime_idx.
    IF NOT EXISTS then makes both migrations no-ops.
    • Plain table: CREATE INDEX CONCURRENTLY
    • Partitioned table: per-partition builds + ATTACH PARTITION INDEX
  • Why not CONCURRENTLY in the migration: Postgres rejects it on a partitioned parent, and inside the
    transaction prisma migrate deploy runs each migration in. This is what forced a revision of perf(db): index LiteLLM_SpendLogs on (api_key, startTime) #37379.
  • Two migration files, not one, so the two lock windows are separate rather than held back to back

Medium

Low

  • Forward-only, like every migration here: reverting the commit leaves the indexes on databases that
    already applied it. Harmless; drop by hand if unwanted.
  • db_scripts/partition_spend_logs.sql and unpartition_spend_logs.sql had to learn both index names
    too — LIKE … INCLUDING DEFAULTS does not copy indexes, and index names are unique per schema, so
    without the rename-aside the recreate would be silently skipped by IF NOT EXISTS

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@codspeed

codspeed Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_spendlogs_user_api_key_index (94b6d06) with litellm_internal_staging (31ca4dd)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds composite descending-time indexes for user- and API-key-filtered spend-log queries, keeping all Prisma schema copies and migration SQL aligned.

  • Adds separate idempotent migrations for (user, startTime DESC) and (api_key, startTime DESC).
  • Updates partition and unpartition runbooks to preserve canonical index naming.
  • Adds PostgreSQL-backed checks for query-plan usage and partitioned-table compatibility.

Confidence Score: 5/5

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

Important Files Changed

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

codecov Bot commented Sep 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@michelligabriele
michelligabriele force-pushed the litellm_spendlogs_user_api_key_index branch from e414c8f to 94b6d06 Compare September 2, 2026 10:16
@yassin-berriai

Copy link
Copy Markdown
Contributor

this is a duplicate of this #37983

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.

2 participants