CacheService — Aquilia Documentation
Comprehensive guide and documentation for CacheService in the Aquilia framework. View API reference, examples, and implementation patterns.
Cache / CacheService CacheService CacheService is the primary app-facing API. It wraps a CacheBackend with namespacing, key prefixing, TTL jitter, stampede prevention, and structured fault emission. Constructor and Properties from aquilia.cache import CacheService, CacheConfig service = CacheService( backend=my_backend, config=CacheConfig(default_ttl=300, namespace="default"), ) # Properties service.backend # Returns the CacheBackend service.config # Returns the CacheConfig service.is_distributed # bool (delegates to backend) service.is_healthy # bool (checks initialized + health state) Method Reference Signature Behavior ))} Cache-Aside and Stampede Prevention The get_or_set(...) pattern supports thundering-herd stampede prevention using a process-local in-memory singleflight futures map. While a key is being fetched, concurrent duplicate reads wait on the primary loader: from aquilia.cache import CacheService class UserService: def __init__(self, cache: CacheService, repo): self.cache = cache self.repo = repo async def get_user(self, user_id: str): return await self.cache.get_or_set( key=f"user: ", loader=lambda: self.repo.find_user(user_id), ttl=300, namespace="users", tags=("users", f"user: "), ) Batch and Invalidation Operations from aquilia.cache import CacheService async def refresh_catalog(cache: CacheService, catalog_items: dict[str, dict]): await cache.set_many( items= ": v for k, v in catalog_items.items()}, ttl=120, namespace="catalog", ) values = await cache.get_many(["product:1", "product:2"], namespace="catalog") # Invalidate by tags (group invalidation) await cache.invalidate_tags("products") # Invalidate whole namespace await cache.invalidate_namespace("catalog") return values Observability and Health stats = await cache.stats() print(stats.to_dict()) ok = await cache.health_check() print("cache healthy:", ok) Behavior Notes • get(...) and get_many(...) degrade gracefully, returning default values on connection errors rather than raising exceptions. • set(...) and set_many(...) log errors and emit a structured cache fault, but do not raise, ensuring data persistence errors do not block the request. • Stampede prevention is local to the current python worker process. Coalescence does not occur across separate host nodes or parallel server processes. DI Example Inject CacheService directly into controllers through dependency injection: from aquilia import Controller, GET from aquilia.cache import CacheService class ProductController(Controller): prefix = "/products" def __init__(self, cache: CacheService): self.cache = cache @GET("/ ") async def get_product(self, ctx, id: int): product = await self.cache.get_or_set( f"product: ", lambda: self.repo.find(id), ttl=300, namespace="catalog", ) return product )
Go to Homepage