Skip to content

perf(reset_budget_job): elect one sweeper per tick and bound the window scan - #36497

Merged
yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_reset_budget_leader_election
Aug 21, 2026
Merged

yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_reset_budget_leader_election

Conversation

@yassin-berriai

@yassin-berriai yassin-berriai commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Every pod runs the budget reset job, so a fleet multiplies one sweep
  • Daily budgets all come due at once, so the sweep lands on every pod together
  • Postgres, auth latency and in-flight requests spike at the reset boundary
  • The per-window scan reads every row carrying budget limits, unbounded
  • Found and updated rows are serialized on the event loop for nobody

How it solves it:

  • One pod takes a Redis lease per tick, the rest skip
  • No Redis, or unreachable Redis, keeps sweeping rather than stranding budgets
  • The window scan is keyset-paginated, so memory no longer tracks key count
  • Service hooks carry counts, and debug payloads serialize only when logged

User Flow

Before: a developer whose classification service calls the proxy sees requests stall past their deadline every day just after the daily budget boundary

  1. Their service sends POST https://litellm-domain/v1/chat/completions on a key belonging to a team with a 24h budget
  2. Through the day the call returns 200 in tens of milliseconds
  3. At the budget boundary every replica starts the same reset sweep against the same database
  4. The same POST now takes tens of seconds, past the 15s deadline the caller allows, and the caller records a timeout
  5. Their load balancer returns 503 while replicas are unavailable, and the retries that follow extend the window

After: the same request keeps returning in tens of milliseconds across the boundary, because one replica does the reset and the others carry on serving

  1. The proxy admin runs the fleet with Redis configured, as before, and changes no settings
  2. Their service sends the same POST https://litellm-domain/v1/chat/completions on the same key
  3. At the budget boundary one replica takes the reset and the rest skip it
  4. The same POST returns 200 in tens of milliseconds, and the caller records no timeout
  5. Budgets are reset exactly as before, so a key over its cap is still refused and a key under it still serves

Relevant issues

Linear ticket

Resolves LIT-4793

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • 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)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Four proxy processes sharing one Postgres and one Redis, mirroring a fleet pointed at a single database. Flipping budget_reset_at into the past is exactly what the daily boundary does to a 24h budget, so the run below makes 40,000 keys come due at one instant and counts the reset writes the fleet actually issues. The minimum possible is one write per due key; anything above that is a second pod redoing work the first already did.

Before captured at 05943b47a3, the base commit, and after at eecee2073f. Round two then removed the per-run cap from the windowed scan, so the after leg was re-run on e90f3f95b2, and that run, reported at the end of this section, is where the AFTER v2 numbers come from. Head is now 661d853da5, which is f3115e2f51 merged with staging. Nothing in this section has been re-measured since e90f3f95b2, which was still the capped, cursor-carrying build of the windowed scan.

That change does not reach these counters. Keys still due and total spend read budget_reset_at and spend, and the windowed scan writes neither: it rewrites only the budget_limits JSON. The write count is the one it could touch, since a window write lands on the same table the count greps, but the cap it lost reached RESET_BUDGET_JOB_BATCH_SIZE * RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN, 50,000 rows at the defaults this rig ran, against the 40,000 seeded here, so it never bit and the capped and uncapped walks issue the same writes. budget_limits is nullable with no default besides, so rows the seed leaves it unset on never enter that scan

Rig:

docker run -d --name litfix-4793-pg -p 6226:5432 \
  -e POSTGRES_PASSWORD=litellm -e POSTGRES_USER=litellm -e POSTGRES_DB=litellm \
  postgres:16 -c log_statement=all
docker run -d --name litfix-4793-redis -p 7172:6379 redis:7

# four pods against the same DB and Redis, ports 4793-4796
for p in 4793 4794 4795 4796; do
  DATABASE_URL="postgresql://litellm:litellm@127.0.0.1:6226/litellm" \
  PYTHONPATH="$PWD" python litellm/proxy/proxy_cli.py --config config.yaml --port $p &
done

config.yaml carries store_model_in_db: true, a Redis cache block, and proxy_budget_rescheduler_min_time: 15 to compress the ten-minute production cycle.

Make 40,000 keys due at once, then count reset writes over the next 150s:

psql -c "INSERT INTO \"LiteLLM_VerificationToken\"
           (token, key_name, spend, max_budget, budget_duration, budget_reset_at, ...)
         SELECT 'midnight-' || g, 'sk-' || g, 9.99, 100, '24h', NOW() - INTERVAL '1 minute', ...
         FROM generate_series(1, 40000) AS g;"

docker logs --since 150s litfix-4793-pg | grep -c 'UPDATE \"public\".\"LiteLLM_VerificationToken\"'

Before, at 05943b47a3:

