Skip to content

fix(caching): keep an open Redis circuit breaker open and quiet on the sync read and spend counter paths - #40624

Merged
mateo-berri merged 16 commits into
litellm_internal_stagingfrom
litellm_redis_breaker_open_silent_miss
Sep 11, 2026
Merged

mateo-berri merged 16 commits into
litellm_internal_stagingfrom
litellm_redis_breaker_open_silent_miss

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A success from a call admitted before the trip closes an open or half-open breaker
  • The breaker then reopens on the next failure and logs OPENED again
  • The sync Redis read skips the breaker and hits Redis on every call
  • Its error log is malformed, so each failure dumps a logging traceback
  • /v1/responses and /v1/messages use that read, so they stay noisy
  • Spend counter updates log an error per request while the breaker is open
  • A refused sync batch read keeps its keys throttled for the next reader
  • Usage-based routing answers 429 No deployments available on every request while the breaker is open, because the refused batch read comes back as no data at all
  • Every cron job logs an error each cycle it cannot take its Redis lock while the breaker is open
  • The usage-based routing and provider budget sync loops log an error per cycle while the breaker is open, and the budget push leaks an unretrieved task traceback

How it solves it:

  • A success closes the breaker only if the breaker has not moved since that call was admitted
  • The sync read runs under the breaker and feeds it its failures
  • Its error log is one well-formed line per real failure
  • Spend counter updates drop quietly and invalidate their local copy
  • A refused batch read releases its keys and returns the in-memory hits, so usage-based routing keeps routing from its local counters
  • The CLI login lookup and the health check state merge treat a refused read as a plain miss
  • A cron job lock refused by the open breaker is a debug line, not an error per cycle
  • The routing and budget sync loops log a refused push at debug, and the budget push task logs its own failure instead of leaking 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

  1. Start the proxy with a Redis cache and send POST https://litellm-domain/v1/chat/completions, POST https://litellm-domain/v1/responses, and POST https://litellm-domain/v1/messages for gpt-5.4-nano: every request returns 200
  2. Redis goes down
  3. Keep sending the same three requests: every request still returns 200
  4. The proxy log shows Redis circuit breaker OPENED once for each Redis client in each worker
  5. Almost every request during the outage adds an Error in tracking cost callback - Redis circuit breaker is open line at ERROR
  6. Every /v1/responses and /v1/messages request adds a --- Logging error --- block with two tracebacks
  7. Each cron cycle that cannot take its Redis lock adds an Error acquiring Redis lock line at ERROR
  8. After 300 requests during the outage each proxy has written about 10,500 log lines and 370 tracebacks
  9. Redis comes back but drops a fifth of its connections for 25 s: the log shows seven OPENED lines inside two seconds with no CLOSED between them, because every success that slipped through closed the breaker and the next five failures reopened it
  10. Switch the router to usage-based-routing-v2 with a provider budget and repeat the outage: every request after the breaker opens returns 429 No deployments available for selected model, and the log adds an Error syncing in-memory cache with Redis line every second plus a Task exception was never retrieved traceback

After: the same outage produces one OPENED line 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 counters

  1. Start the proxy with a Redis cache and send POST https://litellm-domain/v1/chat/completions, POST https://litellm-domain/v1/responses, and POST https://litellm-domain/v1/messages for gpt-5.4-nano: every request returns 200
  2. Redis goes down
  3. Keep sending the same three requests: every request still returns 200
  4. The proxy log shows Redis circuit breaker OPENED once for each Redis client in each worker
  5. No cost tracking error is logged per request; key and team budgets keep being enforced from the proxy's local counters until Redis is back
  6. No --- Logging error --- block appears on /v1/responses or /v1/messages; each real Redis failure before the breaker opened is one line naming the error
  7. No Error acquiring Redis lock line is logged while the breaker is open
  8. After 300 requests during the outage each proxy has written about 310 log lines and no tracebacks
  9. Redis comes back but drops a fifth of its connections for 25 s: the log shows one OPENED per Redis client, held for the full 60 s window, then one CLOSED from the recovery probe
  10. Switch the router to usage-based-routing-v2 with 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 open

