Skip to content

fix(stagger): keep every replica of an elected job on one instant - #36686

Open
yassin-berriai wants to merge 2 commits into
litellm_lit_5434_single_owner_jobsfrom
litellm_stagger_pod_invariant_single_owner
Open

yassin-berriai wants to merge 2 commits into
litellm_lit_5434_single_owner_jobsfrom
litellm_stagger_pod_invariant_single_owner

Conversation

@yassin-berriai

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A staggered elected job runs once per replica, not once
  • Its lease dedupes for the body's runtime, not the TTL
  • A 10-pod fleet can run a daily job ~10 times a day
  • Staggering these bought nothing: one replica does the work

How it solves it:

  • An elected job offsets by job id alone, not by pod
  • Every replica shares one instant, so the election settles it
  • Different jobs keep different offsets, so the burst stays broken up
  • Cost pollers excluded: role-gated but take no lock

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

  1. They set LITELLM_KEY_ROTATION_ENABLED=true and roll out 10 replicas
  2. Each replica registers key_rotation_job on a 24h interval and is given a phase offset up to 300s apart from its peers
  3. The first replica to fire takes the Redis lock, rotates whatever is due in a few seconds, and releases it
  4. The second replica fires up to 300s later, finds the lock free, and runs the same job again
  5. This repeats for every replica, so the fleet performs ten daily scans of the key table where one was intended
  6. Nothing errors and nothing is logged as wrong, because each later pass correctly finds nothing due

After: the same deployment runs it once

  1. They set LITELLM_KEY_ROTATION_ENABLED=true and roll out 10 replicas
  2. Every replica computes the same phase offset for key_rotation_job, because the offset no longer depends on which pod it is
  3. All ten fire at the same instant and contend for the Redis lock
  4. One wins and logs litellm_key_rotation_job: pod <id> owns this run; the other nine cost one Redis read each and return
  5. The key table is scanned once
  6. spend_log_cleanup_job, reset_budget_job and the rest still fire at their own distinct offsets, so they do not land together

Relevant 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

  • 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

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:

### BEFORE (2d0823abf7, stagger as merged in #36589)  (10 replicas)
elected jobs, spread across replicas in seconds (0 means they contend on the lease):
   spend_log_cleanup_job         214s   REPLICAS DIVERGE, each can run
   key_rotation_job              279s   REPLICAS DIVERGE, each can run
   ptu_flat_cost_rollup_job      147s   REPLICAS DIVERGE, each can run
per-pod jobs, spread must stay non-zero:
   update_spend_job              203s   STILL SPREAD
   periodic_reload_job           267s   STILL SPREAD
   update_gateway_requests_job   208s   STILL SPREAD

After, on this branch:

### AFTER (this branch)  (10 replicas)
elected jobs, spread across replicas in seconds (0 means they contend on the lease):
   spend_log_cleanup_job           0s   ONE INSTANT
   key_rotation_job                0s   ONE INSTANT
   ptu_flat_cost_rollup_job        0s   ONE INSTANT
   weekly_spend_report_job         0s   ONE INSTANT
lockless jobs, must STAY spread (they are not elected):
   reset_budget_job              264s   STILL SPREAD
   check_batch_cost_job          228s   STILL SPREAD
per-pod jobs, spread must stay non-zero:
   update_spend_job              203s   STILL SPREAD
   periodic_reload_job           267s   STILL SPREAD
   update_gateway_requests_job   208s   STILL SPREAD

Only the elected jobs move. The per-pod values are identical across the two runs at 203s, 267s and 208s, and reset_budget_job holds 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_job as 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_job joins 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_SECONDS already 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 using run_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 noting PTU_ROLLUP_JOB_ID is 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_job and check_responses_cost_job are 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=identity fails 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

  • 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

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.
@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 12, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR makes owner-elected jobs use a replica-independent stagger offset while preserving replica-specific staggering for lockless and per-pod jobs.

  • Adds the elected-job ID registry used by stagger calculations.
  • Keeps reset_budget_job and cost pollers outside that registry.
  • Adds regression coverage for elected, per-pod, lockless, and operator-overridden scheduling.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

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",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
"reset_budget_job",

Comment on lines 25 to +42

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(
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.
@yassin-berriai
yassin-berriai force-pushed the litellm_stagger_pod_invariant_single_owner branch from 5a823d5 to c954907 Compare August 12, 2026 18:36
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai you were right, reset_budget_job takes no lock on this base. Removed, reasoning in the description. Please review head c954907

@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.39572% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/common_utils/single_owner_job.py 96.59% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@yassin-berriai
yassin-berriai force-pushed the litellm_lit_5434_single_owner_jobs branch 2 times, most recently from e8872f7 to 69c8a91 Compare August 20, 2026 22:15
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_lit_5434_single_owner_jobs branch from 69c8a91 to 2ad9e53 Compare August 20, 2026 23:10
@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot added stale and removed stale labels Nov 19, 2026

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