All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
0.3.0 - 2026-01-02
- Metrics System: Comprehensive, production-ready metrics collection with <1% overhead
InMemoryMetrics: Built-in thread-safe collector with zero external dependencies, perfect for REST API endpointsOpenTelemetryMetrics: Native OpenTelemetry exporter with histogram support for industry-standard observabilityGCPCloudMonitoringMetrics: Google Cloud Monitoring exporter with batched writes, automatic resource detection, and shared APScheduler integrationInstrumentedStorage: Wrapper for automatic storage-level metrics tracking- Tracks hits, misses, sets, deletes, hit rates, latency percentiles (p50/p95/p99), errors, memory usage, and background refresh operations
- Shared collector pattern: Single
MetricsCollectorinstance can track multiple cached functions with per-function breakdown NullMetrics/NULL_METRICSfor zero-overhead disabled metricsMetricsCollectorprotocol for custom implementations
- GCP Client Sharing:
GCPCloudMonitoringMetricsnow accepts optionalclientparameter for connection pooling across multiple collectors - Shared Scheduler Integration: GCP exporter uses
SharedSchedulerinstead of dedicated threads for background metric flushing - Documentation:
docs/metrics.md: Comprehensive metrics guide (streamlined to 149 lines)docs/custom-metrics-exporters.md: Production-ready examples for Prometheus, StatsD, and Datadogexamples/metrics_example.py: Complete metrics usage patternsexamples/shared_metrics_example.py: Shared collector pattern demonstrationexamples/gcp_client_sharing_example.py: GCP client reuse example
- Testing: 17 comprehensive integration tests covering all decorators (TTL, SWR, BG), async/sync modes, thread safety, and performance overhead validation
- All decorators (
TTLCache,SWRCache,BGCache) now accept optionalmetricsparameter InMemCachenow supportsrecord_memory_usage()for tracking cache size- README updated with metrics quick start and API reference
- Metrics system benchmarked at <1% overhead for
InMemoryMetrics - <4% overhead for OpenTelemetry exporter
- <3% overhead for GCP Cloud Monitoring with batched writes
0.2.2-beta - 2025-12-25
- LocalFileCache: filesystem-backed storage with TTL, atomic writes, optional compression, and dedupe to skip identical rewrites.
- ChainCache: composable multi-level cache (e.g., InMem -> Redis -> S3/GCS/local file) with read-through promotion and write-through semantics.
- Dedupe writes: opt-in for RedisCache, S3Cache, GCSCache, and LocalFileCache to avoid rewriting unchanged payloads.
- Docs: production-grade BGCache writer/reader guide (
docs/bgcache.md) now shows Single-Writer/Multi-Reader with ChainCache cold tiers (S3/GCS/LocalFileCache) and per-process readers. - README updates for ChainCache, dedupe_writes, LocalFileCache.
- Tests: integration coverage for LocalFileCache (TTL expiry, dedupe, decorator usage, ChainCache integration).
- Refactor: storage backends split into
advanced_caching.storagepackage (per-backend modules) while preserving public exports.
- Redis dedupe now extends TTL when skipping identical writes.
- SharedAsyncScheduler uses current event loop when available (stability for async BGCache).
0.2.1 - 2025-12-25
- Key Generation Bug: Fixed an issue where
TTLCacheandSWRCachewould fail to correctly generate cache keys when using named placeholders (e.g.,"user:{id}") if the function was called with positional arguments. - Performance: Optimized cache key generation logic to avoid expensive signature binding on every call, using a fast-path for common patterns and efficient argument merging for complex cases.
configure()class method on all decorators to easily create pre-configured cache instances (e.g.,MyCache = TTLCache.configure(cache=RedisCache(...))).- Object Storage Backends: Added
S3Cache(AWS) andGCSCache(Google Cloud) for cost-effective storage of large objects.- Features: Metadata-based TTL checks (saves download costs), Gzip compression, and pluggable serializers.
0.2.0 - 2025-12-23
- Major Architecture Overhaul: The library is now fully async-native.
TTLCache,SWRCache, andBGCachenow supportasync deffunctions natively usingawait.- Synchronous functions are still supported via intelligent inspection, maintaining backward compatibility.
- Unified Scheduling:
SWRCache(in sync mode) andBGCachenow useAPScheduler(SharedSchedulerandSharedAsyncScheduler) for all background tasks, replacing ad-hoc threading. - Testing: Integration tests rewritten to use
pytest-asynciowithmode="auto".
AsyncTTLCache,AsyncStaleWhileRevalidateCache,AsyncBackgroundCacheclasses (aliased toTTLCache,SWRCache,BGCache).configure()class method on all decorators to easily create pre-configured cache instances (e.g.,MyCache = TTLCache.configure(cache=RedisCache(...))).SharedAsyncSchedulerfor managing async background jobs.pytest-asyncioconfiguration inpyproject.toml.
0.1.6 - 2025-12-15
JsonSerializernow usesorjsonfor significantly faster JSON serialization/deserialization (~2-3x faster)BGCache.register_loaderwithrun_immediately=Truenow checks if data exists in cache before executing the loader function, avoiding unnecessary function execution when data is already present in Redis/L2 cache.
- Comprehensive cache rehydration tests for all decorators (TTLCache, SWRCache, BGCache) verifying that existing Redis data is retrieved without re-executing functions.
- 7 new integration tests in
TestCacheRehydrationclass covering cache hit and cache miss scenarios for all decorators.
- Reduced unnecessary loader executions in BGCache when Redis already contains fresh data.
- Improved JSON serialization performance with orjson integration.
0.1.5 - 2025-12-15
- RedisCache now supports pluggable serializers with built-ins for
pickle(default) andjson, plus customdumps/loadsimplementations. HybridCache.from_redishelper for a one-liner L1 (in-memory) + L2 (Redis) setup.HybridCachenow supportsl2_ttlparameter for independent L2 TTL control. Defaults tol1_ttl * 2if not specified.__version__attribute exposed in the main module for version checking.- Comprehensive test coverage for BGCache lambda cache factory pattern and HybridCache l2_ttl behavior.
- Documentation example for using lambda cache factories with BGCache (lazy Redis connection initialization).
0.1.4 - 2025-12-12
- Performance improvements in hot paths:
- Reduced repeated cache initialization/lookups inside decorators.
- Reduced repeated
time.time()calls by reusing a single timestamp per operation. CacheEntryis now a slotted dataclass to reduce per-entry memory/attribute overhead.
- SWR background refresh now uses a shared thread pool (avoids spawning a new thread per refresh).
- Benchmarking & profiling tooling updates:
- Benchmarks can be configured via environment variables (e.g.
BENCH_WORK_MS,BENCH_RUNS). - Helper to compare JSON benchmark runs in
benchmarks.log. - Tight-loop profiler workload for decorator overhead.
- Benchmarks can be configured via environment variables (e.g.
- README updated to reflect current APIs, uv usage, and storage/Redis examples.
- Added step-by-step benchmarking/profiling guide in
docs/benchmarking-and-profiling.md.
0.1.3 - 2025-12-10
- Defined clear semantics for
ttlandinterval_secondswhen set to zero:TTLCache.cached(..., ttl <= 0)now acts as a transparent decorator (no caching); the wrapped function is always executed.SWRCache.cached(..., ttl <= 0)disables SWR and caching entirely; calls go straight to the wrapped function.BGCache.register_loader(..., interval_seconds <= 0 or ttl <= 0)disables background scheduling and caching; the loader is called directly on every invocation.
- Simplified logging strategy to eliminate overhead on hot paths while preserving useful diagnostics:
- Removed all debug/info logging from cache hit/miss and normal code paths.
- Retained and refined error logging only for exceptional situations.
- Error-only logging with structured messages:
SWRCachelogs usinglogger.exceptionwhen a background refresh job fails, including the cache key and full traceback.BGCacherefresh jobs:- Invoke the user-provided
on_errorhandler first when loader failures occur. - Log handler failures with
"BGCache error handler failed for key %r"including the key and traceback. - Log uncaught loader errors with
"BGCache refresh job failed for key %r"when noon_erroris supplied.
- Invoke the user-provided
- New tests ensuring that:
ttl == 0for TTLCache and SWRCache disables caching (each call executes the function and increments a counter).interval_seconds == 0orttl == 0for BGCache disables background loading and caching (each call executes the loader and increments a counter).
0.1.2 - 2025-12-10
- Unified public decorator arguments to use consistent names:
TTLCache.cached(key, ttl, cache=None)SWRCache.cached(key, ttl, stale_ttl=0, cache=None, enable_lock=True)BGCache.register_loader(key, interval_seconds, ttl=None, run_immediately=True, on_error=None, cache=None)
- Documented and clarified key template behavior across decorators:
- Positional templates:
"user:{}"→ first positional argument - Named templates:
"user:{user_id}","i18n:{lang}"→ keyword arguments by name - Robust key lambdas for default arguments and complex keys.
- Positional templates:
- Updated README API reference to match current behavior and naming, with:
- New "Key templates & custom keys" section.
- Richer examples for TTLCache, SWRCache, and BGCache (sync + async).
- Clear explanation of how
key,ttl,stale_ttl, andinterval_secondsinteract.
- New edge-case tests for:
InMemCache(cleanup, lock property,set_if_not_existswith expired entries).HybridCache(constructor validation, basic get/set/exists/delete behavior).validate_cache_storage()failure path.- Decorator key-generation edge paths:
- Static keys without placeholders.
- No-arg functions with static keys.
- Templates with positional placeholders but only kwargs passed.
- Templates with missing named placeholders falling back to raw keys.
- Additional key-template tests for TTLCache and SWRCache:
- Positional vs named templates.
- Extra kwargs with named templates.
- Default-argument handling via
key=lambda *a, **k: ....
- Increased test coverage from ~70% to ~82%:
decorators.pycoverage improved to ~87%.storage.pycoverage improved to ~74%.
- Ensured all tests pass under the documented
pyproject.tomlconfiguration.
0.1.1 - 2025-12-10
- Initial release of advanced-caching
- TTLCache decorator for time-based caching with configurable key patterns
- SWRCache (StaleWhileRevalidateCache) decorator for serving stale data while refreshing in background
- BGCache (BackgroundCache) decorator for background scheduler-based periodic loading with APScheduler
- InMemCache storage backend: Thread-safe in-memory cache with TTL support
- RedisCache storage backend: Distributed Redis-backed cache for multi-machine setups
- HybridCache storage backend: Two-level L1 (memory) + L2 (Redis) cache
- CacheStorage protocol for type-safe custom backend implementations
- CacheEntry dataclass for accessing cache metadata (TTL, age, freshness)
- validate_cache_storage() utility function for verifying custom implementations
- Full async/sync support for all decorators
- Comprehensive test suite with 18 unit tests (100% passing)
- Four benchmark suites with real-world measurements showing 9,000-75,000x performance gains
- Complete documentation with API reference, examples, and custom storage implementation guide
- Example: FileCache implementation demonstrating custom storage backend
- Six detailed use case examples (Web APIs, databases, configuration, distributed caching, locks)
- PEP 621 compliant project metadata
- MIT License
- Development tools: pytest, pytest-cov, uv build system
- GitHub Actions workflows for automated testing and PyPI publishing
- Type-Safe: Full type hints and docstrings throughout
- Zero Framework Dependencies: Works with FastAPI, Flask, Django, or plain Python (only requires APScheduler)
- Thread-Safe: Reentrant locks and atomic operations
- Performance: 9,000-75,000x faster on cache hits vs no cache
- Flexible: Multiple storage backends, composable decorators, custom backend support
- Production-Ready: Comprehensive tests, benchmarks, and documentation