Relevant 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

  • 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 legs run the same rig against real OpenAI spend on gpt-5.4-nano. Before is the merge base 8a4fae0e17, After is this branch at 2fc520329f. The two commits on top of it merge the base and regenerate schema.d.ts for the schema check, and none of the base commits merged in (through 7419a536ad) 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 local redis-server on a random free port plus two proxies A and B, each started with --num_workers 2 and LITELLM_LOG=WARNING, pointed at a fresh Postgres database litellm_lit7518_qa (dropped, created, and prisma 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, then redis-server is 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 of ps -o %cpu= summed across every proxy process, the two parents plus the four spawn_main uvicorn workers. The last case swaps the setup for a single-worker proxy that reaches Redis through a small TCP relay with socket_timeout: 0.1 in cache_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 at LITELLM_LOG=INFO because the breaker logs its CLOSED transition at info level

model_list:
  - model_name: gpt-5.4-nano
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: 127.0.0.1
    port: ${REDIS_PORT}

router_settings:
  redis_host: 127.0.0.1
  redis_port: ${REDIS_PORT}
  enable_health_check_routing: true

general_settings:
  master_key: sk-qa-breaker-1234
  database_url: os.environ/DATABASE_URL
  background_health_checks: true
  health_check_interval: 5
redis-server --port $REDIS_PORT --save "" --appendonly no &
LITELLM_LOG=WARNING litellm --config config.yaml --port $PORT_A --num_workers 2 > proxy_a.log 2>&1 &
LITELLM_LOG=WARNING litellm --config config.yaml --port $PORT_B --num_workers 2 > proxy_b.log 2>&1 &

CHAT='{"model":"gpt-5.4-nano","max_tokens":16,"messages":[{"role":"user","content":"request IDX: reply with one word"}]}'
RESP='{"model":"gpt-5.4-nano","max_output_tokens":16,"input":"request IDX: reply with one word"}'
MSGS='{"model":"gpt-5.4-nano","max_tokens":16,"messages":[{"role":"user","content":"request IDX: reply with one word"}]}'

burst() { seq 1 $4 | xargs -P $5 -n 1 sh -c '
  i=$1; port=$([ $((i % 2)) -eq 0 ] && echo '"$PORT_A"' || echo '"$PORT_B"')
  curl -s -o /dev/null -w "%{http_code}\n" -m 60 http://127.0.0.1:$port'"$2"' \
    -H "Authorization: Bearer sk-qa-breaker-1234" -H "Content-Type: application/json" \
    -d "$(printf %s '"'$3'"' | sed "s/IDX/$i/")"
' _ | sort | uniq -c; }

burst healthy /v1/chat/completions "$CHAT" 40 10
burst healthy /v1/responses "$RESP" 40 10
burst healthy /v1/messages "$MSGS" 40 10
kill %1   # redis-server
burst open /v1/chat/completions "$CHAT" 100 30
burst open /v1/responses "$RESP" 100 30
burst open /v1/messages "$MSGS" 100 30

The blip case uses the same yaml with cache_params.port and router_settings.redis_port pointing at the relay and socket_timeout: 0.1 added under cache_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 and drop <p> closes the connection with probability p on each read

import asyncio, random, sys, pathlib
LISTEN, TARGET, CTRL = int(sys.argv[1]), int(sys.argv[2]), pathlib.Path(sys.argv[3])
def mode() -> tuple[float, float]:
    try:
        text = CTRL.read_text().split()
    except Exception:
        return 0.0, 0.0
    if not text:
        return 0.0, 0.0
    if text[0] == "drop":
        return 0.0, float(text[1])
    return float(text[0]), 0.0
async def pump(r, w, other):
    try:
        while True:
            data = await r.read(65536)
            if not data:
                break
            d, p = mode()
            if p and random.random() < p:
                other.close()
                break
            if d:
                await asyncio.sleep(d)
            w.write(data)
            await w.drain()
    except Exception:
        pass
    finally:
        try:
            w.close()
        except Exception:
            pass
async def handle(cr, cw):
    try:
        sr, sw = await asyncio.open_connection("127.0.0.1", TARGET)
    except Exception:
        cw.close(); return
    await asyncio.gather(pump(cr, sw, cw), pump(sr, cw, sw))
async def main():
    srv = await asyncio.start_server(handle, "127.0.0.1", LISTEN)
    async with srv:
        await srv.serve_forever()
asyncio.run(main())
redis-server --port $BLIP_REDIS_PORT --save "" --appendonly no &
echo 0 > delay.txt
python3 lit7518_relay.py $RELAY_PORT $BLIP_REDIS_PORT delay.txt &
LITELLM_LOG=INFO litellm --config config_blip.yaml --port $BLIP_PORT > proxy_blip.log 2>&1 &

storm() { seq 1 $1 | xargs -P $2 -n 1 sh -c 'curl -s -o /dev/null -w "%{http_code}\n" -m 60 \
  http://127.0.0.1:'"$BLIP_PORT"'/v1/chat/completions \
  -H "Authorization: Bearer sk-qa-breaker-1234" -H "Content-Type: application/json" \
  -d "{\"model\":\"gpt-5.4-nano\",\"messages\":[{\"role\":\"user\",\"content\":\"say hi $1\"}],\"max_tokens\":5}"' _; }
blip() {   # $1 = phase name, $2 = relay setting during the fault window
  start=$(wc -l < proxy_blip.log)
  storm 2500 40 > blip_$1_codes.txt &
  sleep 5; echo "$2" > delay.txt; sleep 25; echo 0 > delay.txt; wait
  sleep 65   # let the 60 s recovery window pass, then probe
  storm 20 5 > blip_$1_probe_codes.txt
  sort blip_$1_codes.txt | uniq -c; sort blip_$1_probe_codes.txt | uniq -c
  tail -n +$start proxy_blip.log | grep -c 'circuit breaker OPENED'
  tail -n +$start proxy_blip.log | grep -c 'circuit breaker CLOSED'
  tail -n +$start proxy_blip.log | grep 'circuit breaker OPENED\|circuit breaker CLOSED'
}
blip latency 0.3
blip drop "drop 0.2"

Before (8a4fae0)

Redis healthy: /v1/chat/completions

  1. burst healthy /v1/chat/completions "$CHAT" 40 10
  2. Output: 40 200, avg proxy CPU during burst 19%

Redis healthy: /v1/responses

  1. burst healthy /v1/responses "$RESP" 40 10
  2. Output: 40 200, avg proxy CPU during burst 19%

Redis healthy: /v1/messages

  1. burst healthy /v1/messages "$MSGS" 40 10
  2. Output: 40 200, avg proxy CPU during burst 13%

Redis gone, breaker open: /v1/chat/completions

  1. kill %1 (redis-server, redis-cli -p $REDIS_PORT ping now says connection refused) then burst open /v1/chat/completions "$CHAT" 100 30
  2. Output: 100 200, avg proxy CPU during burst 40%

Redis gone, breaker open: /v1/responses

  1. burst open /v1/responses "$RESP" 100 30
  2. Output: 100 200, avg proxy CPU during burst 37%

Redis gone, breaker open: /v1/messages

  1. burst open /v1/messages "$MSGS" 100 30
  2. Output: 100 200, avg proxy CPU during burst 40%

Per-proxy log stats after all 420 requests

  1. 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
  2. Output: 369 and 371 tracebacks, 137 and 136 ERROR lines, 82 and 83 --- Logging error --- dumps, 0 set_deployment_health_states - Exception lines, 5 and 6 Error acquiring Redis lock lines, 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 broken logger.error call 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/responses and /v1/messages make through the thread pool
  3. grep -h 'ERROR\|WARNING' proxy_*.log | sed 's/^[0-9:]* - //' | sort | uniq -c | sort -rn | head -8
  4. Output (the self._log(ERROR, msg, args, **kwargs) lines are the --- Logging error --- dumps, each one followed by two tracebacks):
 238 LiteLLM Proxy:ERROR: spend_log_error_logger.py:81 - Error in tracking cost callback - Redis circuit breaker is open — skipping async_increment_pipeline
 166     self._log(ERROR, msg, args, **kwargs)
  20 LiteLLM:ERROR: redis_cache.py:1556 - Error occurred in async batch get cache - Error 61 connecting to 127.0.0.1:41013. Connection refused.
   9 LiteLLM Proxy:ERROR: pod_lock_manager.py:112 - Error acquiring Redis lock for background_health_check_db_save: Redis circuit breaker is open — skipping async_set_cache
   8 LiteLLM:WARNING: redis_cache.py:243 - Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
   8     raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
   4 LiteLLM Proxy:WARNING: config_sync_pubsub.py:256 - config sync subscriber redis error: Error 61 connecting to 127.0.0.1:41013. Connection refused.; reconnecting in 20s
   4 LiteLLM Proxy:WARNING: config_sync_pubsub.py:256 - config sync subscriber redis error: Error 61 connecting to 127.0.0.1:41013. Connection refused.; reconnecting in 10s

Redis latency blip: breaker state changes

  1. 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)
  2. Output: 2500 200 for the load, 20 200 for the probe, 1 OPENED, 1 CLOSED. 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:
18:21:24 Redis circuit breaker OPENED after 1222 consecutive failures (0 hard connectivity) — fast-failing Redis calls for 60s
18:22:29 Redis circuit breaker CLOSED — Redis recovered
  1. 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)
  2. Output: 2500 200 for the load, 20 200 for the probe, 7 OPENED, 1 CLOSED. 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:
