Skip to content

fix(router): await budget redis pipeline before sync reads - #32618

Closed
emerzon wants to merge 13 commits into
BerriAI:mainfrom
emerzon:litellm_budget_sync_race_backport
Closed

emerzon wants to merge 13 commits into
BerriAI:mainfrom
emerzon:litellm_budget_sync_race_backport

Conversation

@emerzon

@emerzon emerzon commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Router budget sync can replace live spend with an older Redis value
  • A logging timeout can drop spend already taken off the queue
  • Virtual-key model budgets crash if the Redis queue lock is missing

How it solves it:

  • Await the Redis increment pipeline before reading spend back
  • Shield the write and cleanup task; restore the batch if Redis fails
  • Skip the Redis-to-memory overwrite when the flush did not land
  • Initialize the same queue lock on the virtual-key model budget limiter

A flush task owns the detached batch through the Redis write and its cleanup. Cancellation waits for that task to finish, including while the flush waits for its lock and after repeated cancellation, so an applied batch is not replayed. Failed writes coalesce retained increments by spend key, keep the latest TTL, and skip the Redis read. Synchronization merges spend queued during Redis I/O under the queue lock, and the flush lock serializes overlapping syncs. The virtual-key model budget limiter initializes the inherited queue state

User Flow

Before: a team with a tight provider budget keeps getting completions after spend should have blocked them, and a slow Redis flush plus a logging timeout can let an authenticated client keep spending past the budget

  1. The admin sets a bedrock budget_limit of 0.00001 for 1d on the proxy router
  2. Their app sends POST https://litellm-domain/v1/chat/completions until the first request costs more than 0.00001
  3. The next POST https://litellm-domain/v1/chat/completions still returns 200 instead of a budget exceeded error
  4. Another authenticated client with the same key can keep sending costly requests while Redis is delayed and continue past the configured budget

After: spend stays at the recorded value once logging finishes, later requests are blocked, and a cancelled Redis flush does not drop the spend that already happened

  1. The admin sets the same bedrock budget_limit of 0.00001 for 1d
  2. Their app sends the same POST https://litellm-domain/v1/chat/completions until the first request costs more than 0.00001
  3. Once the spend callback finishes, the next POST https://litellm-domain/v1/chat/completions returns a budget exceeded error
  4. Another authenticated client with the same key sees the recorded spend after a logging timeout

Relevant issues

Fixes #32614

Refs #20886

Backports #20888 onto main

Linear ticket

Resolves LIT-8390

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • 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

Both revisions used real AWS Bedrock requests and Redis 7.4.4 in a local container. The proxy configuration was the same on each revision

model_list:
  - model_name: bedrock-budget
    litellm_params:
      model: bedrock/converse/global.openai.gpt-5.6-luna
      aws_region_name: us-east-1
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6380
  provider_budget_config:
    bedrock:
      budget_limit: 0.00001
      time_period: 1d
general_settings:
  master_key: sk-pr-maintenance

Before (238f434)

  1. Start the main proxy on port 4300 and clear the isolated Redis database

    docker exec litellm-pr32618-redis redis-cli FLUSHDB
  2. Send the same request twice

    for n in 1 2; do
      curl -sS -o /tmp/budget-before-$n.json -w "HTTP %{http_code}\n" http://127.0.0.1:4300/v1/chat/completions \
        -H 'Authorization: Bearer sk-pr-maintenance' -H 'Content-Type: application/json' \
        -d '{"model":"bedrock-budget","messages":[{"role":"user","content":"Reply pong"}],"max_tokens":64}'
    done
  3. Observe HTTP 200, then HTTP 200. Both responses contain pong although the first request cost $0.0000152, above the $0.00001 budget