=== BEFORE (no leader election, 4 pods, 40000 keys due at once) ===
  pod :4793 health=200
  pod :4794 health=200
  pod :4795 health=200
  pod :4796 health=200
  keys made due at once      : 40000

  reset UPDATE statements    : 102500
  keys still due after       : 0 (0 means the reset completed)
  total spend after reset    : 0 (0 means every key was zeroed)
  redundant writes           : 62500 (2.56x the minimum of 40000)
  redis lock key             : (nil)

After, at eecee2073f:

=== AFTER (leader election, 4 pods, 40000 keys due at once) ===
  pod :4793 health=200
  pod :4794 health=200
  pod :4795 health=200
  pod :4796 health=200
  keys made due at once      : 40000

  reset UPDATE statements    : 40000
  keys still due after       : 0 (0 means the reset completed)
  total spend after reset    : 0 (0 means every key was zeroed)
  redundant writes           : 0 (1.00x the minimum of 40000)
  redis lock key             : (nil)

Both runs finish the reset: no key is left due and every key is zeroed, so the fix removes duplicate work without dropping any. The 2.56x figure is what four pods produce; it grows with replica count and with how long a sweep takes, which is why a 40-pod fleet on a large due population melts rather than merely spiking.

The pods that skipped a tick say so, and the lease is handed back after each sweep rather than held for its TTL:

Pod 4c68ac20-2d59-433e-b3cc-0066a4c48f2c successfully acquired Redis lock for cronjob_id=reset_budget_job
Pod 4c68ac20-2d59-433e-b3cc-0066a4c48f2c successfully released Redis lock for cronjob_id=reset_budget_job
... pod 9a1f could not acquire lock for cronjob_id=reset_budget_job, held by pod 4c68ac20

Counted across the burst, the three non-leader pods yielded 4 times between them, which is the contention the lease converts into a skip instead of a duplicate sweep.

The event-loop cost the hooks used to pay, measured on the same 500-row chunk the job reads:

batch size            : 500
one json.dumps        : 4.0 ms, 530 KiB
calls per key chunk   : 5
blocking per chunk    : 20 ms

Re-run of the after leg on e90f3f95b2. This one counts row updates from pg_stat_user_tables rather than the statement log, because the log had grown large enough across runs that reading it returned an empty window; the previous script refused to compare that run rather than reporting a zero:

=== AFTER v2 (leader election + resumable scan, 4 pods, 40000 keys) ===
  keys seeded due at once    : 40000

  row updates on the table   : 39000
  redundant writes           : -1000 (0.97x the minimum of 40000)
  keys still due after       : 0 (0 means the reset completed)
  total spend after reset    : 0 (0 means every key was zeroed)

pg_stat counters are sampled rather than exact, which is why this reads slightly under one write per key; the statement-log count above is the precise one. What matters is that it is nowhere near the 2.56x the unfixed build produces, and the reset still completes.

Review notes

Three review rounds, and the last two each shrank the diff.

Round one: capping the window scan without remembering where it stopped meant every tick restarted at the first row, so a deployment with more windowed rows than one run's cap would never reach the rest, leaving them pinned at their cap indefinitely. The unbounded original could not starve, so the cap created that. First fix carried the position across ticks in the job instance.

Round two: that was still wrong, because the lease is released after every sweep, so consecutive ticks routinely run on different pods and a fresh pod's position is unset. It would restart at the first row and the tail would starve anyway. Rather than move the position into Redis, the per-run cap is gone: paging is what bounds the memory, and the cursor strictly advances so the walk terminates without a bound. That removes the cursor state, the resume logic, the wrap logic and the truncation warning, and with them the whole starvation question. Against the previous unbounded single-statement read this is strictly better on memory and identical on coverage.

Coverage for it: one test walks a table needing far more pages than a per-run cap would allow and asserts the last row is reached, and one runs two independent job instances, standing in for two pods, and requires each to cover the table end to end. Both were mutation-checked against reintroducing the cap, and both initially SURVIVED that mutant because the fixture tables were smaller than the default cap, so the tests now force the cap low to make it bite.

Round three: rebased onto current staging after the PR went conflicting, and deleted the review comments rather than defending them. Staging had independently added the same db_spend_update_writer mock line to tests/test_litellm/proxy/test_proxy_server.py, so that file drops out of the diff entirely, and the only comment left to remove was the one on the lock wiring in proxy_server.py. _acquire_lease already carries that rationale in its docstring, so the comment was restating it in a second place

The pod-local cursor finding is already resolved at this head, and was resolved before it was filed: it is anchored to e90f3f95b2, the commit round two replaced. _reset_windows_for starts every walk at an empty cursor and loops until a page comes back short, with no per-run cap and no position on the instance, so which pod won the lease cannot change what gets swept. test_every_tick_sweeps_the_whole_window_table_whichever_pod_won runs two separate job objects over one table and requires each to reach the last row, and reintroducing the cap fails it along with test_reset_budget_windows_pages_to_the_end_of_a_large_table

Type

🐛 Bug Fix

