Repository navigation
fix(stagger): keep every replica of an elected job on one instant - #36686
yassin-berriai wants to merge 2 commits into
Conversation
Every proxy process registers the same scheduler, and it registers it once per uvicorn worker process rather than once per pod, so a job with a shared side effect runs replicas times processes. The jobs that did elect an owner each hand-rolled it, and the dialects disagree on the one case that matters: acquire_lock reports contention and an unreachable Redis identically, so the PTU rollup ran unguarded while key rotation, spend log cleanup and UI session cleanup skipped, meaning a Redis outage silently stopped those three everywhere at once. Adds run_as_single_owner and claim_once_per_window, which name that decision as WhenLockUnavailable and carry the two lease shapes the proxy actually uses: a mutex held for one run, and a done-marker sized to a reporting window. The lease is now renewed while the body runs, so the TTL is a failover deadline rather than a run budget. On a live proxy that is the difference between a spend log cleanup losing its 60s lock partway through a multi-minute sweep, which a challenger could take at 75s, 120s and 180s, and holding it to completion. LITELLM_JOB_ROLE=serving registers none of these jobs, so an operator can run them on a dedicated worker deployment instead of on every replica taking traffic. A serving pod keeps the jobs that drain its own in-memory queues and refresh its own model registry, so it still writes spend. The default is unchanged, and an unrecognised value falls back to it with a warning. Both Helm charts gain an opt-in worker Deployment, off by default and pinned to one process. Live-Redis integration tests cover election, failover, renewal, rolling restart and once-per-window claims. Also fixes the ownership gauge, which only ever fired on a reentrant re-acquisition and so was driven to 0 by every release and never back up.
|
|
Greptile SummaryThe PR makes owner-elected jobs use a replica-independent stagger offset while preserving replica-specific staggering for lockless and per-pod jobs.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| litellm/proxy/common_utils/scheduled_job_stagger.py | Uses job-only offset identity for registered single-owner jobs while retaining existing offset behavior elsewhere. |
| litellm/proxy/common_utils/single_owner_job.py | Defines the elected-job registry and correctly excludes the lockless budget reset job. |
| tests/test_litellm/proxy/common_utils/test_scheduled_job_stagger.py | Adds regression tests for replica-invariant elected jobs and replica-varying lockless or per-pod jobs. |
Reviews (2): Last reviewed commit: "fix(stagger): keep every replica of an e..." | Re-trigger Greptile
| #: replica poll the provider at once rather than one. | ||
| SINGLE_OWNER_JOB_IDS: Final = frozenset( | ||
| { | ||
| "reset_budget_job", |
There was a problem hiding this comment.
Lockless reset job is synchronized
If multiple default-role or worker replicas run the scheduler, classifying reset_budget_job as single-owner gives every replica the same phase offset even though its callback has no election wrapper, causing concurrent duplicate database updates and Redis cache invalidations.
| "reset_budget_job", |
|
|
||
| T = TypeVar("T") | ||
|
|
||
| #: Scheduler ids of jobs that elect an owner before touching the database, so on any | ||
| #: given tick one replica does the work and the rest cost a single Redis read. | ||
| #: | ||
| #: These are the ids whose phase offset must NOT vary by pod. A per-pod offset spreads | ||
| #: replicas across the stagger window, and a lease released when its body returns only | ||
| #: dedupes for that body's runtime, so replicas further apart than that each find the | ||
| #: lock free and each run. Offsetting by job id alone keeps different jobs on different | ||
| #: instants, which is what staggering is for, while leaving every replica of one job on | ||
| #: the same instant, which is what lets the election do its job. | ||
| #: | ||
| #: Deliberately narrower than "jobs a serving pod skips": the batch and responses cost | ||
| #: pollers are role-gated but take no lock, so firing them together would have every | ||
| #: replica poll the provider at once rather than one. | ||
| SINGLE_OWNER_JOB_IDS: Final = frozenset( | ||
| { |
There was a problem hiding this comment.
Scheduling rationale is repeated
The long comment repeats rationale already added to scheduled_job_stagger.py; keeping the same implementation details in several source comments increases maintenance burden and allows the explanations to drift from the scheduler and locking behavior.
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
A phase offset that varies by pod is right for a job every replica has to run, and wrong for one that elects an owner. The lease is released when the body returns, so it dedupes for that body's runtime rather than for the lock's TTL, and replicas placed further apart than that each find the lock free and each run. With the default 300s window a ten-replica fleet can run a once-a-day job close to ten times a day: key rotation and expired UI session cleanup are both daily intervals whose bodies finish in seconds. Bounding the window cannot fix it, because no non-zero spread is safe once the lease is gone. So an elected job now offsets by job id alone. Every replica lands on the same instant, they contend on the lease exactly as they did before the stagger existed, and one wins. Different jobs still get different offsets, which is the burst this module exists to break up, and only one replica does the work anyway so spreading these bought nothing to begin with. The set is deliberately narrower than the jobs a serving pod skips. The batch and responses cost pollers are role-gated but take no lock, so pinning them to one instant would have every replica poll the provider at once. Measured across ten replicas: the elected jobs go from 147-279s of spread to 0, while update_spend, periodic_reload and the gateway request flush keep theirs unchanged at 203s, 267s and 208s.
5a823d5 to
c954907
Compare
|
@greptileai you were right, reset_budget_job takes no lock on this base. Removed, reasoning in the description. Please review head c954907 |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
e8872f7 to
69c8a91
Compare
69c8a91 to
2ad9e53
Compare
|
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
TLDR
Problem this solves:
How it solves it:
User Flow
Before: an operator running ten replicas finds their daily key rotation scanning the key table once per replica instead of once, and the only visible symptom is database load
LITELLM_KEY_ROTATION_ENABLED=trueand roll out 10 replicaskey_rotation_jobon a 24h interval and is given a phase offset up to 300s apart from its peersAfter: the same deployment runs it once
LITELLM_KEY_ROTATION_ENABLED=trueand roll out 10 replicaskey_rotation_job, because the offset no longer depends on which pod it islitellm_key_rotation_job: pod <id> owns this run; the other nine cost one Redis read each and returnspend_log_cleanup_job,reset_budget_joband the rest still fire at their own distinct offsets, so they do not land togetherRelevant issues
Follows #36589, which introduced the stagger, and #36618, which introduced the election helpers this depends on.
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito 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
The discriminating measurement is how far apart the stagger places two replicas of the same job. For an elected job any spread wider than the body's runtime permits a second run, so the target is exactly 0, while a per-pod job must keep its spread or this would be a regression rather than a fix.
Ten replicas, same job ids, same settings, run against each tree.
Before, on
2d0823abf7:After, on this branch:
Only the elected jobs move. The per-pod values are identical across the two runs at 203s, 267s and 208s, and
reset_budget_jobholds its 264s, which is the part showing this is surgical rather than the stagger being switched off.Type
🐛 Bug Fix
Caveats (if any)
Review notes
Greptile round 1, 4/5, and it caught a real one. The first version of this PR listed
reset_budget_jobas single-owner. It is not: its election lives in #36497 and #36311, neither merged, so on this base it takes no lock at all. Pinning it to one instant would have had every replica start the full budget sweep simultaneously, which is the exact thundering herd that work exists to remove, so the change would have made the thing it was fixing worse. It is removed, and the test that pins the exclusion now asserts the behaviour rather than just the membership: a lockless job must still come out spread across replicas. Re-adding it fails that test.This is the same misclassification I had already guarded against for the cost pollers and did not apply here, which is why the rule in the docstring is now stated as "membership is: this job elects an owner", not "a serving pod skips it".
reset_budget_jobjoins the set when its own entry point elects, and that is worth doing as part of whichever reset-budget PR lands.Why not a dedupe bound.
DEFAULT_CRON_DEDUPE_SECONDSalready bounds how far apart replicas of its three cron ids may be placed, and the obvious fix was to add the interval jobs to it. That does not work. The bound's own docstring said the value is "how long each job's leader-election lock stays held", and that premise is false for any job usingrun_as_single_owner, which releases the lease when the body returns. The dedupe span is the body's runtime, which is seconds and not knowable statically, so no non-zero bound is safe. Worth notingPTU_ROLLUP_JOB_IDis in that map today with a horizon taken from its lock TTL and it releases on completion too, so that entry rested on the same premise; it is now covered by the pod-invariant rule instead, and the bound is left in place as a second line of defence with its comment corrected.Why this costs nothing. Staggering exists to stop every replica hitting Postgres at the same moment. For an elected job only the winner touches Postgres and the losers cost one Redis read, so the burst being prevented was never there. Every one of these jobs takes its lock before any database work: verified per job rather than assumed.
Why the set is narrower than the role gate. It would be tempting to reuse "the jobs a serving pod skips" from #36618, and that set is wrong here.
check_batch_cost_jobandcheck_responses_cost_jobare role-gated but take no lock, so pinning them to one instant would have every replica poll the provider simultaneously, which is worse than what they do now. A test pins that exclusion so the two sets cannot be conflated later.Drift. The set is ids, so a future elected job added without updating it silently gets pod-varying offsets and the bug returns. The tests reduce but do not remove this: every id in the set is asserted pod-invariant, the known per-pod jobs are asserted still spread, and the pollers are asserted excluded. Deriving the set from a lock-taking property rather than a name list would remove the drift entirely and is worth doing when there is a registry to derive it from.
Mutation check. Reverting the one-line change to
identity=identityfails 8 of the parametrized tests, one per elected job id. The existing 22 stagger tests pass unchanged either way, which is the point: none of them covered this.QA runbook
Final Attestation