After (e817a974cd36)

  1. Start the PR proxy on port 4301 with the same configuration and clear the isolated Redis database, then restart the proxy so its in-memory budget state is empty too

    docker exec litellm-pr32618-redis redis-cli FLUSHDB
  2. Send the request twice two seconds apart, wait five more seconds, then send it a third time

    for n in 1 2; do
      curl -sS -o /tmp/budget-current-$n.json -w "request=$n HTTP %{http_code} bytes=%{size_download}\n" \
        http://127.0.0.1:4301/v1/chat/completions \
        -H 'Authorization: Bearer sk-pr-maintenance' -H 'Content-Type: application/json' \
        -d '{"model":"bedrock-budget","messages":[{"role":"user","content":"Reply pong"}],"max_tokens":64}'
      sleep 2
    done
    sleep 5
    curl -sS -o /tmp/budget-current-3.json -w "request=3 HTTP %{http_code} bytes=%{size_download}\n" \
      http://127.0.0.1:4301/v1/chat/completions \
      -H 'Authorization: Bearer sk-pr-maintenance' -H 'Content-Type: application/json' \
      -d '{"model":"bedrock-budget","messages":[{"role":"user","content":"Reply pong"}],"max_tokens":64}'
  3. Observe the first request return 200, the second return 200 while spend logging is still in flight, and the third return 429 with Exceeded budget for provider bedrock: 1.52e-05 >= 1e-05. Redis held 0.0000152 spend, above the configured 0.00001 budget

    request=1 HTTP 200 bytes=526
    request=2 HTTP 200 bytes=526
    request=3 HTTP 429 bytes=181
    

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Low

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

Note

Medium Risk
Changes async spend accounting on the request logging hot path and multi-instance Redis sync; mistakes could mis-enforce budgets, but behavior is narrowly scoped and heavily tested.

Overview
Fixes router and proxy budget spend getting out of sync with Redis, which could let traffic continue after a cap was exceeded.

Router budget limiting no longer fires Redis increment pipelines in a detached task. Spend flushes are serialized with queue/flush locks, awaited before periodic sync reads Redis, and use asyncio.shield so a cancelled callback still finishes an in-flight write. Failed pipelines re-queue detached increments (coalesced per spend key); successful writes are not replayed on cancel. When copying Redis into memory, pending queue increments are added so a read cannot wipe live in-memory spend.

Virtual-key model max budgets initialize the same Redis increment queue locks/state (they skip the parent __init__), so keyed model budgets use the same safe flush path.

Tests cover ordering (pipeline before batch_get), failure/requeue, cancellation, and concurrent increments during Redis I/O.

Reviewed by Cursor Bugbot for commit d3b1ddc. Bugbot is set up for automated code reviews on this repo. Configure here.

@codecov

codecov Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.18519% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router_strategy/budget_limiter.py 84.61% 16 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing emerzon:litellm_budget_sync_race_backport (d3b1ddc) with main (f3cf1cd)

Open in CodSpeed

@emerzon

emerzon commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@greptile-apps

@greptile-apps

greptile-apps Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Adds synchronization locks to budget tracking Redis operations.

Safe to merge. The changes are narrowly scoped to the Redis increment flush and sync path, the locking invariants are consistent, and the extensive mock test suite validates every documented edge case including cancellation, failure requeue, coalescing, and the ordering guarantee between the pipeline write and the batch-get read.

Summary

This PR fixes a race condition where in-flight Redis pipeline writes could be dropped or overwritten during periodic spend synchronization, causing provider budgets to allow spend past their configured limits. It also fixes a crash in the virtual-key model budget limiter when the shared queue locks were not initialized.

  • RouterBudgetLimiting now protects the increment queue with an asyncio.Lock, detaches batches before writing, awaits the Redis pipeline inside _push_in_memory_increments_to_redis, requeues increments on failure (coalescing by key), and merges pending queue entries into the Redis sync read so concurrent logging is not wiped.
  • _PROXY_VirtualKeyModelMaxBudgetLimiter.__init__ now initializes _redis_increment_queue_lock, _redis_increment_flush_lock, and _detached_increment_operations to match the inherited flush path.
  • New mock-only tests cover pipeline ordering, cancellation safety, failure requeue, coalescing, and double-apply prevention.

Reviews (21) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

@emerzon
emerzon force-pushed the litellm_budget_sync_race_backport branch from bd9d1be to 942f482 Compare August 12, 2026 17:13
@emerzon

emerzon commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Updated and rebased this pull request; @greptile-apps, please review the latest changes and flag any remaining concerns.

@emerzon
emerzon marked this pull request as ready for review August 22, 2026 01:01
Copilot AI lite review requested due to automatic review settings August 22, 2026 01:01

Copilot AI left a comment

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.

Pull request overview

This PR backports a fix to the router budget limiter so Redis increment pipeline flushes are awaited before sync reads, preventing stale Redis values from overwriting in-memory spend. It also initializes the same queue lock in the proxy model-budget limiter subclass and adds regression tests covering the race and failure requeue behavior

