Skip to content

feat(reset_budget_job): elect one reset runner per tick via PodLockManager - #36311

Draft
ryan-crabbe-berri wants to merge 9 commits into
mainfrom
litellm_lit_5138_reset_leader_election
Draft

ryan-crabbe-berri wants to merge 9 commits into
mainfrom
litellm_lit_5138_reset_leader_election

Conversation

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Every pod runs the budget reset job every ~10 minutes
  • Concurrent runs at the same boundary pile up postgres contention
  • That contention is what caused the LIT-5138 timeouts

How it solves it:

  • One pod per tick wins a redis lock, the rest skip
  • Broken redis fails open, so resets never stop fleet-wide
  • The leader re-checks the lock between phases
  • Same-owner re-acquire renews the lease atomically

User Flow

Before: a proxy admin running many pods sees periodic postgres load spikes and occasional reset-run timeouts

  1. The admin runs 20 pods; every ~10 minutes all 20 fire the same budget reset scans at once
  2. At a popular boundary (say Monday 00:00 UTC) the database serializes 20 identical write bursts
  3. Some runs time out; the admin sees timeout errors in the logs even though every run is retryable

After: one pod does the work per tick and the others stand by

  1. The admin runs the same 20 pods with redis configured
  2. Each tick, one pod logs that it acquired the reset lock and does the work; the other 19 log that they skipped the cycle
  3. Database load per tick drops to a single run's worth; if the leader dies, the lock expires and another pod picks up within a tick

Relevant issues

Linear ticket

Refs LIT-5138

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

Captured live against two worktree proxies on ports 4155/4156 sharing one postgres + redis, at commit 4578c63 (the same implementation this PR re-lands): the self-heal tick plus both pods contesting the lock, one skipping the cycle while the other holds it

Type

🆕 New Feature

Changes

Stacked on #36287 and deliberately split out of it so the bug fix stays pure; this half is an optimization, since chunk commits are atomic and idempotent and concurrent runners only duplicate work

ResetBudgetJob takes an injected PodLockManager (the shared instance key rotation and UI session cleanup already use) and each tick acquires cronjob_lock:reset_budget_job with a 300s TTL: winners run all five phases and release in a finally, losers skip the cycle. A failed acquire only skips when another pod verifiably holds the lock; if redis is unreachable or the key is gone, the run proceeds unguarded, so redis health can never stop budget resets fleet-wide (no redis configured keeps today's every-pod behavior). The leader re-asserts the lock between phases and stops if another pod took over after TTL expiry. PodLockManager.acquire_lock now renews the lease when the holding pod re-acquires, via an atomic compare-and-expire script with a plain SET fallback, which key rotation and session cleanup inherit

An alternative worth weighing at review: claiming rows with FOR UPDATE SKIP LOCKED inside the existing transactions would serialize pods in postgres itself with no redis dependency and none of this lease machinery. This PR ships the redis approach because it reuses the established PodLockManager pattern, but the maintainers may prefer the postgres-native design

Behavior note: with election active, only the leader invalidates its own in-memory user_api_key_cache entries; other pods keep stale entries up to user_api_key_cache_ttl (60s default). Redis-backed spend counters are shared, so enforcement correctness self-heals within that TTL

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

…end cascade

A postgres timeout mid-cascade previously left LiteLLM_BudgetTable rows
stamped for the next window while team member, enduser, org and tag spend
stayed at cap, so every later tick skipped them until the window rolled
over. All cascade writes and the budget_reset_at advance now share one
prisma batch transaction; a failed run persists nothing and the rows stay
due for the next ~10 minute tick. Cache and counter invalidation runs only
after commit, and the catch-all enduser log line now names the cascade.
…scans

Every pod and worker previously ran the reset job every ~10 minutes,
each fetching every expired row with no limit and writing one giant
transaction at the same calendar-aligned boundary; that concurrency is
what piled up postgres lock contention and timeouts. The job now takes
the shared PodLockManager redis lock (no redis keeps the old behavior),
and each phase walks its due rows in 500-row chunks, one transaction per
chunk, stopping when a chunk is short, makes no forward progress, or
hits the per-run cap; leftovers wait for the next tick.
…heartbeat the lock

Review fixes on the two prior commits. Reset scans now skip rows with no
budget_duration, so permanently due rows can neither starve a phase nor
have a lifetime cap zeroed every tick. Chunk progress counts rows whose
new budget_reset_at actually cleared the cutoff, so a zero-length
duration cannot burn the per-run chunk cap. A failed lock acquire only
skips the run when another pod verifiably holds the lock; a broken redis
runs unguarded instead of silently disabling resets fleet-wide. Partial
row failures report real progress and fire the failure hook without
killing the phase. The leader re-asserts the lock between phases and
stops if another pod took over, and the budget window advance uses
update_many so a tier deleted mid-chunk cannot abort the transaction.
Lint budget ceilings re-ratcheted for the net-fixed violations.
… budget durations

Bot review follow-ups. PodLockManager now extends the lock TTL when the
holding pod re-acquires, via an atomic compare-and-expire script with a
plain SET fallback, so a run longer than the TTL keeps its lease instead
of silently sharing the job with another pod. The positive-duration
validation that team member endpoints already had is hoisted to
management common_utils and applied to key, internal user, budget,
customer and team intake, so a tenant can no longer create zero-duration
budgets whose permanently due rows starve other tenants' resets. Such
durations now return 400 at intake; existing rows are untouched.
…itellm_lit_5138_budget_reset_fixes

# Conflicts:
#	basedpyright-code-budget.json
#	litellm/proxy/management_endpoints/team_endpoints.py
#	ruff-strict-budget.json
#	tests/litellm_utils_tests/test_proxy_budget_reset.py
#	type-discipline-budget.json
String defaults for the two getenv calls (PLW1508) and the chunk
outcome returns moved to try/else (TRY300).
@codecov

codecov Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.63636% with 12 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/common_utils/reset_budget_job.py 96.00% 8 Missing ⚠️
.../proxy/db/db_transaction_queue/pod_lock_manager.py 80.95% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

…nager

Re-lands the leader election deferred out of the LIT-5138 bug fix PR:
the shared PodLockManager redis lock elects one pod per ~10 minute tick
(no redis keeps every pod running as before, and a broken redis fails
open after checking whether any pod actually holds the lock), the leader
re-asserts the lock between phases and stops if another pod took over,
and PodLockManager renews the lease on same-owner re-acquire through an
atomic compare-and-expire script with a plain SET fallback.
@ryan-crabbe-berri
ryan-crabbe-berri force-pushed the litellm_lit_5138_reset_leader_election branch from e53938a to 17437d0 Compare August 8, 2026 23:08
Base automatically changed from litellm_lit_5138_budget_reset_fixes to litellm_internal_staging August 10, 2026 21:42
@yuneng-berri
yuneng-berri deleted the branch main September 13, 2026 04:40
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:12

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.

2 participants