18:22:39 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:39 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:39 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:40 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:40 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:40 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:22:40 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
18:23:44 Redis circuit breaker CLOSED — Redis recovered

After (2fc5203)

Redis healthy: /v1/chat/completions

  1. burst healthy /v1/chat/completions "$CHAT" 40 10
  2. Output: 40 200, avg proxy CPU during burst 15%

Redis healthy: /v1/responses

  1. burst healthy /v1/responses "$RESP" 40 10
  2. Output: 40 200, avg proxy CPU during burst 9%

Redis healthy: /v1/messages

  1. burst healthy /v1/messages "$MSGS" 40 10
  2. Output: 40 200, avg proxy CPU during burst 9%

Redis gone, breaker open: /v1/chat/completions

  1. kill %1 (redis-server, redis-cli -p $REDIS_PORT ping now says connection refused) then burst open /v1/chat/completions "$CHAT" 100 30
  2. Output: 100 200, avg proxy CPU during burst 29%

Redis gone, breaker open: /v1/responses

  1. burst open /v1/responses "$RESP" 100 30
  2. Output: 100 200, avg proxy CPU during burst 17%

Redis gone, breaker open: /v1/messages

  1. burst open /v1/messages "$MSGS" 100 30
  2. Output: 100 200, avg proxy CPU during burst 27%

