Skip to content

feat(caching): give RedisCache a pub/sub and lease surface and drop raw client reaches - #42984

Closed
devin-ai-integration[bot] wants to merge 2 commits into
mainfrom
litellm_redis_cache_pubsub_lease
Closed

devin-ai-integration[bot] wants to merge 2 commits into
mainfrom
litellm_redis_cache_pubsub_lease

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • proxy helpers reached into the raw redis client for pub/sub and locks
  • RedisCache had no shared subscribe, publish, or lease surface
  • the Rust cache backend had no pub/sub capability

How it solves it:

  • RedisCache grows async_publish, async_subscribe, RedisSubscription, connection_pool_status
  • config sync, auth invalidation, the credential refresh lock, and debug stats go through it
  • litellm-rust gains a PubSubCache capability and a Redis implementation

User Flow

Before: a proxy operator running several workers against one Redis gets cross-worker coordination, but each feature wires the redis client differently

  1. They start the proxy with a Redis cache and multiple workers
  2. Config sync, auth cache invalidation, and credential refresh locking each open their own path into the raw redis client
  3. A Redis Cluster client silently disables some of those paths, and debug endpoints reach the client directly for pool stats

After: the same deployment gets the same coordination through one RedisCache surface, with a matching Rust backend

  1. They start the proxy with a Redis cache and multiple workers
  2. Config sync, auth cache invalidation, and the credential refresh lease all run through RedisCache pub/sub and script calls
  3. Cluster clients keep degrading the same way, and debug stats read the pool through the cache

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)

Type

🆕 New Feature
🧹 Refactoring

Screenshots / Proof of Fix

Caveats (if any)

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

…aw client reaches

Add async_publish and async_subscribe to the Python RedisCache, returning a
RedisSubscription that yields RedisMessage values and skips redis-py's
subscribe acks, plus connection_pool_status for the debug endpoint. Cluster
clients raise NotImplementedError, matching the existing skip behaviour.

Move the config sync and auth cache invalidation modules onto that surface
and rewrite the MCP refresh lock onto async_register_script, so no proxy code
reaches into init_async_client or redis_client any more. This defines the
surface a native RedisCache has to match.

On the Rust side add the PubSubCache and MessageStream capability traits and
implement them in cache-redis with a dedicated subscription connection driven
by a reader thread, tested against an in-process RESP server over a real
socket.
@devin-ai-integration

devin-ai-integration Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_redis_cache_pubsub_lease (398d78b) with main (f0e671f)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

The PR is not ready to merge until subscription closure and timeout behavior are corrected and the tests satisfy the repository's mock-only requirement.

Findings

  1. P1 Full queue blocks closure ▶
  2. P1 Indefinite wait ends early ▶
  3. P2 Tests make real network calls ▶
  4. P2 Failed subscribe retains connection ▶

Summary

The PR adds Python RedisCache publish, subscribe, and pool-status methods; moves proxy coordination and credential leases behind cache methods; and introduces a Rust pub/sub capability.

  • The Rust subscription can hang during close when its queue is full.
  • The Python subscription breaks its documented indefinite-wait contract and does not clean up a failed subscribe.
  • New socket-backed tests conflict with the repository's test-location requirement.

Reviews (1) · Last reviewed commit: "fix(caching): type the redis pool status..."

channel: received.get_channel_name().to_owned(),
payload: received.get_payload_bytes().to_vec(),
};
if sender.blocking_send(Ok(message)).is_err() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Full queue blocks closure If more than 1,024 messages arrive without being drained, blocking_send blocks the reader. close() then sets the stop flag and waits for that reader while keeping the receiver open. The reader cannot finish the send or check the flag, so close() never returns.

Comment on lines +630 to +633
deadline: Final = None if timeout is None else clock() + timeout
while True:
remaining = _PUBSUB_WAIT_SLICE_SECONDS if deadline is None else max(deadline - clock(), 0.0)
frame: object = await self.pubsub.get_message(timeout=remaining)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Indefinite wait ends early get_message(timeout=None) promises to wait indefinitely, but it polls Redis for one second and returns None if no message arrives. A caller requesting an indefinite wait therefore gets a timeout after an idle second instead of waiting for a message.

Comment on lines +1504 to +1506
server = fakeredis.TcpFakeServer(("127.0.0.1", 0), server_type="redis")
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()

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 Tests make real network calls This fixture starts a TCP Redis server for tests under tests/test_litellm/, where the repository requires mock-only tests and forbids real network calls. The new lock-test fixture also starts redis-server and connects over localhost TCP. This repository requirement must be satisfied before merging.

Rule Used: What: prevent any tests from being added here that make real network calls - only mock tests can be added to this folder. Exception: tests/e2e folder, this folder can contain network calls. Why: ensure it runs correctly on github ci/cd + for all d... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +1919 to +1922
async def async_subscribe(self, *channels: str) -> RedisSubscription:
pubsub: Final = self._standalone_async_client().pubsub()
await pubsub.subscribe(*channels)
return RedisSubscription(pubsub)

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 Failed subscribe retains connection If pubsub.subscribe() fails after taking a connection, this method raises without closing the PubSub. The caller never receives a subscription it can close, so repeated reconnect attempts can retain connections and put pressure on the shared pool.

@codecov

codecov Bot commented Sep 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.80000% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/caching/redis_cache.py 96.72% 2 Missing ⚠️
...ver/outbound_credentials/redis_distributed_lock.py 95.23% 1 Missing ⚠️
...utbound_credentials/runtime_refresh_coordinator.py 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

This branch had an error being deployed

1 failed deployment
e2e-changed — 398d78be Deployed Sep 24, 2026 by yujonglee-berri via oauth #842
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.

3 participants