caching-patternslisted
Install: claude install-skill dbtinoy-/lexigram-framework-skills
# Caching Patterns
## Overview
Multi-backend caching behind `CacheBackendProtocol` (Result-based: get/set/delete) plus `CacheService` (ergonomic facade with stampede protection). Swap memory, Redis, or Memcached via config without changing service code.
## Basic Usage
```python
from lexigram.contracts.infra.cache import CacheBackendProtocol
class ProductService:
def __init__(self, cache: CacheBackendProtocol):
self.cache = cache
async def get_price(self, product_id: str) -> Result[float, DomainError]:
cached = await self.cache.get(f"price:{product_id}")
if cached.is_ok():
return Ok(float(cached.unwrap()))
price = await self._compute_price(product_id)
await self.cache.set(f"price:{product_id}", str(price), ttl=300)
return Ok(price)
```
Protocol methods: `get`, `set(key, value, ttl=None)`, `delete`, `delete_many`, `delete_pattern`, `exists`, `get_many`, `set_many`, `clear`.
## Stampede Protection (CacheService)
```python
from lexigram.cache import CacheService
class PriceService:
def __init__(self, cache: CacheService):
self.cache = cache
async def get_price(self, product_id: str) -> float:
return await self.cache.get_or_compute(
key=f"price:{product_id}",
factory=lambda: self._compute_price(product_id),
ttl=300,
)
```
`get_or_compute(key, factory, ttl, backend)` deduplicates concurrent misses — one caller recomputes, others wait.