Per-proxy log stats after all 420 requests

  1. 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
  2. Output: 0 tracebacks, 14 and 14 ERROR lines, 0 --- Logging error --- dumps, 0 set_deployment_health_states - Exception lines, 0 Error acquiring Redis lock lines, 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 more
  3. grep -h 'ERROR\|WARNING' proxy_*.log | sed 's/^[0-9:]* - //' | sort | uniq -c | sort -rn | head -8
  4. Output:
  13 LiteLLM:ERROR: redis_cache.py:1577 - Error occurred in async batch get cache - Error 61 connecting to 127.0.0.1:21797. Connection refused.
   8 LiteLLM:WARNING: redis_cache.py:250 - Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
   7 LiteLLM:ERROR: redis_cache.py:1380 - litellm.caching.caching: get() - Got exception from REDIS: Error 61 connecting to 127.0.0.1:21797. Connection refused.
   4 LiteLLM Proxy:WARNING: config_sync_pubsub.py:256 - config sync subscriber redis error: Error 61 connecting to 127.0.0.1:21797. Connection refused.; reconnecting in 20s
   4 LiteLLM Proxy:WARNING: config_sync_pubsub.py:256 - config sync subscriber redis error: Error 61 connecting to 127.0.0.1:21797. Connection refused.; reconnecting in 10s
   4 LiteLLM Proxy:WARNING: config_sync_pubsub.py:256 - config sync subscriber redis error: Connection closed by server.; reconnecting in 5s
   4 LiteLLM Proxy:WARNING: billing_metrics.py:218 - Enterprise billing metrics disabled: licensed deployment missing config (LITELLM_BILLING_METRICS_ENDPOINT, LITELLM_BILLING_METRICS_CLIENT_CERT, LITELLM_BILLING_METRICS_CLIENT_KEY)
   4 LiteLLM Proxy:WARNING: auth_cache_invalidation_pubsub.py:175 - auth cache invalidation subscriber redis error: Error 61 connecting to 127.0.0.1:21797. Connection refused.; reconnecting in 20s