Caveats (if any)

  • Redis absent or unreachable sweeps unguarded, matching sibling jobs
  • A sweep outliving its 900s lease can overlap one other pod
  • Duplicate sweeps were already harmless, so this removes cost only
  • Service hooks no longer carry full row payloads, only counts
  • The window scan walks the whole table each sweep, on the leader only

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

Link to Devin session: https://app.devin.ai/sessions/4f559acee90644a1bca9ad024785fb53
Requested by: @yassin-berriai

@CLAassistant

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR elects one budget-reset worker per tick, paginates window-budget scans, and reduces event-loop serialization while preserving complete reset coverage

  • Adds Redis-backed leader election with fail-open behavior when Redis is unavailable
  • Replaces whole-table materialization with keyset pagination that walks each table to completion
  • Sends count-only service-hook metadata and lazily serializes debug payloads
  • Adds regression coverage for lease behavior, paging beyond the former cap, and independent job instances

Confidence Score: 5/5

The PR appears safe to merge

No blocking failure remains

Important Files Changed

Filename Overview
litellm/constants.py Adds the reset-job lock name and fixed lease TTL used for cross-pod election
litellm/proxy/common_utils/reset_budget_job.py Implements lease election, lazy debug serialization, count-only hook metadata, and complete keyset-paginated window scans
litellm/proxy/proxy_server.py Injects the existing pod lock manager into the scheduled reset-budget job
tests/litellm_utils_tests/test_proxy_budget_reset.py Updates service-hook expectations for intentionally omitted row payloads
tests/test_litellm/proxy/common_utils/test_reset_budget_job.py Covers leader election, Redis failure behavior, pagination, full-table traversal, and independent worker instances

Reviews (4): Last reviewed commit: "perf(reset_budget_job): elect one sweepe..." | Re-trigger Greptile

Comment thread litellm/proxy/proxy_server.py Resolved
@veria-ai

veria-ai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.74468% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/common_utils/reset_budget_job.py 95.65% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_reset_budget_leader_election (661d853) with litellm_internal_staging (e07a712)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (33bafd0) during the generation of this report, so e07a712 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@yassin-berriai
yassin-berriai force-pushed the litellm_reset_budget_leader_election branch from eecee20 to e90f3f9 Compare August 11, 2026 11:10
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai the starvation finding was correct and is fixed on head e90f3f95b2; reasoning and mutation checks are in the PR description

@yassin-berriai
yassin-berriai force-pushed the litellm_reset_budget_leader_election branch from e90f3f9 to f378455 Compare August 11, 2026 15:14
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai correct on both rounds; the per-run cap is now gone entirely on head f378455921, so there is no scan position to share. Reasoning in the PR description

@greptile-apps

greptile-apps Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Confirmed — removing the cap entirely is the right resolution. A cap is only safe if the resume position survives pod re-election, which it can't: the lease is released after each sweep, so the next tick can elect any pod, and that pod's cursor starts at "". A capped walk on a fresh pod restarts at row one every tick and never reaches the tail.

Paging alone bounds the memory to one page at a time. The walk terminates when the table drains. Nothing needs to be shared. The concern is resolved.

@yassin-berriai

yassin-berriai commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@greptileai please re-review f3115e2. Rebased onto staging, the pod-local cursor is gone, and the narrating comment on the lock wiring is deleted.

…ow scan

Every pod schedules the budget reset job, so a fleet re-read the whole due
population and wrote it back against one Postgres at the same calendar
boundary, multiplying a single sweep by its replica count. The job now takes
the shared PodLockManager lease, so one pod sweeps per tick. A deployment with
no Redis keeps its previous behavior, and a Redis that cannot answer sweeps
unguarded rather than stranding every expired budget at its cap.

The per-window scan read every row carrying budget_limits in one statement, so
its cost grew with the deployment's key count. It is now keyset-paginated and
walks to the end of the table on every sweep. A per-run cap would need a resume
position, and no pod can hold one because the lease rotates between ticks, so
the strictly advancing cursor is what terminates the walk.

Found and updated rows were also JSON-serialized into the service hook's
metadata and into debug lines on every chunk, on the event loop, whether or not
anything consumed them. The hooks now carry counts, and the debug payload is
deferred until a record is actually emitted.

Resolves LIT-4793
@yassin-berriai
yassin-berriai force-pushed the litellm_reset_budget_leader_election branch from 453a979 to f3115e2 Compare August 20, 2026 22:10
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai re-review f3115e2 please. Same tree as 453a9793e3, which an amend orphaned; only the commit message changed, so the anchor points nowhere.

@yassin-berriai
yassin-berriai enabled auto-merge (squash) August 20, 2026 23:05
yassin-berriai and others added 2 commits August 20, 2026 23:12
…der_election

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@yassin-berriai
yassin-berriai merged commit 66a89f5 into litellm_internal_staging Aug 21, 2026
71 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_reset_budget_leader_election branch August 21, 2026 00:29
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.

3 participants