Changes:

  • Await Redis increment pipeline flushes (with a locked queue snapshot) before performing Redis sync reads
  • Add a per-instance lock for the Redis increment queue, including in _PROXY_VirtualKeyModelMaxBudgetLimiter
  • Add regression tests for awaiting the pipeline, requeueing on failures, and preserving new increments during a failed flush

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
litellm/router_strategy/budget_limiter.py Adds a lock-protected increment queue snapshot and awaits Redis pipeline before sync reads
litellm/proxy/hooks/model_max_budget_limiter.py Initializes the inherited Redis increment queue lock in the subclass initializer
tests/test_litellm/router_strategy/test_budget_limiter.py Adds regression tests for the sync race and requeue semantics on Redis pipeline failure
tests/proxy_unit_tests/test_unit_test_max_model_budget_limiter.py Adds a regression test ensuring the subclass initializes the lock used by the inherited increment path

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@veria-ai

veria-ai Bot commented Aug 22, 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: 4 · PR risk: 0/10

@emerzon
emerzon force-pushed the litellm_budget_sync_race_backport branch from 72d95d8 to 6498d2f Compare August 22, 2026 01:39
@emerzon

emerzon commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest staging and addressed the Copilot and Veria review notes in 6498d2f93b. @greptile-apps please re-review

@emerzon
emerzon force-pushed the litellm_budget_sync_race_backport branch from 6498d2f to 5bfcc99 Compare August 30, 2026 14:40
@emerzon

emerzon commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest litellm_internal_staging so lint can load .github/actions/detect-changes.

@emerzon

emerzon commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: extracted Redis copy-after-flush so C901 stays within the strict budget.

@emerzon

emerzon commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the empty-flush budget sync bug so later Redis increments are not dropped.

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:29
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@emerzon
emerzon changed the base branch from litellm_internal_staging to main September 15, 2026 17:23
@emerzon
emerzon requested a review from a team September 15, 2026 17:23
@emerzon
emerzon force-pushed the litellm_budget_sync_race_backport branch from fb82c4f to 45a7bf9 Compare September 15, 2026 17:28
@emerzon

emerzon commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main and verified focused tests locally. @greptileai @veria-ai please review the current tip for regressions

bugbot run

@emerzon

emerzon commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the CI compatibility findings and pushed the updated tip. @greptileai @veria-ai please review these latest changes

bugbot run

@emerzon

emerzon commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run Please review tip 5885eef after rebasing onto current main; the unrelated batch marker issue remains tracked in #42627

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai @veria-ai Please review tip 7e82f1f. The duplicate test file is removed, and 89 focused tests plus make check pass

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run Please review tip 7e82f1f. The Redis tests now live in the mapped hot-path file, with behavior unchanged

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review tip 7e82f1f. Veria skipped this test-only follow-up; all required CI and patch coverage now pass

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai @veria-ai Please review tip 2ec5918. Failed Redis increments now coalesce by key; 94 focused budget tests and make check pass

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run Please review tip 2ec5918. Redis outage retries now retain exact spend with one queued operation per key

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai @veria-ai Please review tip 1a40105. Private-state assertions are removed; 94 focused budget tests and make check pass

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run Please review tip 1a40105. This test-only follow-up removes detached-batch assertions while retaining spend and recovery coverage

@cursor cursor Bot left a comment •

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.

Stale Bugbot comment from a previous run.

@emerzon

emerzon commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Current-tip CI and patch coverage pass; Greptile is 5/5, Bugbot and Veria are clear. @mateo-berri, please review the Redis synchronization fix

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit d3b1ddc. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor

Superseded by #43125, an internal copy of this branch at d3b1ddc with your commits and authorship intact so CircleCI can build it. Thanks!

mateo-berri added a commit that referenced this pull request Sep 25, 2026
…copy of #32618) (#43125)

* fix(router): await budget redis pipeline before sync reads

* refactor(router): remove superseded Redis flush helper

* fix(router): preserve concurrent spend during Redis synchronization

* fix(router): type per-key spend totals without loop Final bindings

* fix(router): log Redis failures before cancellable cleanup

* fix(router): finalize Redis batches before propagating cancellation

* test(router): reproduce cancellation while Redis cleanup is blocked

* test: align budget hotpath checks with awaited Redis flush

* fix(budgets): finish Redis flush after cancellation while queued

* test(budgets): consolidate Redis regressions in mapped tests

* fix(budgets): coalesce failed Redis increments by key

* test(budgets): assert spend behavior instead of batch state

* perf(router): sum pending budget spend by key once per sync

---------

Co-authored-by: Emerson Gomes <emerson.gomes@thalesgroup.com>
Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Router budget sync can overwrite memory cache with stale Redis spend

4 participants