Repository navigation
fix(caching): keep an open Redis circuit breaker open and quiet on the sync read and spend counter paths - #40624
Conversation
An open breaker raised a generic Exception on every skipped call, and DualCache caught it and logged a full ERROR traceback each time. Under load that became hundreds of traceback formats per second on every replica and pinned the proxies at 100% CPU. Raise a typed RedisCircuitBreakerOpenError instead and have DualCache return its in-memory result without logging for it. Classify redis-py pool exhaustion (ConnectionError chained from TimeoutError) as a timeout so a latency blip goes through the duration gate. Track a breaker generation so a call admitted before the breaker opened cannot close it, leaving that to the HALF_OPEN probe. Rate limit the LoggingWorker callback-error traceback to one per interval so a stalled logging backend cannot start a second traceback storm. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…date, not a cost tracking failure Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…nstead of per request warning Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR improves Redis-outage behavior by keeping circuit-breaker state stable across concurrent calls, fast-failing synchronous reads, preserving local cache results, and suppressing repetitive open-breaker errors. Changes added since the previous review also include independently tested improvements to streaming usage accounting, concurrent logging metadata snapshots, Claude Code classifier input handling, collector-sidecar connection-pool configuration, rate-limiter headers, and dashboard entity rendering.
Confidence Score: 5/5The reviewed changes appear safe to merge, with no outstanding correctness, security, or repository-rule issue identified. All prior Redis circuit-breaker findings are either fully addressed or resolved. mateo-berri accepted the low-probability stale-success recovery timing caveat, noting that it requires a call to outlive the complete recovery timeout; the generation-bound admission logic additionally prevents stale calls and overtaken probes from closing a newer breaker state. mateo-berri also correctly disputed the detached-write finding because the queue-clearing and detached scheduling behavior predated this PR, and Greptile withdrew it. No new blocking or non-blocking actionable issue was established.
|
| Filename | Overview |
|---|---|
| litellm/caching/redis_cache.py | Adds generation-aware circuit-breaker admission, guarded synchronous reads, and correctly formatted failure accounting. |
| litellm/caching/dual_cache.py | Rolls back batch reservations and returns available in-memory hits when an open breaker refuses Redis. |
| litellm/router_strategy/budget_limiter.py | Keeps Redis pushes detached from request callbacks while retrieving and appropriately logging task failures. |
| litellm/proxy/proxy_server.py | Quietly drops open-breaker spend increments after invalidating potentially stale local counters. |
| litellm/litellm_core_utils/litellm_logging.py | Snapshots mutable metadata and headers before iteration to avoid concurrent-mutation failures. |
| litellm/utils.py | Reorders response metadata finalization and success logging and adds mock-stream usage support. |
| litellm/router_strategy/complexity_router/complexity_router.py | Omits Claude Code harness system text from classifier input based on request metadata. |
| helm/litellm/templates/gateway/deployment.yaml | Gives the collector sidecar local connection-pool settings when pooling is enabled. |
| ui/litellm-dashboard/src/components/VirtualKeysPage/keyTableColumns.tsx | Refactors virtual-key table rendering through shared entity and user cell components. |
Reviews (13): Last reviewed commit: "chore(ui): regenerate schema.d.ts after ..." | Re-trigger Greptile
…timeout check Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…r quiet when the breaker is open The sync RedisCache.get_cache ran outside the breaker and logged with a stray positional argument, so every failure printed a logging-module stack dump. Cache.add_cache and its async twins logged a full traceback for the expected open-breaker fast fail Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…le worker tracebacks per error type Swallowed failures are now reported to the breaker when the admitted call exits, so a call admitted before the breaker opened cannot refresh the open timer or knock out the recovery probe. The sync batch read raises the typed open-breaker error like its async twin so DualCache releases its batch reservations, and LoggingWorker throttles tracebacks per exception class instead of worker-wide Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…rded call swallowed batch_cache_write flushes through async_set_cache_pipeline, both guarded. The inner guard consumed the swallowed pipeline failure and the outer then recorded a success, so a dead Redis never tripped the breaker on the batch write path. Only the outermost admission now reports, and the sync batch read runs under the same guard. Also covers the sync add_cache and embedding pipeline wrappers, the increment pipeline, sadd, and the stale raise path in tests. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…en_silent_miss Take the staging tree outright. #40620 already landed the typed RedisCircuitBreakerOpenError, DEBUG-level refusal logging at every DualCache, Cache, limiter, and router catch site, and sync timeout classification, so the overlapping parts of this branch are superseded. The pieces that are still missing on staging are rebuilt on top in the next commit
|
Closing: #40620 landed the traceback fix on staging and the remaining hardening is being rescoped in a separate PR |
…ad and spend counter paths The sync get path was unguarded, logged with a stray format argument, and never fed the breaker. The sync batch read swallowed the breaker's refusal as an ERROR plus a service failure event per call, so DualCache dropped its in-memory hits and left batch reservations behind. record_success closed an OPEN breaker on stale in-flight successes, skipping the recovery timeout and the half-open probe. The spend counter pipeline re-raised the refusal into the cost callback, which logged an ERROR and fired the failed-tracking alert per request.
1 similar comment
…th state cache The sync Redis read now raises while the circuit breaker is open, and the health state merge caught that as a generic error, skipping the local write and logging an error on every background health check cycle. Read the shared snapshot through a helper that treats the refused read as a miss so the merge falls back to the pod-local copy the way a swallowed connection error already did
…aker A call admitted before the breaker opened could finish while the breaker was HALF_OPEN and close it before the designated probe reported, so Redis traffic resumed on a stale answer. The admission now records whether the call is the probe and only the probe's success closes a half-open breaker. The cron job lock manager also logged an error every cycle the open breaker refused its Redis call, one line per job per pod. That refusal is now a debug line like every other guarded call, while real Redis errors still log at error
…at admitted the call
1 similar comment
|
bugbot run |
…edis breaker is open
The provider budget push runs inside the request success callback, so awaiting the Redis pipeline there made every request wait for the round trip. Hand it back to a task whose failure is logged through the breaker aware logger, so an open breaker stays a debug line and a real Redis error is one error line instead of an unretrieved task traceback
| queued: Final = self.redis_increment_operation_queue | ||
| self.redis_increment_operation_queue = [] | ||
| if queued: | ||
| asyncio.create_task(_push_increments_to_redis(self.dual_cache.redis_cache, queued)) |
There was a problem hiding this comment.
The increment queue is cleared before the Redis write starts in an untracked task. If shutdown cancels that task after the request callback finishes, the increments are not restored or retried. Redis can then undercount provider spend, weakening budget enforcement across instances. This is non-blocking, but retaining and draining these tasks during shutdown—or preserving increments until the write completes—would avoid that loss.
There was a problem hiding this comment.
The base already scheduled this write as a detached task and cleared the queue. This commit only retrieves its failure, so shutdown loss is unchanged
There was a problem hiding this comment.
You're right. The base implementation already cleared the queue before scheduling the detached increment task, so shutdown cancellation could lose those increments before this PR as well. This change only wraps the same detached operation to consume and log failures; it does not introduce or worsen that behavior. I'll withdraw this comment as non-actionable for this PR.
…itellm_redis_breaker_open_silent_miss
|
bugbot run |
There was a problem hiding this comment.
✅ 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 25ed0ab. Configure here.
…erriAI#40624) (cherry picked from commit ff4b558)
TLDR
Problem this solves:
No deployments availableon every request while the breaker is open, because the refused batch read comes back as no data at allHow it solves it:
User Flow
Before: requests still succeed while Redis is down, but each proxy writes about 10,000 log lines and 370 tracebacks for 300 requests, a flapping Redis reopens the breaker seven times in two seconds, and with usage-based routing on every request answers 429 once the breaker opens
POST https://litellm-domain/v1/chat/completions,POST https://litellm-domain/v1/responses, andPOST https://litellm-domain/v1/messagesforgpt-5.4-nano: every request returns 200Redis circuit breaker OPENEDonce for each Redis client in each workerError in tracking cost callback - Redis circuit breaker is openline at ERROR/v1/responsesand/v1/messagesrequest adds a--- Logging error ---block with two tracebacksError acquiring Redis lockline at ERROROPENEDlines inside two seconds with noCLOSEDbetween them, because every success that slipped through closed the breaker and the next five failures reopened itusage-based-routing-v2with a provider budget and repeat the outage: every request after the breaker opens returns 429No deployments available for selected model, and the log adds anError syncing in-memory cache with Redisline every second plus aTask exception was never retrievedtracebackAfter: the same outage produces one
OPENEDline per Redis client and one well-formed line per real failure, a flapping Redis opens the breaker once per client for the full recovery window, and usage-based routing keeps answering 200 from its local countersPOST https://litellm-domain/v1/chat/completions,POST https://litellm-domain/v1/responses, andPOST https://litellm-domain/v1/messagesforgpt-5.4-nano: every request returns 200Redis circuit breaker OPENEDonce for each Redis client in each worker--- Logging error ---block appears on/v1/responsesor/v1/messages; each real Redis failure before the breaker opened is one line naming the errorError acquiring Redis lockline is logged while the breaker is openOPENEDper Redis client, held for the full 60 s window, then oneCLOSEDfrom the recovery probeusage-based-routing-v2with a provider budget and repeat the outage: every request returns 200, routed from the local usage counters, and the log shows no sync error and no task traceback while the breaker is openRelevant issues
Linear ticket
Resolves LIT-7518
Finishes the quiet-open-breaker guarantee from LIT-7468 on the paths #40620 did not cover. Pool exhaustion still counting as a hard connectivity failure is tracked separately in LIT-7542
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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@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
Both legs run the same rig against real OpenAI spend on
gpt-5.4-nano. Before is the merge base8a4fae0e17, After is this branch at2fc520329f. The two commits on top of it merge the base and regenerateschema.d.tsfor the schema check, and none of the base commits merged in (through7419a536ad) touch the files this PR changes or the Redis, breaker, and router sync paths these legs exercise, so both legs stand as run. Each leg boots a localredis-serveron a random free port plus two proxies A and B, each started with--num_workers 2andLITELLM_LOG=WARNING, pointed at a fresh Postgres databaselitellm_lit7518_qa(dropped, created, andprisma db pushed right before the Before leg) and at that Redis for both the cache and the router. Background health checks run every 5 s with health check routing on, so each worker merges its health snapshot through Redis every cycle and the merge's Redis read gets refused while the breaker is open. The proxies get three healthy bursts of 40 requests at concurrency 10 on/v1/chat/completions,/v1/responses, and/v1/messages, thenredis-serveris killed and the same three endpoints get 100 requests each at concurrency 30 with the breaker open. Every burst alternates requests between the two proxies. Avg proxy CPU% per burst is the mean over 0.5 s samples ofps -o %cpu=summed across every proxy process, the two parents plus the fourspawn_mainuvicorn workers. The last case swaps the setup for a single-worker proxy that reaches Redis through a small TCP relay withsocket_timeout: 0.1incache_params, runs two 25 s fault windows through the relay under a 2500 request storm (a 0.3 s latency blip as the ticket describes, then a window where the relay closes 20% of connections so hard failures interleave with successes), and after each window sends 20 more requests once the 60 s recovery window has passed so a CLOSED transition has a chance to show. That proxy runs atLITELLM_LOG=INFObecause the breaker logs its CLOSED transition at info levelThe blip case uses the same yaml with
cache_params.portandrouter_settings.redis_portpointing at the relay andsocket_timeout: 0.1added undercache_params. The relay is the script below: it forwards bytes between the proxy and Redis and re-reads a control file on every read, where a number is a delay in seconds added to each forwarded read anddrop <p>closes the connection with probability p on each readBefore (8a4fae0)
Redis healthy: /v1/chat/completions
burst healthy /v1/chat/completions "$CHAT" 40 1040 200, avg proxy CPU during burst 19%Redis healthy: /v1/responses
burst healthy /v1/responses "$RESP" 40 1040 200, avg proxy CPU during burst 19%Redis healthy: /v1/messages
burst healthy /v1/messages "$MSGS" 40 1040 200, avg proxy CPU during burst 13%Redis gone, breaker open: /v1/chat/completions
kill %1(redis-server,redis-cli -p $REDIS_PORT pingnow says connection refused) thenburst open /v1/chat/completions "$CHAT" 100 30100 200, avg proxy CPU during burst 40%Redis gone, breaker open: /v1/responses
burst open /v1/responses "$RESP" 100 30100 200, avg proxy CPU during burst 37%Redis gone, breaker open: /v1/messages
burst open /v1/messages "$MSGS" 100 30100 200, avg proxy CPU during burst 40%Per-proxy log stats after all 420 requests
for f in proxy_*.log; do grep -c '^Traceback (most recent call last)' $f; grep -c 'LiteLLM.*ERROR' $f; grep -c -- '--- Logging error ---' $f; grep -c 'set_deployment_health_states - Exception' $f; grep -c 'Error acquiring Redis lock' $f; wc -l < $f; done--- Logging error ---dumps, 0set_deployment_health_states - Exceptionlines, 5 and 6Error acquiring Redis locklines, 10,555 and 10,627 log lines per proxy process. The merge base never guards the sync Redis read with the breaker, so every sync read while Redis is down goes to the socket, gets connection refused, and lands in a brokenlogger.errorcall whose dump is what the--- Logging error ---count measures; 7 or 8 of those per proxy come from the background health check merge, the rest from the sync cache reads that/v1/responsesand/v1/messagesmake through the thread poolgrep -h 'ERROR\|WARNING' proxy_*.log | sed 's/^[0-9:]* - //' | sort | uniq -c | sort -rn | head -8self._log(ERROR, msg, args, **kwargs)lines are the--- Logging error ---dumps, each one followed by two tracebacks):Redis latency blip: breaker state changes
blip latency 0.3(2500 requests at concurrency 40, relay adds 0.3 s to every Redis read from 5 s to 30 s into the load, then 20 probe requests 65 s after the OPENED line)2500 200for the load,20 200for the probe,1OPENED,1CLOSED. Every call in flight during the blip times out, so the breaker opens once on the timeout streak and stays open until the probe after the recovery window closes it:blip drop "drop 0.2"(same load, relay closes 20% of connections instead of delaying them, so the proxy sees hard connection errors mixed with successful calls)2500 200for the load,20 200for the probe,7OPENED,1CLOSED. Every success that lands while the breaker is open silently closes it, so the next 5 hard failures reopen it again and the log shows 7 OPENED lines inside 2 s with no CLOSED line between them. The one CLOSED line comes 64 s later from the background health check's Redis call after the recovery window:After (2fc5203)
Redis healthy: /v1/chat/completions
burst healthy /v1/chat/completions "$CHAT" 40 1040 200, avg proxy CPU during burst 15%Redis healthy: /v1/responses
burst healthy /v1/responses "$RESP" 40 1040 200, avg proxy CPU during burst 9%Redis healthy: /v1/messages
burst healthy /v1/messages "$MSGS" 40 1040 200, avg proxy CPU during burst 9%Redis gone, breaker open: /v1/chat/completions
kill %1(redis-server,redis-cli -p $REDIS_PORT pingnow says connection refused) thenburst open /v1/chat/completions "$CHAT" 100 30100 200, avg proxy CPU during burst 29%Redis gone, breaker open: /v1/responses
burst open /v1/responses "$RESP" 100 30100 200, avg proxy CPU during burst 17%Redis gone, breaker open: /v1/messages
burst open /v1/messages "$MSGS" 100 30100 200, avg proxy CPU during burst 27%Per-proxy log stats after all 420 requests
for f in proxy_*.log; do grep -c '^Traceback (most recent call last)' $f; grep -c 'LiteLLM.*ERROR' $f; grep -c -- '--- Logging error ---' $f; grep -c 'set_deployment_health_states - Exception' $f; grep -c 'Error acquiring Redis lock' $f; wc -l < $f; done--- Logging error ---dumps, 0set_deployment_health_states - Exceptionlines, 0Error acquiring Redis locklines, 308 and 308 log lines per proxy process. The ERROR lines left are the connection refused errors from the calls that hit the socket before each breaker opened. The background health check merge treats the refused Redis read as a miss and keeps writing its local copy, the pod lock for the health check DB save logs the open breaker at debug, and the spend counter updates drop quietly, so none of them shows up at ERROR any moregrep -h 'ERROR\|WARNING' proxy_*.log | sed 's/^[0-9:]* - //' | sort | uniq -c | sort -rn | head -8Redis latency blip: breaker state changes
blip latency 0.3(2500 requests at concurrency 40, relay adds 0.3 s to every Redis read from 5 s to 30 s into the load, then 20 probe requests 65 s after the OPENED line)2500 200for the load,20 200for the probe,1OPENED,1CLOSED. Same shape as the merge base: every call in flight during the blip times out, the breaker opens once on the timeout streak, and the probe after the recovery window closes it:blip drop "drop 0.2"(same load, relay closes 20% of connections instead of delaying them, so the proxy sees hard connection errors mixed with successful calls)2500 200for the load,20 200for the probe,1OPENED,1CLOSED. A success that lands while the breaker is open no longer closes it, so the Redis client whose calls hit 5 hard failures inside the window (the relay drops connections at random, so on this run only one of the proxy's two clients, the proxy cache or the router cache, tripped) opened its breaker once and stayed open for the whole 60 s window instead of flapping. Only the recovery probe after the window closes it, here 65 s later as the 20 probe requests began:Usage-based routing while the breaker is open
The routing case swaps the setup for a single-worker proxy with two
gpt-5.4-nanodeployments in one group underusage-based-routing-v2and a provider budget, so the router's usage sync loop and the provider budget sync loop both run against Redis, atLITELLM_LOG=WARNING. Redis is killed after a healthy burst, then the same 20 requests run right after the kill and again 30 s later with the breaker openBefore (8a4fae0)
burstwith Redis up:20 200kill %1thenburstright after Redis died:20 200, the breaker has not opened yetburst30 s later with the breaker open:20 429. The refused batch read comes back as no data at all, so the router sees no deployment it can pickstats:lines=254 sync_errors=39 unretrieved=2 tracebacks=3After (2fc5203)
burstwith Redis up:20 200kill %1thenburstright after Redis died:20 200burst30 s later with the breaker open:20 200, routed from the in-memory usage countersstats:lines=121 sync_errors=2 unretrieved=0 tracebacks=0. The two sync errors are the connection refused failures from the pushes that reached the socket before the breaker opened, logged once each from the push taskType
🐛 Bug Fix
Caveats (if any)
Medium
Low
not found or expiredwhile the breaker is openFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/104607cf41f042a785c583a2eee31505
Open in Devin Desktop: https://app.devin.ai/desktop/session/104607cf41f042a785c583a2eee31505?variant=devin