Caching#
Dogpile L2 caching integration for SQLAlchemy repositories with commit-aware invalidation and per-process singleflight protection.
Configuration & Region Management#
- class advanced_alchemy.cache.CacheConfig(
- backend='dogpile.cache.null',
- expiration_time=3600,
- arguments=<factory>,
- key_prefix='aa:',
- enabled=True,
- serializer=None,
- deserializer=None,
- region_factory=None,
Bases:
objectConfiguration for a dogpile.cache region.
This dataclass holds configuration options for setting up a cache region using dogpile.cache. It supports multiple backends (Redis, Memcached, file, memory) and provides sensible defaults for getting started quickly.
Example
Basic memory cache configuration:
config = CacheConfig( backend="dogpile.cache.memory", expiration_time=300, )
Redis cache configuration:
config = CacheConfig( backend="dogpile.cache.redis", expiration_time=3600, arguments={ "host": "localhost", "port": 6379, "db": 0, }, )
- backend: str = 'dogpile.cache.null'#
Cache backend identifier.
Common backends: -
dogpile.cache.null: No-op cache (default, for development) -dogpile.cache.memory: In-process memory cache -dogpile.cache.redis: Redis backend -dogpile.cache.memcached: Memcached backend -dogpile.cache.dbm: DBM file-based cache
- expiration_time: int = 3600#
Default TTL (time-to-live) in seconds for cached items.
Set to
-1for no expiration. Default is 3600 (1 hour).
- key_prefix: str = 'aa:'#
Prefix for all cache keys.
This helps avoid key collisions when sharing a cache backend with other applications. Default is
aa:(advanced-alchemy).
- enabled: bool = True#
Enable or disable caching globally.
When
False, all cache operations are bypassed and data is always fetched from the database. Useful for debugging or testing.
- class advanced_alchemy.cache.CacheManager(config)#
Bases:
objectManages dogpile.cache regions with model-aware invalidation.
This class provides a high-level interface for caching SQLAlchemy model instances using dogpile.cache. It handles serialization, cache key generation, and model-version-based invalidation for list queries.
All cache operations are available in both sync and async variants: - Sync methods end with
_sync(e.g.,get_sync,set_sync) - Async methods end with_async(e.g.,get_async,set_async)Async methods use
asyncio.to_thread()with capacity limiting to prevent blocking the event loop when using network-based backends like Redis or Memcached.Features: - Lazy initialization of cache regions - Model-aware cache key generation - Version-based invalidation for list queries - Graceful degradation when dogpile.cache is not installed - Support for custom serializers - Both sync and async operation support
Example
Sync usage:
from advanced_alchemy.cache import CacheConfig, CacheManager config = CacheConfig( backend="dogpile.cache.memory", expiration_time=300, ) manager = CacheManager(config) # Cache a value (sync) result = manager.get_or_create_sync( "users:1", lambda: fetch_user_from_db(1), )
Async usage:
# Cache a value (async) result = await manager.get_or_create_async( "users:1", lambda: fetch_user_from_db(1), )
- property region: SyncCacheRegionProtocol#
Get the cache region, creating it if necessary.
The region is lazily initialized on first access. If dogpile.cache is not installed or initialization fails, returns a NullRegion that provides the same interface but doesn’t actually cache anything.
- Returns:
The configured cache region or a NullRegion fallback.
- get_sync(key)#
Get a value from the cache (sync).
- Parameters:
key (str) – The cache key (without prefix).
- Returns:
The cached value or NO_VALUE if not found.
- Return type:
object
- set_sync(key, value)#
Set a value in the cache (sync).
- Parameters:
key (str) – The cache key (without prefix).
value (Any) – The value to cache.
- delete_sync(key)#
Delete a value from the cache (sync).
- Parameters:
key (str) – The cache key (without prefix).
- async get_async(key)#
Get a value from the cache (async).
- Parameters:
key (str) – The cache key (without prefix).
- Returns:
The cached value or NO_VALUE if not found.
- Return type:
object
- async set_async(key, value)#
Set a value in the cache (async).
- Parameters:
key (str) – The cache key (without prefix).
value (Any) – The value to cache.
- async delete_async(key)#
Delete a value from the cache (async).
- Parameters:
key (str) – The cache key (without prefix).
- async get_entity_async(
- model_name,
- entity_id,
- model_class,
- bind_group=None,
Get a cached entity by model name and ID (async).
- Parameters:
model_name (str) – The model/table name.
entity_id (Any) – The entity’s primary key value.
model_class (type[T]) – The SQLAlchemy model class for deserialization.
bind_group (str | None) – Optional routing group for multi-master configurations. When provided, entity caches are namespaced by bind_group to prevent data leaks between database shards/replicas.
- Returns:
The cached model instance or None if not found.
- Return type:
T | None
- async set_entity_async(
- model_name,
- entity_id,
- entity,
- bind_group=None,
Cache an entity (async).
- Parameters:
model_name (str) – The model/table name.
entity_id (Any) – The entity’s primary key value.
entity (Any) – The SQLAlchemy model instance to cache.
bind_group (str | None) – Optional routing group for multi-master configurations. When provided, entity caches are namespaced by bind_group to prevent data leaks between database shards/replicas.
- async invalidate_entity_async(
- model_name,
- entity_id,
- bind_group=None,
Invalidate the cache for a specific entity (async).
This should be called after an entity is created, updated, or deleted to ensure the cache doesn’t serve stale data.
- Parameters:
model_name (str) – The model/table name.
entity_id (Any) – The entity’s primary key value.
bind_group (str | None) – Optional routing group for multi-master configurations. When provided, only the cache entry for that bind_group is invalidated.
- async invalidate_all_async()#
Invalidate all cached values (async).
Warning
This invalidates the entire region, not just keys with the configured prefix. Use with caution in shared cache environments.
Serialization & Listeners#
- advanced_alchemy.cache.default_serializer(model)#
Serialize a SQLAlchemy model instance to JSON bytes.
This function extracts column values from a SQLAlchemy model and serializes them to JSON format. The serialized data includes metadata about the model class for validation during deserialization.
Note
Relationships are NOT serialized. Only column values are included. The deserialized object will be a detached instance without relationship data loaded.
- Parameters:
model (Any) – The SQLAlchemy model instance to serialize.
- Returns:
JSON-encoded bytes representation of the model.
- Return type:
bytes
Example
Serializing a model:
user = User(id=1, name="John", email="john@example.com") data = default_serializer(user) # b'{"__aa_model__": "User", "__aa_table__": "users", "id": 1, ...}'
- advanced_alchemy.cache.default_deserializer(data, model_class)#
Deserialize JSON bytes to a SQLAlchemy model instance.
Creates a new, detached instance of the model class populated with the serialized column values. The instance is NOT attached to any session and should be treated as a read-only snapshot.
Warning
The returned instance is detached and does not have relationships loaded. Accessing lazy-loaded relationships will raise DetachedInstanceError. Use
session.merge()if you need to work with relationships.- Parameters:
data (bytes) – JSON bytes to deserialize.
model_class (type[T]) – The SQLAlchemy model class to instantiate.
- Returns:
A new, detached instance of the model class.
- Raises:
ValueError – If the serialized data is for a different model class.
- Return type:
T
Example
Deserializing data:
data = b'{"__aa_model__": "User", "id": 1, "name": "John"}' user = default_deserializer(data, User) # user is a detached User instance
- advanced_alchemy.cache.setup_cache_listeners()#
Register cache invalidation event listeners globally.
This registers the unified listener on Session, which handles both sync and async contexts by detecting a running event loop at commit time. For more control, prefer using scoped listeners via SQLAlchemyConfig.
- advanced_alchemy.cache.DOGPILE_CACHE_INSTALLED: bool#
Boolean flag indicating whether
dogpile.cacheis installed.