Redis latency blip: breaker state changes

  1. 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)
  2. Output: 2500 200 for the load, 20 200 for the probe, 1 OPENED, 1 CLOSED. 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:
19:28:31 Redis circuit breaker OPENED after 1180 consecutive failures (0 hard connectivity) — fast-failing Redis calls for 60s
19:29:35 Redis circuit breaker CLOSED — Redis recovered
  1. 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)
  2. Output: 2500 200 for the load, 20 200 for the probe, 1 OPENED, 1 CLOSED. 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:
19:29:46 Redis circuit breaker OPENED after 5 consecutive failures (5 hard connectivity) — fast-failing Redis calls for 60s
19:30:51 Redis circuit breaker CLOSED — Redis recovered

Usage-based routing while the breaker is open

The routing case swaps the setup for a single-worker proxy with two gpt-5.4-nano deployments in one group under usage-based-routing-v2 and a provider budget, so the router's usage sync loop and the provider budget sync loop both run against Redis, at LITELLM_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 open

model_list:
  - model_name: nano-group
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY
  - model_name: nano-group
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: 127.0.0.1
    port: ${REDIS_PORT}

router_settings:
  redis_host: 127.0.0.1
  redis_port: ${REDIS_PORT}
  routing_strategy: usage-based-routing-v2
  num_retries: 0
  provider_budget_config:
    openai:
      budget_limit: 100
      time_period: 1d

general_settings:
  master_key: sk-qa-breaker-1234
  database_url: os.environ/DATABASE_URL
redis-server --port $REDIS_PORT --save "" --appendonly no &
LITELLM_LOG=WARNING litellm --config config_routing.yaml --port $PORT > proxy_routing.log 2>&1 &

burst() { for i in $(seq 1 20); do curl -s -o /dev/null -w "%{http_code}\n" -m 60 http://127.0.0.1:$PORT/v1/chat/completions \
  -H "Authorization: Bearer sk-qa-breaker-1234" -H "Content-Type: application/json" \
  -d "{\"model\":\"nano-group\",\"max_tokens\":8,\"messages\":[{\"role\":\"user\",\"content\":\"request $i: reply with one word\"}]}"; done | sort | uniq -c; }
stats() { echo "lines=$(wc -l < proxy_routing.log) sync_errors=$(grep -c 'Error syncing in-memory cache with Redis' proxy_routing.log) unretrieved=$(grep -c 'Task exception was never retrieved' proxy_routing.log) tracebacks=$(grep -c '^Traceback' proxy_routing.log)"; }

burst            # Redis up
kill %1          # redis-server
burst            # right after Redis died
sleep 30; burst  # breaker open
sleep 5; stats
grep -h ERROR proxy_routing.log | sed 's/^[0-9:]* - //' | sort | uniq -c | sort -rn | head -6
Before (8a4fae0)
  1. burst with Redis up: 20 200
  2. kill %1 then burst right after Redis died: 20 200, the breaker has not opened yet
  3. burst 30 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 pick
  4. stats: lines=254 sync_errors=39 unretrieved=2 tracebacks=3
  5. Top ERROR lines:
  36 LiteLLM Router:ERROR: budget_limiter.py:604 - Error syncing in-memory cache with Redis: Redis circuit breaker is open — skipping async_batch_get_cache
  20 LiteLLM Proxy:ERROR: common_request_processing.py:1456 - litellm.proxy.proxy_server._handle_llm_api_exception(): Exception occured - litellm.RateLimitError: No deployments available for selected model. Passed model=nano-group. Deployments={'58f9ddc03fca2f0990818b602aa27870ae2a9c765ef125b62d175df2d5da72c4': {'current_tpm': 0, 'tpm_limit': inf, 'current_rpm': 0, 'rpm_limit': inf}}. Received Model Group=nano-group
   3 LiteLLM:ERROR: redis_cache.py:1781 - LiteLLM Redis Caching: async increment_pipeline() - Got exception from REDIS Error 61 connecting to 127.0.0.1:26395. Connection refused.
   3 LiteLLM Router:ERROR: base_routing_strategy.py:150 - Error syncing in-memory cache with Redis: Redis circuit breaker is open — skipping async_increment_pipeline
   2 LiteLLM:ERROR: redis_cache.py:1556 - Error occurred in async batch get cache - Error 61 connecting to 127.0.0.1:26395. Connection refused.
   2 LiteLLM:ERROR: redis_cache.py:1271 - LiteLLM Redis Caching: async async_increment() - Got exception from REDIS Error 61 connecting to 127.0.0.1:26395. Connection refused., Writing value=19
