Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

perf(proxy): stagger scheduled background jobs across jobs and pods (#36589)

Yassin Kortamb0626cad8c8f
diff --git a/litellm/constants.py b/litellm/constants.py
index 8c3541067a5..8ab660b0852 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1529,6 +1529,10 @@ APSCHEDULER_REPLACE_EXISTING: Final = os.getenv("APSCHEDULER_REPLACE_EXISTING",
"1",
] # always replace existing jobs
+# Width of the window scheduled background jobs are spread across, so they do not all fire
+# on one instant on every replica. Tunable per deployment via general_settings.
+DEFAULT_STAGGER_WINDOW_SECONDS: Final = 300
+
# The number of tag entries are higher than number of user, team entries. This leads to a higher QPS.
# This will run tag spcific tasks at a later time to smooth QPS
DAILY_TAG_SPEND_BATCH_MULTIPLIER: Final = 2.3
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 08348187645..1a06906fdf9 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -18,7 +18,7 @@ from pydantic import (
from typing_extensions import NotRequired, Required, TypedDict
from litellm._uuid import uuid
-from litellm.constants import MCP_STDIO_ALLOWED_COMMANDS
+from litellm.constants import DEFAULT_STAGGER_WINDOW_SECONDS, MCP_STDIO_ALLOWED_COMMANDS
from litellm.litellm_core_utils.initialize_dynamic_callback_params import (
validate_no_callback_env_reference,
)
@@ -2251,6 +2251,39 @@ class CoordinationRedisParams(LiteLLMPydanticObjectBase):
return any(value is not None for value in (self.host, self.url, self.startup_nodes, self.sentinel_nodes))
+class ScheduledJobStaggerSettings(LiteLLMPydanticObjectBase):
+ """
+ Spreads the proxy's scheduled background jobs across a window instead of firing them
+ all on one instant, on every replica, forever.
+ """
+
+ model_config = ConfigDict(frozen=True, extra="forbid", protected_namespaces=())
+
+ enabled: bool = Field(default=True, description="apply deterministic phase offsets to scheduled background jobs")
+ window_seconds: int = Field(
+ default=DEFAULT_STAGGER_WINDOW_SECONDS,
+ ge=0,
+ description=(
+ "width of the window jobs are spread over. An interval job is never offset by "
+ "more than one of its own periods, so it is not delayed past the wait it already has"
+ ),
+ )
+ identity: str | None = Field(
+ default=None,
+ description=(
+ "replaces the POD_NAME/HOSTNAME-derived component of the offset hash. Set this "
+ "when replicas share a hostname and would otherwise land on the same offset"
+ ),
+ )
+ offsets: Mapping[str, int] = Field(
+ default_factory=dict,
+ description=(
+ "explicit offset in seconds per scheduler job id, overriding the derived value. "
+ "0 pins a job to its unshifted schedule"
+ ),
+ )
+
+
class ConfigGeneralSettings(LiteLLMPydanticObjectBase):
"""
Documents all the fields supported by `general_settings` in config.yaml
@@ -2437,6 +2470,14 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase):
None,
description="By default, the user calling /team/new is automatically added to the new team as a team admin. If True, proxy admins are no longer auto-added; members explicitly listed in members_with_roles are unaffected. Default is False.",
)
+ scheduled_job_stagger: ScheduledJobStaggerSettings | None = Field(
+ None,
+ description=(
+ "Spreads the proxy's scheduled background jobs (spend flushes, budget resets, "
+ "config reloads, exports) across a window instead of firing them together on "
+ "every replica. On by default; set to tune the window, pin a job, or turn it off."
+ ),
+ )
maximum_spend_logs_retention_period: str | None = Field(
None,
description="Maximum retention period for spend logs (e.g., '7d' for 7 days). Logs older than this will be deleted.",
diff --git a/litellm/proxy/common_utils/scheduled_job_stagger.py b/litellm/proxy/common_utils/scheduled_job_stagger.py
new file mode 100644
index 00000000000..e48e9686f13
--- /dev/null
+++ b/litellm/proxy/common_utils/scheduled_job_stagger.py
@@ -0,0 +1,347 @@
+"""
+Deterministic phase offsets for the proxy's scheduled background jobs.
+
+APScheduler anchors an ``interval`` job at ``now + interval``, so every job registered in
+the same startup shares one firing instant for the life of the process, and every replica
+brought up by the same rollout shares it too. The result is a burst: each tick, every job
+on every replica queries Postgres at the same moment, competing with the request path for
+the connection pool. The product's own daily/monthly crons are worse still, since they name
+a wall-clock instant that is identical on every replica by construction.
+
+The fix is a phase offset derived from ``sha256(job_id, identity)``, where ``identity``
+covers the pod and the worker process. Different jobs get different offsets, different
+replicas get different offsets for the same job, and nothing collapses back onto a shared
+instant after a restart. Hashing rather than randomising keeps a given process's schedule
+stable for its whole life and lets the applied offsets be logged once and reasoned about
+later.
+
+The offset lives in the trigger rather than in a one-off ``next_run_time`` because a cron
+trigger recomputes each fire from the wall clock and would otherwise snap straight back
+onto the shared instant after its first shifted run.
+
+Only schedules LiteLLM itself chose are shifted. Interval jobs are always eligible; cron
+jobs only when their id is one of the product's own defaults, so an operator-supplied
+crontab keeps the exact instant it asks for. A job whose call site passed an explicit
+``next_run_time`` already anchors itself and is left alone.
+"""
+
+# apscheduler ships no type information, so its imports have no stubs. The Protocols below
+# narrow everything it hands back, which is why this is the only diagnostic left to silence.
+# pyright: reportMissingTypeStubs=false
+
+import hashlib
+import os
+import socket
+from collections.abc import Callable, Mapping, Sequence
+from datetime import datetime, timedelta
+from types import MappingProxyType
+from typing import Final, Protocol
+
+from apscheduler.events import EVENT_JOB_SUBMITTED
+from apscheduler.triggers.base import BaseTrigger
+from apscheduler.triggers.interval import IntervalTrigger
+from pydantic import ValidationError
+
+from litellm._logging import verbose_proxy_logger
+from litellm._uuid import uuid
+from litellm.constants import (
+ MONTHLY_SPEND_REPORT_JOB_ID,
+ PROMETHEUS_FALLBACK_STATS_JOB_ID,
+ PTU_ROLLUP_JOB_ID,
+ PTU_ROLLUP_LOCK_TTL_SECONDS,
+)
+from litellm.proxy._types import ScheduledJobStaggerSettings
+
+GENERAL_SETTINGS_KEY: Final = "scheduled_job_stagger"
+
+#: Cron schedules LiteLLM picks on the operator's behalf, so shifting them changes nothing the
+#: operator asked for. Every other cron trigger is an operator-supplied crontab, preserved exactly.
+#:
+#: The value is the span over which a second firing would redo work the first already did, which
+#: is how long each job's leader-election lock stays held. Two replicas further apart than that
+#: both find the key free and both run, which for the spend report means the customer gets it
+#: twice. Offsets for these jobs are bounded by it, so widening the window cannot resurrect the
+#: duplicate-work failure this feature exists to avoid.
+DEFAULT_CRON_DEDUPE_SECONDS: Final = MappingProxyType(
+ {
+ MONTHLY_SPEND_REPORT_JOB_ID: 3600,
+ PROMETHEUS_FALLBACK_STATS_JOB_ID: 3600,
+ PTU_ROLLUP_JOB_ID: PTU_ROLLUP_LOCK_TTL_SECONDS,
+ }
+)
+
+
+class Trigger(Protocol):
+ """The one method APScheduler asks a trigger for"""
+
+ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime) -> datetime | None: ...
+
+
+class ScheduledJob(Protocol):
+ @property
+ def id(self) -> str: ...
+
+ @property
+ def trigger(self) -> Trigger: ...
+
+
+class JobScheduler(Protocol):
+ """The slice of ``AsyncIOScheduler`` this module uses, which ships no type information"""
+
+ @property
+ def running(self) -> bool: ...
+
+ def get_jobs(self) -> Sequence[ScheduledJob]: ...
+
+ def modify_job(self, job_id: str, *, trigger: Trigger) -> object: ...
+
+ def add_listener(self, callback: Callable[["JobSubmission"], None], mask: int = ...) -> None: ...
+
+
+class JobSubmission(Protocol):
+ """An ``EVENT_JOB_SUBMITTED`` event"""
+
+ @property
+ def job_id(self) -> str: ...
+
+ @property
+ def scheduled_run_times(self) -> Sequence[datetime]: ...
+
+
+class _OffsetTrigger:
+ """
+ Delegates to ``base`` on a clock rolled back by ``offset``, then rolls the answer
+ forward again, so every fire lands exactly ``offset`` later than it otherwise would
+ while the underlying schedule keeps its own semantics.
+
+ Composed rather than derived from ``BaseTrigger``: APScheduler only ever asks a trigger
+ for its next fire time, and it accepts this by virtual registration below.
+ """
+
+ __slots__ = ("base", "offset")
+
+ def __init__(self, base: Trigger, offset: timedelta) -> None:
+ self.base = base
+ self.offset = offset
+
+ def get_next_fire_time(self, previous_fire_time: datetime | None, now: datetime) -> datetime | None:
+ shifted_previous: Final = None if previous_fire_time is None else previous_fire_time - self.offset
+ next_fire_time: Final = self.base.get_next_fire_time(shifted_previous, now - self.offset)
+ return None if next_fire_time is None else next_fire_time + self.offset
+
+ def __str__(self) -> str:
+ return f"{self.base}[+{int(self.offset.total_seconds())}s]"
+
+
+# APScheduler type-checks assigned triggers with isinstance, so it has to accept this one
+BaseTrigger.register(_OffsetTrigger)
+
+
+def parse_stagger_settings(general_settings: Mapping[str, object]) -> ScheduledJobStaggerSettings:
+ raw: Final = general_settings.get(GENERAL_SETTINGS_KEY)
+ if raw is None:
+ return ScheduledJobStaggerSettings()
+ try:
+ return ScheduledJobStaggerSettings.model_validate(raw)
+ except ValidationError as exc:
+ verbose_proxy_logger.warning(
+ "Ignoring invalid general_settings.%s, falling back to defaults: %s",
+ GENERAL_SETTINGS_KEY,
+ exc,
+ )
+ return ScheduledJobStaggerSettings()
+
+
+def resolve_stagger_identity(configured: str | None) -> str:
+ """
+ The value hashed alongside a job id to place this process in the stagger window.
+
+ The process id is part of it because a pod runs one scheduler per uvicorn worker, and
+ workers sharing a hostname would otherwise all land on the same offset. That makes the
+ offsets change across restarts, which is what stops a simultaneous rollout from
+ reconverging; the applied values are logged so a given run stays explainable.
+ """
+ host: Final = configured or os.getenv("POD_NAME") or os.getenv("HOSTNAME") or _hostname()
+ return f"{host}:{os.getpid()}"
+
+
+def _hostname() -> str:
+ try:
+ return socket.gethostname()
+ except OSError:
+ return str(uuid.uuid4())
+
+
+def offset_seconds(*, job_id: str, identity: str, window_seconds: int) -> int:
+ """A stable point in ``[0, window_seconds)`` for this job on this process"""
+ if window_seconds <= 0:
+ return 0
+ digest: Final = hashlib.sha256(f"{job_id}\x00{identity}".encode()).digest()
+ return int.from_bytes(digest[:8], "big") % window_seconds
+
+
+def _interval_seconds(job: ScheduledJob) -> int | None:
+ if not isinstance(job.trigger, IntervalTrigger):
+ return None
+ interval: Final = getattr(job.trigger, "interval", None)
+ return int(interval.total_seconds()) if isinstance(interval, timedelta) else None
+
+
+def _is_staggerable(job: ScheduledJob) -> bool:
+ if hasattr(job, "next_run_time"):
+ # the call site anchored the first fire itself
+ return False
+ if _interval_seconds(job) is not None:
+ return True
+ return job.id in DEFAULT_CRON_DEDUPE_SECONDS
+
+
+def _window_for(*, job_id: str, period_seconds: int | None, settings: ScheduledJobStaggerSettings) -> int:
+ """
+ Exclusive upper bound on this job's offset. An interval job is never offset by more than
+ one of its own periods, so it is not delayed past the wait it already had, and a
+ leader-elected cron is never offset past the span in which a second replica would redo
+ its work.
+ """
+ limits: Final = (settings.window_seconds, period_seconds, DEFAULT_CRON_DEDUPE_SECONDS.get(job_id))
+ return min(limit for limit in limits if limit is not None)
+
+
+def _clamped_override(*, job_id: str, requested: int) -> int:
+ horizon: Final = DEFAULT_CRON_DEDUPE_SECONDS.get(job_id)
+ if horizon is None or requested < horizon:
+ return requested
+ verbose_proxy_logger.warning(
+ "general_settings.%s.offsets[%s]=%ss would place replicas more than %ss apart, "
+ "which is long enough for a second replica to redo the run; using %ss instead",
+ GENERAL_SETTINGS_KEY,
+ job_id,
+ requested,
+ horizon,
+ horizon - 1,
+ )
+ return horizon - 1
+
+
+def _offset_for(
+ *,
+ job_id: str,
+ period_seconds: int | None,
+ staggerable: bool,
+ settings: ScheduledJobStaggerSettings,
+ identity: str,
+) -> int:
+ override: Final = settings.offsets.get(job_id)
+ if override is not None:
+ return _clamped_override(job_id=job_id, requested=max(0, override))
+ if not staggerable:
+ return 0
+ return offset_seconds(
+ job_id=job_id,
+ identity=identity,
+ window_seconds=_window_for(job_id=job_id, period_seconds=period_seconds, settings=settings),
+ )
+
+
+def stagger_trigger(
+ *,
+ job_id: str,
+ trigger: Trigger,
+ period_seconds: int | None,
+ settings: ScheduledJobStaggerSettings,
+ identity: str | None = None,
+) -> Trigger:
+ """
+ The trigger a job should carry, shifted by its own share of the window.
+
+ For a job registered against an already-running scheduler, which the startup sweep cannot
+ reach: every job carries a ``next_run_time`` by then, so re-running the sweep would treat
+ them all as self-anchored and change nothing.
+ """
+ offset: Final = _offset_for(
+ job_id=job_id,
+ period_seconds=period_seconds,
+ staggerable=True,
+ settings=settings,
+ identity=identity or resolve_stagger_identity(settings.identity),
+ )
+ return trigger if offset == 0 else _OffsetTrigger(trigger, timedelta(seconds=offset))
+
+
+def apply_scheduled_job_stagger(
+ *,
+ scheduler: JobScheduler,
+ settings: ScheduledJobStaggerSettings,
+ identity: str | None = None,
+) -> Mapping[str, int]:
+ """
+ Shift each eligible job's schedule by its own offset. Call this once, after every job is
+ registered and before the scheduler starts, so the offset is folded into the first fire
+ rather than applied to a schedule already running.
+
+ ``identity`` is resolved from the environment when the caller does not supply one.
+
+ Returns the offset applied to every registered job, including the zeroes, so the caller
+ and the logs describe the same thing.
+ """
+ resolved_identity: Final = identity or resolve_stagger_identity(settings.identity)
+ if scheduler.running:
+ # every job already carries a next_run_time by now, so the sweep would skip all of
+ # them and report success while changing nothing
+ verbose_proxy_logger.warning(
+ "Scheduled job stagger skipped: the scheduler is already running, so offsets must be "
+ "applied before it starts"
+ )
+ return MappingProxyType({job.id: 0 for job in scheduler.get_jobs()})
+ if not settings.enabled:
+ verbose_proxy_logger.info(
+ "Scheduled job stagger disabled via general_settings.%s; all jobs keep their unshifted schedule",
+ GENERAL_SETTINGS_KEY,
+ )
+ return MappingProxyType({job.id: 0 for job in scheduler.get_jobs()})
+
+ offsets: Final = MappingProxyType(
+ {
+ job.id: _offset_for(
+ job_id=job.id,
+ period_seconds=_interval_seconds(job),
+ staggerable=_is_staggerable(job),
+ settings=settings,
+ identity=resolved_identity,
+ )
+ for job in scheduler.get_jobs()
+ }
+ )
+ for job in scheduler.get_jobs():
+ if offsets[job.id] > 0:
+ scheduler.modify_job(
+ job.id,
+ trigger=_OffsetTrigger(job.trigger, timedelta(seconds=offsets[job.id])),
+ )
+
+ verbose_proxy_logger.info(
+ "Scheduled job stagger applied (identity=%s, window=%ss): %s",
+ resolved_identity,
+ settings.window_seconds,
+ ", ".join(f"{job_id}=+{seconds}s" for job_id, seconds in sorted(offsets.items())),
+ )
+ return offsets
+
+
+def attach_job_timing_logger(scheduler: JobScheduler) -> None:
+ """Log each fire's scheduled instant against the instant it actually started"""
+ scheduler.add_listener(_log_job_submitted, EVENT_JOB_SUBMITTED)
+
+
+def _log_job_submitted(event: JobSubmission) -> None:
+ if not event.scheduled_run_times:
+ return
+ scheduled: Final = event.scheduled_run_times[0]
+ started: Final = datetime.now(scheduled.tzinfo)
+ verbose_proxy_logger.debug(
+ "Scheduled job %s started: scheduled_run_time=%s actual_start_time=%s delay=%.3fs",
+ event.job_id,
+ scheduled.isoformat(),
+ started.isoformat(),
+ (started - scheduled).total_seconds(),
+ )
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 2fc69ef5f6e..172eba9e43c 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -171,6 +171,7 @@ try:
import orjson
import yaml
from apscheduler.schedulers.asyncio import AsyncIOScheduler
+ from apscheduler.triggers.interval import IntervalTrigger
except ImportError as e:
raise ImportError(f"Missing dependency {e}. Run `pip install 'litellm[proxy]'`")
@@ -344,6 +345,12 @@ from litellm.proxy.common_utils.periodic_reload_schedule import (
)
from litellm.proxy.common_utils.proxy_state import ProxyState
from litellm.proxy.common_utils.reset_budget_job import ResetBudgetJob
+from litellm.proxy.common_utils.scheduled_job_stagger import (
+ apply_scheduled_job_stagger,
+ attach_job_timing_logger,
+ parse_stagger_settings,
+ stagger_trigger,
+)
from litellm.proxy.common_utils.swagger_utils import ERROR_RESPONSES
from litellm.proxy.common_utils.timezone_utils import (
get_budget_reset_settings,
@@ -6142,10 +6149,17 @@ class ProxyConfig:
retention_interval: Final = general_settings.get("maximum_spend_logs_retention_interval", "1d")
try:
interval_seconds: Final = duration_in_seconds(retention_interval)
+ # this runs against a started scheduler, which the startup stagger sweep
+ # cannot reach, so the offset is applied here or the job reconverges across
+ # replicas the first time an admin edits the retention settings
scheduler.add_job(
spend_log_cleanup.cleanup_old_spend_logs,
- "interval",
- seconds=interval_seconds + random.randint(0, 60),
+ stagger_trigger(
+ job_id="spend_log_cleanup_job",
+ trigger=IntervalTrigger(seconds=interval_seconds),
+ period_seconds=interval_seconds,
+ settings=parse_stagger_settings(general_settings),
+ ),
args=[prisma_client],
id="spend_log_cleanup_job",
replace_existing=True,
@@ -8941,6 +8955,14 @@ class ProxyStartupEvent:
# Do NOT reset job times to "now" as this can trigger the memory leak
# The misfire_grace_time and coalesce settings will handle any missed runs properly
+ # Every job above anchors on this process's start instant, so without a phase offset
+ # they all fire together, on every replica the rollout brought up at the same time
+ attach_job_timing_logger(scheduler)
+ apply_scheduled_job_stagger(
+ scheduler=scheduler,
+ settings=parse_stagger_settings(general_settings),
+ )
+
# Start the scheduler immediately without processing backlogs
scheduler.start(paused=False)
verbose_proxy_logger.info(
diff --git a/tests/test_litellm/proxy/common_utils/test_scheduled_job_stagger.py b/tests/test_litellm/proxy/common_utils/test_scheduled_job_stagger.py
new file mode 100644
index 00000000000..ca4d62737b6
--- /dev/null
+++ b/tests/test_litellm/proxy/common_utils/test_scheduled_job_stagger.py
@@ -0,0 +1,305 @@
+import itertools
+import logging
+import os
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+
+import pytest
+from apscheduler.executors.asyncio import AsyncIOExecutor
+from apscheduler.jobstores.memory import MemoryJobStore
+from apscheduler.schedulers.asyncio import AsyncIOScheduler
+from apscheduler.triggers.cron import CronTrigger
+from apscheduler.triggers.interval import IntervalTrigger
+
+from litellm.constants import PTU_ROLLUP_JOB_ID, PTU_ROLLUP_LOCK_TTL_SECONDS
+from litellm.proxy._types import ScheduledJobStaggerSettings
+from litellm.proxy.common_utils.scheduled_job_stagger import (
+ apply_scheduled_job_stagger,
+ attach_job_timing_logger,
+ offset_seconds,
+ parse_stagger_settings,
+ resolve_stagger_identity,
+ stagger_trigger,
+)
+
+OPERATOR_CRON_JOB_ID = "spend_log_cleanup_job"
+SHARED_INTERVAL_JOB_IDS = ("periodic_reload_job", "get_credentials_job", "add_deployment_job")
+
+
+async def _noop() -> None: ...
+
+
+def _scheduler() -> AsyncIOScheduler:
+ return AsyncIOScheduler(
+ jobstores={"default": MemoryJobStore()},
+ executors={"default": AsyncIOExecutor()},
+ timezone=None,
+ )
+
+
+def _with_jobs(scheduler: AsyncIOScheduler) -> AsyncIOScheduler:
+ for job_id in SHARED_INTERVAL_JOB_IDS:
+ scheduler.add_job(_noop, "interval", seconds=30, id=job_id, replace_existing=True)
+ scheduler.add_job(
+ _noop, "cron", hour=0, minute=15, timezone=timezone.utc, id=PTU_ROLLUP_JOB_ID, replace_existing=True
+ )
+ # an operator-supplied crontab, which must survive untouched
+ scheduler.add_job(_noop, CronTrigger.from_crontab("0 3 * * *"), id=OPERATOR_CRON_JOB_ID, replace_existing=True)
+ return scheduler
+
+
+def _next_run_times(scheduler: AsyncIOScheduler) -> dict[str, datetime]:
+ scheduler.start(paused=True)
+ try:
+ return {job.id: job.next_run_time for job in scheduler.get_jobs()}
+ finally:
+ scheduler.shutdown(wait=False)
+
+
+def _settings(**overrides) -> ScheduledJobStaggerSettings:
+ return ScheduledJobStaggerSettings(**overrides)
+
+
+def _stagger(scheduler: AsyncIOScheduler, identity: str = "pod-a:1", **overrides):
+ return apply_scheduled_job_stagger(scheduler=scheduler, settings=_settings(**overrides), identity=identity)
+
+
+def _fire_times(trigger, start: datetime, steps: int) -> tuple[datetime, ...]:
+ """The fire times APScheduler would produce, each computed from the one before it"""
+ return tuple(
+ itertools.accumulate(
+ range(steps - 1),
+ lambda previous, _: trigger.get_next_fire_time(previous, previous),
+ initial=trigger.get_next_fire_time(None, start),
+ )
+ )
+
+
+async def test_jobs_sharing_an_interval_no_longer_share_a_firing_instant():
+ """The defect: APScheduler anchors every interval job at ``now + interval``"""
+ unstaggered = _next_run_times(_with_jobs(_scheduler()))
+ base_times = [unstaggered[job_id] for job_id in SHARED_INTERVAL_JOB_IDS]
+ assert max(base_times) - min(base_times) < timedelta(seconds=1)
+
+ scheduler = _with_jobs(_scheduler())
+ _stagger(scheduler)
+ staggered = _next_run_times(scheduler)
+
+ shifted_times = [staggered[job_id] for job_id in SHARED_INTERVAL_JOB_IDS]
+ assert len(set(shifted_times)) == len(SHARED_INTERVAL_JOB_IDS)
+ assert max(shifted_times) - min(shifted_times) >= timedelta(seconds=1)
+
+
+def test_replicas_do_not_start_the_same_job_at_the_same_instant():
+ offsets = {
+ identity: offset_seconds(job_id="update_spend_job", identity=identity, window_seconds=300)
+ for identity in ("pod-a:1", "pod-b:1", "pod-c:1", "pod-a:2")
+ }
+ assert len(set(offsets.values())) == len(offsets)
+
+
+def test_offset_is_reproducible_for_a_given_job_and_identity():
+ first = offset_seconds(job_id="update_spend_job", identity="pod-a:7", window_seconds=300)
+ second = offset_seconds(job_id="update_spend_job", identity="pod-a:7", window_seconds=300)
+ assert first == second
+
+
+def test_offset_never_exceeds_one_period_of_an_interval_job():
+ """A job may be phase shifted, never delayed past the wait it already had"""
+ scheduler = _scheduler()
+ scheduler.add_job(_noop, "interval", seconds=5, id="tight_job", replace_existing=True)
+ applied = _stagger(scheduler, window_seconds=300)
+
+ assert 0 <= applied["tight_job"] < 5
+
+
+async def test_operator_supplied_cron_keeps_its_exact_schedule():
+ unstaggered = _next_run_times(_with_jobs(_scheduler()))
+
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler)
+ staggered = _next_run_times(scheduler)
+
+ assert applied[OPERATOR_CRON_JOB_ID] == 0
+ assert staggered[OPERATOR_CRON_JOB_ID] == unstaggered[OPERATOR_CRON_JOB_ID]
+
+
+def test_default_cron_is_staggered_and_keeps_its_offset_on_every_later_fire():
+ """
+ A cron trigger recomputes each fire from the wall clock, so an offset applied only to
+ the first run would snap straight back onto the shared instant
+ """
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler)
+ assert applied[PTU_ROLLUP_JOB_ID] > 0
+
+ trigger = next(job.trigger for job in scheduler.get_jobs() if job.id == PTU_ROLLUP_JOB_ID)
+ fires = _fire_times(trigger, datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc), 3)
+
+ expected = timedelta(minutes=15) + timedelta(seconds=applied[PTU_ROLLUP_JOB_ID])
+ assert [fire - fire.replace(hour=0, minute=0, second=0, microsecond=0) for fire in fires] == [expected] * 3
+
+
+async def test_explicit_offset_overrides_the_derived_one_and_zero_pins_a_job():
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler, offsets={"periodic_reload_job": 0, PTU_ROLLUP_JOB_ID: 7})
+ unstaggered = _next_run_times(_with_jobs(_scheduler()))
+ staggered = _next_run_times(scheduler)
+
+ assert applied["periodic_reload_job"] == 0
+ assert applied[PTU_ROLLUP_JOB_ID] == 7
+ assert staggered[PTU_ROLLUP_JOB_ID] - unstaggered[PTU_ROLLUP_JOB_ID] == timedelta(seconds=7)
+
+
+async def test_disabling_the_stagger_leaves_every_schedule_untouched():
+ unstaggered = _next_run_times(_with_jobs(_scheduler()))
+
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler, enabled=False)
+ staggered = _next_run_times(scheduler)
+
+ assert set(applied.values()) == {0}
+ assert {job_id: run for job_id, run in staggered.items() if job_id != OPERATOR_CRON_JOB_ID}.keys() == {
+ job_id for job_id in unstaggered if job_id != OPERATOR_CRON_JOB_ID
+ }
+ assert staggered[PTU_ROLLUP_JOB_ID] == unstaggered[PTU_ROLLUP_JOB_ID]
+
+
+async def test_a_job_that_anchored_its_own_first_fire_is_left_alone():
+ anchor = datetime.now(timezone.utc) + timedelta(seconds=90)
+ scheduler = _scheduler()
+ scheduler.add_job(
+ _noop, "interval", days=7, next_run_time=anchor, id="weekly_spend_report_job", replace_existing=True
+ )
+ applied = _stagger(scheduler)
+
+ assert applied["weekly_spend_report_job"] == 0
+ assert _next_run_times(scheduler)["weekly_spend_report_job"] == anchor
+
+
+async def test_applying_after_the_scheduler_started_is_refused_loudly(caplog):
+ """
+ Every job carries a next_run_time once the scheduler is running, so the sweep would skip
+ all of them and report success while changing nothing
+ """
+ scheduler = _with_jobs(_scheduler())
+ scheduler.start(paused=True)
+ try:
+ before = {job.id: job.next_run_time for job in scheduler.get_jobs()}
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ applied = _stagger(scheduler)
+ after = {job.id: job.next_run_time for job in scheduler.get_jobs()}
+ finally:
+ scheduler.shutdown(wait=False)
+
+ assert set(applied.values()) == {0}
+ assert after == before
+ assert "already running" in caplog.text
+
+
+async def test_a_leader_elected_cron_is_never_spread_past_its_dedupe_window():
+ """
+ These crons hold a lock that marks the window's work done. Two replicas further apart
+ than that both find the key free and both run, so the monthly report goes out twice.
+ """
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler, window_seconds=100_000)
+
+ assert 0 < applied[PTU_ROLLUP_JOB_ID] < PTU_ROLLUP_LOCK_TTL_SECONDS
+
+
+async def test_an_explicit_offset_past_the_dedupe_window_is_clamped_and_warned(caplog):
+ scheduler = _with_jobs(_scheduler())
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ applied = _stagger(scheduler, offsets={PTU_ROLLUP_JOB_ID: 100_000})
+
+ assert applied[PTU_ROLLUP_JOB_ID] == PTU_ROLLUP_LOCK_TTL_SECONDS - 1
+ assert PTU_ROLLUP_JOB_ID in caplog.text
+
+
+async def test_an_explicit_offset_on_an_ordinary_job_is_honored_as_given():
+ scheduler = _with_jobs(_scheduler())
+ applied = _stagger(scheduler, offsets={"periodic_reload_job": 100_000})
+
+ assert applied["periodic_reload_job"] == 100_000
+
+
+def test_a_job_registered_after_startup_still_gets_its_offset():
+ """
+ The runtime reschedule path adds to a started scheduler, where the sweep cannot see the
+ job, so the trigger has to carry the offset before it is handed over
+ """
+ base = IntervalTrigger(seconds=3600, timezone=timezone.utc)
+ shifted = stagger_trigger(
+ job_id="spend_log_cleanup_job",
+ trigger=base,
+ period_seconds=3600,
+ settings=_settings(),
+ identity="pod-a:1",
+ )
+ start = datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc)
+
+ offset = _fire_times(shifted, start, 1)[0] - _fire_times(base, start, 1)[0]
+ assert timedelta(0) < offset < timedelta(seconds=3600)
+ assert _fire_times(shifted, start, 2)[1] - _fire_times(shifted, start, 1)[0] == timedelta(seconds=3600)
+
+
+ "raw, expected_window",
+ [
+ (None, 300),
+ ({"window_seconds": 45}, 45),
+ ({"bogus_key": 1}, 300),
+ ({"window_seconds": -1}, 300),
+ ("not-a-mapping", 300),
+ ],
+)
+def test_settings_parse_and_fall_back_to_defaults_when_invalid(raw, expected_window):
+ general_settings = {} if raw is None else {"scheduled_job_stagger": raw}
+ assert parse_stagger_settings(general_settings).window_seconds == expected_window
+
+
+def test_a_config_shaped_block_parses_whole():
+ """The block arrives as plain YAML-decoded dicts, so every key has to survive that shape"""
+ settings = parse_stagger_settings(
+ {
+ "scheduled_job_stagger": {
+ "enabled": False,
+ "window_seconds": 600,
+ "identity": "replica-3",
+ "offsets": {"update_spend_job": 0, PTU_ROLLUP_JOB_ID: 900},
+ }
+ }
+ )
+
+ assert (settings.enabled, settings.window_seconds, settings.identity) == (False, 600, "replica-3")
+ assert dict(settings.offsets) == {"update_spend_job": 0, PTU_ROLLUP_JOB_ID: 900}
+
+
+def test_identity_prefers_pod_name_and_separates_workers_on_one_host(monkeypatch):
+ monkeypatch.setenv("POD_NAME", "litellm-abc")
+ monkeypatch.setenv("HOSTNAME", "litellm-abc")
+ identity = resolve_stagger_identity(None)
+
+ assert identity.startswith("litellm-abc:")
+ assert identity == f"litellm-abc:{os.getpid()}"
+
+ monkeypatch.delenv("POD_NAME")
+ assert resolve_stagger_identity(None).startswith("litellm-abc:")
+ assert resolve_stagger_identity("explicit").startswith("explicit:")
+
+
+def test_job_timing_is_logged_with_scheduled_and_actual_start(caplog):
+ scheduler = _scheduler()
+ attach_job_timing_logger(scheduler)
+ scheduled = datetime.now(timezone.utc) - timedelta(seconds=2)
+ listener = next(iter(scheduler._listeners))[0]
+
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):
+ listener(SimpleNamespace(job_id="update_spend_job", scheduled_run_times=[scheduled]))
+
+ message = caplog.text
+ assert "update_spend_job" in message
+ assert f"scheduled_run_time={scheduled.isoformat()}" in message
+ assert "actual_start_time=" in message
+ assert "delay=2." in message
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 326dfb80a7e..1e46ae9c577 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -23640,6 +23640,8 @@ export interface components {
* @description When set to True, rejects requests that contain client-side 'metadata.tags' to prevent users from influencing budgets by sending different tags. Tags can only be inherited from the API key metadata.
*/
reject_clientside_metadata_tags?: boolean | null;
+ /** @description Spreads the proxy's scheduled background jobs (spend flushes, budget resets, config reloads, exports) across a window instead of firing them together on every replica. On by default; set to tune the window, pin a job, or turn it off. */
+ scheduled_job_stagger?: components["schemas"]["ScheduledJobStaggerSettings"] | null;
/**
* Store Model In Db
* @description If True, models and config are stored in and loaded from the database. Default is False.
@@ -32444,6 +32446,37 @@ export interface components {
[key: string]: unknown;
};
};
+ /**
+ * ScheduledJobStaggerSettings
+ * @description Spreads the proxy's scheduled background jobs across a window instead of firing them
+ * all on one instant, on every replica, forever.
+ */
+ ScheduledJobStaggerSettings: {
+ /**
+ * Enabled
+ * @description apply deterministic phase offsets to scheduled background jobs
+ * @default true
+ */
+ enabled: boolean;
+ /**
+ * Identity
+ * @description replaces the POD_NAME/HOSTNAME-derived component of the offset hash. Set this when replicas share a hostname and would otherwise land on the same offset
+ */
+ identity?: string | null;
+ /**
+ * Offsets
+ * @description explicit offset in seconds per scheduler job id, overriding the derived value. 0 pins a job to its unshifted schedule
+ */
+ offsets?: {
+ [key: string]: number;
+ };
+ /**
+ * Window Seconds
+ * @description width of the window jobs are spread over. An interval job is never offset by more than one of its own periods, so it is not delayed past the wait it already has
+ * @default 300
+ */
+ window_seconds: number;
+ };
/**
* SearchTool
* @description Search tool configuration.