Cache Module
The Cache module implements a four-layer caching architecture that automatically routes reads and writes through in-process, local, distributed, and persistent cache tiers. It provides decorators for zero-code caching and event-driven invalidation.
Four-Layer Architecture
| Layer | Backend | Speed | Scope |
|---|---|---|---|
L1 | In-process (LRU dict) | Nanoseconds | Single process |
L2 | Local Redis / Memcached | Sub-millisecond | Single machine |
L3 | Distributed Redis cluster | 1-5 ms | Multiple machines |
L4 | Persistent (CDN, S3, file) | 10-100 ms | Global |
Configuration
example.py
python
Copied!
Basic Usage
example.py
python
Copied!
@cached Decorator
Cache the return value of any async function. The decorator generates a cache key from the function name and arguments.
get_user.py
python
Copied!
Cache Tags
Group cached entries by tags for bulk invalidation. This is useful when a single data change should invalidate multiple related cache entries.
example.py
python
Copied!
Invalidation Strategies
Time-Based (TTL)
example.py
python
Copied!
Event-Driven Invalidation
invalidate_user_cache.py
python
Copied!
Write-Through
update_user.py
python
Copied!
Cache-Aside (Lazy Loading)
get_user.py
python
Copied!
Cache Statistics
example.py
python
Copied!