After (2fc5203)
  1. burst with Redis up: 20 200
  2. kill %1 then burst right after Redis died: 20 200
  3. burst 30 s later with the breaker open: 20 200, routed from the in-memory usage counters
  4. stats: 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 task
  5. Top ERROR lines:
   4 LiteLLM:ERROR: redis_cache.py:1802 - LiteLLM Redis Caching: async increment_pipeline() - Got exception from REDIS Error 61 connecting to 127.0.0.1:56998. Connection refused.
   2 LiteLLM:ERROR: redis_cache.py:1577 - Error occurred in async batch get cache - Error 61 connecting to 127.0.0.1:56998. Connection refused.
   2 LiteLLM Router:ERROR: redis_cache.py:413 - Error syncing in-memory cache with Redis: Error 61 connecting to 127.0.0.1:56998. Connection refused.
   1 LiteLLM:ERROR: redis_cache.py:1291 - LiteLLM Redis Caching: async async_increment() - Got exception from REDIS Error 61 connecting to 127.0.0.1:56998. Connection refused., Writing value=19

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Spend counter increments are dropped while the breaker is open
    • Per-key and per-team budget checks run on the in-memory copy until Redis returns
    • The old code dropped them too, it just also logged an error per request

Low

  • A failure recorded while the breaker is OPEN still refreshes its recovery timer
    • A call admitted before the trip that fails late pushes the probe back by up to one recovery timeout
  • Pool exhaustion still counts as a hard connectivity failure (LIT-7542)
    • The 5 s timeout gate does not apply to it, so a dry pool can open the breaker on its own
  • The CLI login lookup answers 400 not found or expired while the breaker is open
    • Only for the seconds the breaker refuses Redis; the login works again once it closes

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

Link to Devin session: https://app.devin.ai/sessions/104607cf41f042a785c583a2eee31505
Open in Devin Desktop: https://app.devin.ai/desktop/session/104607cf41f042a785c583a2eee31505?variant=devin

mateo-berri and others added 3 commits September 10, 2026 20:58
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-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_redis_breaker_open_silent_miss (25ed0ab) with litellm_internal_staging (7419a53)

Open in CodSpeed

@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.75000% with 1 line in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

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

  • Binds Redis-call success to the breaker generation that admitted the call.
  • Preserves in-memory batch results and releases reservations when Redis is refused.
  • Treats expected open-breaker failures quietly in spend, routing, lock, health-state, and CLI paths.
  • Adds focused regression coverage for breaker transitions and outage fallback behavior.
  • Finalizes response metadata before asynchronous success handlers consume it.
  • Propagates database-pool settings to eligible collector sidecars while retaining direct token-authenticated connections.

Confidence Score: 5/5

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

Important Files Changed

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

Comment thread litellm/caching/redis_cache.py Resolved
Comment thread litellm/caching/redis_cache.py Resolved
mateo-berri and others added 3 commits September 10, 2026 21:35
…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/caching/redis_cache.py Resolved
…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

…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
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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.
@mateo-berri mateo-berri reopened this Sep 11, 2026
Comment thread litellm/caching/redis_cache.py Resolved
@mateo-berri mateo-berri changed the title fix(caching): make an open Redis circuit breaker a quiet cache miss instead of a traceback storm fix(caching): keep an open Redis circuit breaker open and quiet on the sync read and spend counter paths Sep 11, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/caching/redis_cache.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@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.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment on lines +547 to +550
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))

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 Detached Writes Can Be Lost

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.

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.

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

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.

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.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@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 25ed0ab. Configure here.

@mateo-berri mateo-berri 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.

LGTM

@mateo-berri
mateo-berri merged commit ff4b558 into litellm_internal_staging Sep 11, 2026
91 checks passed
@mateo-berri
mateo-berri deleted the litellm_redis_breaker_open_silent_miss branch September 11, 2026 02:55
sathvik-vyapar pushed a commit to shubhamvyapar/litellm that referenced this pull request Sep 16, 2026
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.

1 participant