The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Memory Leak Fix] Fix InMemoryCache unbounded growth when TTLs are set (#14869)
Copilot1816176f9d51
diff --git a/litellm/caching/in_memory_cache.py b/litellm/caching/in_memory_cache.pyindex 63869474d47..082cac791f2 100644--- a/litellm/caching/in_memory_cache.py+++ b/litellm/caching/in_memory_cache.py@@ -36,7 +36,7 @@ class InMemoryCache(BaseCache):max_size_in_memory [int]: Maximum number of items in cache. done to prevent memory leaks. Use 200 items as a default"""self.max_size_in_memory = (- max_size_in_memory or 200+ max_size_in_memory if max_size_in_memory is not None else 200) # set an upper bound of 200 items in-memoryself.default_ttl = default_ttl or 600self.max_size_per_item = (@@ -103,20 +103,32 @@ class InMemoryCache(BaseCache):def evict_cache(self):"""Eviction policy:- - check if any items in ttl_dict are expired -> remove them from ttl_dict and cache_dict+ 1. First, remove expired items from ttl_dict and cache_dict+ 2. If cache is still at or above max_size_in_memory, evict items with earliest expiration timesThis guarantees the following:- - 1. When item ttl not set: At minimumm each item will remain in memory for 5 minutes- - 2. When ttl is set: the item will remain in memory for at least that amount of time+ - 1. When item ttl not set: At minimum each item will remain in memory for the default ttl+ - 2. When ttl is set: the item will remain in memory for at least that amount of time, unless cache size requires eviction- 3. the size of in-memory cache is bounded"""current_time = time.time()++ # Step 1: Remove expired itemsexpired_keys = [key for key, ttl in self.ttl_dict.items() if current_time > ttl]for key in expired_keys:self._remove_key(key)+ # Step 2: If cache is still full, evict items with earliest expiration times+ if len(self.cache_dict) >= self.max_size_in_memory:+ # Sort by expiration time (earliest first) and evict until we're under the limit+ items_by_expiration = sorted(self.ttl_dict.items(), key=lambda x: x[1])+ keys_to_evict = items_by_expiration[:len(self.cache_dict) - self.max_size_in_memory + 1]++ for key, _ in keys_to_evict:+ self._remove_key(key)+# de-reference the removed item# https://www.geeksforgeeks.org/diagnosing-and-fixing-memory-leaks-in-python/# One of the most common causes of memory leaks in Python is the retention of objects that are no longer being used.@@ -135,6 +147,10 @@ class InMemoryCache(BaseCache):return Falsedef set_cache(self, key, value, **kwargs):+ # Handle the edge case where max_size_in_memory is 0+ if self.max_size_in_memory == 0:+ return # Don't cache anything if max size is 0+if len(self.cache_dict) >= self.max_size_in_memory:# only evict when cache is fullself.evict_cache()diff --git a/tests/test_litellm/caching/test_in_memory_cache.py b/tests/test_litellm/caching/test_in_memory_cache.pyindex 72f264b8b7d..616c60c74a0 100644--- a/tests/test_litellm/caching/test_in_memory_cache.py+++ b/tests/test_litellm/caching/test_in_memory_cache.py@@ -88,3 +88,101 @@ def test_in_memory_cache_ttl_allow_override():new_ttl_time = in_memory_cache.ttl_dict["new-fake-key"]assert new_ttl_time is not Noneassert new_ttl_time != initial_ttl_time+++def test_in_memory_cache_max_size_with_ttl():+ """+ Test that max_size_in_memory is respected even when all items have long TTLs.+ This tests the fix for the unbounded growth issue.+ """+ in_memory_cache = InMemoryCache(max_size_in_memory=3)+ long_ttl = 86400 # 1 day++ # Fill the cache to max capacity+ for i in range(3):+ in_memory_cache.set_cache(key=f"key_{i}", value=f"value_{i}", ttl=long_ttl)+ time.sleep(0.01) # Small delay to ensure different timestamps++ assert len(in_memory_cache.cache_dict) == 3+ assert len(in_memory_cache.ttl_dict) == 3++ # Add another item - should evict the earliest item+ in_memory_cache.set_cache(key="key_3", value="value_3", ttl=long_ttl)++ # Cache should still be at max size, not larger+ assert len(in_memory_cache.cache_dict) == 3+ assert len(in_memory_cache.ttl_dict) == 3++ # key_0 should have been evicted (it was added first)+ assert "key_0" not in in_memory_cache.cache_dict+ assert "key_0" not in in_memory_cache.ttl_dict++ # Other keys should still be present+ assert "key_1" in in_memory_cache.cache_dict+ assert "key_2" in in_memory_cache.cache_dict+ assert "key_3" in in_memory_cache.cache_dict+++def test_in_memory_cache_expired_items_evicted_first():+ """+ Test that expired items are evicted before non-expired items when cache is full.+ """+ in_memory_cache = InMemoryCache(max_size_in_memory=3)++ # Add items with short TTL that will expire+ in_memory_cache.set_cache(key="expired_1", value="value_1", ttl=1)+ in_memory_cache.set_cache(key="expired_2", value="value_2", ttl=1)++ # Add item with long TTL+ in_memory_cache.set_cache(key="long_lived", value="value_long", ttl=86400)++ assert len(in_memory_cache.cache_dict) == 3++ # Wait for short TTL items to expire+ time.sleep(2)++ # Add new item - should evict expired items first, not the long-lived one+ in_memory_cache.set_cache(key="new_item", value="new_value", ttl=86400)++ # Long-lived item should still be present+ assert "long_lived" in in_memory_cache.cache_dict+ assert "new_item" in in_memory_cache.cache_dict++ # Expired items should be gone+ assert "expired_1" not in in_memory_cache.cache_dict+ assert "expired_2" not in in_memory_cache.cache_dict+ assert "expired_1" not in in_memory_cache.ttl_dict+ assert "expired_2" not in in_memory_cache.ttl_dict+++def test_in_memory_cache_eviction_order():+ """+ Test that when non-expired items need to be evicted, those with earliest expiration times are evicted first.+ """+ in_memory_cache = InMemoryCache(max_size_in_memory=2)++ # Add items with different TTLs+ now = time.time()+ in_memory_cache.set_cache(key="early_expire", value="value_1", ttl=100) # expires in 100 seconds+ time.sleep(0.01)+ in_memory_cache.set_cache(key="late_expire", value="value_2", ttl=200) # expires in 200 seconds++ # Verify TTL order+ early_ttl = in_memory_cache.ttl_dict["early_expire"]+ late_ttl = in_memory_cache.ttl_dict["late_expire"]+ assert early_ttl < late_ttl, "early_expire should have earlier expiration time"++ assert len(in_memory_cache.cache_dict) == 2++ # Add third item - should evict the one with earliest expiration time+ in_memory_cache.set_cache(key="new_item", value="value_3", ttl=300)++ assert len(in_memory_cache.cache_dict) == 2++ # Item with earliest expiration should be evicted+ assert "early_expire" not in in_memory_cache.cache_dict+ assert "early_expire" not in in_memory_cache.ttl_dict++ # Items with later expiration should remain+ assert "late_expire" in in_memory_cache.cache_dict+ assert "new_item" in in_memory_cache.cache_dict