Simple in-memory cache with timeout and request coalescing Prevents cache stampede by using per-key locks to ensure only one request computes a value while others wait.
| 100 | |
| 101 | |
| 102 | class SimpleCache: |
| 103 | """Simple in-memory cache with timeout and request coalescing |
| 104 | |
| 105 | Prevents cache stampede by using per-key locks to ensure only one |
| 106 | request computes a value while others wait. |
| 107 | """ |
| 108 | |
| 109 | def __init__(self): |
| 110 | self._cache: dict[str, CacheEntry] = {} |
| 111 | self._cache_lock = threading.Lock() |
| 112 | self._compute_locks: dict[str, threading.Lock] = {} |
| 113 | self._compute_locks_lock = threading.Lock() |
| 114 | |
| 115 | def get(self, key: str, timeout_seconds: int | None = None) -> Any | None: |
| 116 | """Get cached value if it exists and hasn't expired""" |
| 117 | with self._cache_lock: |
| 118 | if key not in self._cache: |
| 119 | return None |
| 120 | |
| 121 | entry = self._cache[key] |
| 122 | |
| 123 | # Check if cache is still valid |
| 124 | if timeout_seconds is not None: |
| 125 | age = (datetime.now() - entry.timestamp).total_seconds() |
| 126 | if age > timeout_seconds: |
| 127 | del self._cache[key] |
| 128 | return None |
| 129 | |
| 130 | return entry.data |
| 131 | |
| 132 | def set(self, key: str, value: Any): |
| 133 | """Set cache value""" |
| 134 | with self._cache_lock: |
| 135 | self._cache[key] = CacheEntry(data=value, timestamp=datetime.now()) |
| 136 | |
| 137 | def invalidate(self, key: str): |
| 138 | """Invalidate a specific cache entry""" |
| 139 | with self._cache_lock: |
| 140 | if key in self._cache: |
| 141 | del self._cache[key] |
| 142 | |
| 143 | def clear(self): |
| 144 | """Clear all cache entries""" |
| 145 | with self._cache_lock: |
| 146 | self._cache.clear() |
| 147 | |
| 148 | def _get_compute_lock(self, key: str) -> threading.Lock: |
| 149 | """Get or create a lock for a specific cache key""" |
| 150 | with self._compute_locks_lock: |
| 151 | if key not in self._compute_locks: |
| 152 | self._compute_locks[key] = threading.Lock() |
| 153 | return self._compute_locks[key] |
| 154 | |
| 155 | def _cleanup_compute_lock(self, key: str): |
| 156 | """Clean up compute lock after use to avoid memory leak""" |
| 157 | with self._compute_locks_lock: |
| 158 | if key in self._compute_locks: |
| 159 | # Only delete if no one is using it (not locked) |