### Memcached Installation and Backend Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Command to install CacheKit with Memcached support and an example of setting up a MemcachedBackend. ```bash pip install cachekit[memcached] # Default: connects to 127.0.0.1:11211 ``` ```python from cachekit import cache from cachekit.backends.memcached import MemcachedBackend backend = MemcachedBackend() @cache(backend=backend, ttl=3600) def get_user(user_id: int): return fetch_from_db(user_id) ``` -------------------------------- ### Quick Install with Pip and Uv Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Commands to install the cachekit library using pip and uv. ```bash # With pip pip install cachekit # With uv (recommended - faster) uv add cachekit # Start Redis if you haven't docker run -p 6379:6379 redis ``` -------------------------------- ### Install or Reinstall CacheKit Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Commands to install or reinstall the CacheKit package using uv. ```bash # Make sure package is installed uv add cachekit # Or reinstall uv remove cachekit && uv add cachekit ``` -------------------------------- ### Python Configuration Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of configuring CacheKit using Python decorators. ```python from cachekit import cache @cache(ttl=3600, namespace="myapp") def cached_function(): return expensive_operation() ``` -------------------------------- ### Quick Start Installation and Validation Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Commands to install dependencies and run quick validation checks. ```bash make install # Install dependencies make quick-check # Run fast validation (< 2 min) make test # Run all tests ``` -------------------------------- ### CacheKit Basic Usage Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md A simple Python example demonstrating CacheKit usage and verifying it's working. ```python from cachekit import cache @cache(ttl=60) def test_function(): return "working" result = test_function() print(f"Cache working: {result}") ``` -------------------------------- ### Monitoring Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Python code demonstrating how to use CacheKit for monitoring by calling a cached function multiple times. ```python from cachekit import cache @cache(ttl=3600, namespace="monitoring_example") def monitored_function(): return expensive_operation() # Use the cached function multiple times to build statistics for i in range(3): result = monitored_function() print(f"Call {i+1}: {result}") ``` -------------------------------- ### Intent Presets Examples Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Examples of using different intent presets for cache configuration. ```python from cachekit import cache # Zero overhead - all features disabled @cache.minimal(backend=None) def minimal_function(): pass # Development - SWR enabled, invalidation disabled @cache.dev(backend=None) def dev_function(): pass # Production - all features enabled @cache.production(backend=None) def prod_function(): pass # Testing - deterministic behavior @cache.test(backend=None) def test_function(): pass # Secure - encryption + all features @cache.secure(master_key="a" * 64, backend=None) def secure_function(): pass # cachekit.io SaaS - production-grade via managed API (closed alpha) # Requires: CACHEKIT_API_KEY env var # @cache.io(ttl=300) # def io_function(): # pass ``` -------------------------------- ### Redis URL Configuration Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Example showing how CACHEKIT_REDIS_URL takes precedence over REDIS_URL. ```bash export CACHEKIT_REDIS_URL=redis://prod.example.com:6379/0 export REDIS_URL=redis://localhost:6379/0 # Ignored - won't be used ``` -------------------------------- ### Example Usage with @cache.io Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Demonstrates enabling production-grade features with the @cache.io decorator. ```python @cache.io(ttl=300) def fetch_data(user_id: int): return expensive_api_call(user_id) ``` -------------------------------- ### CachekitIO Cloud API Key Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Environment variable for setting the API key for CachekitIO Cloud. ```bash # CachekitIO Cloud (invite-only alpha) export CACHEKIT_API_KEY=ck_your_api_key ``` -------------------------------- ### Start Redis (Linux) Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Command to start Redis service on Linux. ```bash # Start Redis (Linux) sudo systemctl start redis ``` -------------------------------- ### Quick Start with Redis - Basic Cache Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md This snippet demonstrates a basic cache decorator usage with an expensive function. ```python from cachekit import cache @cache # Uses Redis by default def expensive_function(): return do_work() ``` -------------------------------- ### Environment Setup for Redis Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Environment variables for configuring Redis connection URL and connection pool size for CacheKit. ```bash # Redis (recommended default) export REDIS_URL="redis://localhost:6379" # Optional: explicit Redis configuration export CACHEKIT_REDIS_URL="redis://localhost:6379" export CACHEKIT_CONNECTION_POOL_SIZE=20 # CachekitIO Cloud (invite-only alpha) export CACHEKIT_API_KEY=ck_your_api_key ``` -------------------------------- ### Redis Configuration Environment Variables Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example .env file for configuring Redis connection and cache settings. ```bash # Redis Configuration CACHEKIT_REDIS_URL=redis://localhost:6379/0 CACHEKIT_CONNECTION_POOL_SIZE=20 CACHEKIT_SOCKET_TIMEOUT=1.0 CACHEKIT_SOCKET_CONNECT_TIMEOUT=1.0 # Cache Configuration CACHEKIT_DEFAULT_TTL=3600 CACHEKIT_MAX_CHUNK_SIZE_MB=50 CACHEKIT_ENABLE_COMPRESSION=true CACHEKIT_COMPRESSION_LEVEL=6 # Logging LOG_LEVEL=INFO CACHE_METRICS_ENABLED=true ``` -------------------------------- ### Quick Start with Redis - Running Redis Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md This snippet shows how to run Redis using Docker and set the REDIS_URL environment variable. ```bash # 1. Run Redis docker run -p 6379:6379 redis # 2. Set Redis URL export REDIS_URL="redis://localhost:6379" ``` -------------------------------- ### Start Redis (macOS) Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Command to start Redis service on macOS. ```bash # Start Redis (macOS) brew services start redis ``` -------------------------------- ### Absolute Imports Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Demonstrates correct and incorrect usage of absolute imports. ```diff + from cachekit.decorators.main import redis_cache # Good + from cachekit.serializers import StandardSerializer - from .main import redis_cache # Bad (will fail) ``` -------------------------------- ### Troubleshooting: Valid and Invalid CACHEKIT_MASTER_KEY Formats Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Examples of valid and invalid formats for the CACHEKIT_MASTER_KEY. ```bash # Valid key formats: # - 64 character hex string (32 bytes) # - Minimum requirement: 32 bytes (64 hex characters) # Invalid key formats: # WRONG - not hex export CACHEKIT_MASTER_KEY="my-secret-key" # WRONG - too short export CACHEKIT_MASTER_KEY="abcd1234" # CORRECT - 64 hex characters = 32 bytes export CACHEKIT_MASTER_KEY="a1b2c3d4e5f6789012345678901234567890abcdef12345678901234567890" ``` -------------------------------- ### L1 Cache Configuration Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Python code demonstrating how to configure L1 cache behavior with SWR and invalidation. ```python from cachekit import cache from cachekit.config import L1CacheConfig # Enable SWR (stale-while-revalidate) with custom threshold @cache( l1=L1CacheConfig( # Correct parameter name is 'l1', not 'l1_config' enabled=True, max_size_mb=100, swr_enabled=True, swr_threshold_ratio=0.5, # Refresh at 50% of TTL invalidation_enabled=True, namespace_index=True, ), backend=None ) def my_function(): return expensive_computation() # illustrative - not defined ``` -------------------------------- ### Intent-Based Presets for Common Configurations Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Demonstrates using predefined presets for common caching configurations like production, secure, and minimal. ```python @cache.production # All reliability features enabled @cache.secure # Encryption + reliability @cache.minimal # Maximum speed, minimal overhead ``` -------------------------------- ### CacheKit Resilience Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Demonstrates how CacheKit continues to function even when the Redis backend is unavailable, executing the function normally without caching. ```python @cache def critical_function(): return important_data() # Redis is down? No problem! # Function executes normally, just without caching result = critical_function() # Works even if Redis is offline ``` -------------------------------- ### Prerequisites: SDK installed Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README_SDK_E2E.md Commands to navigate to the cachekit directory and install the library. ```bash cd cachekit make install # Install cachekit library ``` -------------------------------- ### Troubleshooting: Correct Environment Variable Prefix Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Example showing the correct and incorrect prefixes for Cachekit environment variables. ```bash # WRONG - won't be read: export CACHE_REDIS_URL=redis://localhost:6379 # CORRECT - will be read: export CACHEKIT_REDIS_URL=redis://localhost:6379 ``` -------------------------------- ### Quick Start Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/features/circuit-breaker.md Demonstrates basic usage of the circuit breaker, showing normal behavior and how it handles backend failures by returning stale cache or None. ```python from cachekit import cache @cache(ttl=300, backend=None) # Circuit breaker active def expensive_operation(x): return do_expensive_computation() # Redis working: Normal cache behavior result = expensive_operation(1) # L1 hit or L2 hit or compute # Backend down: Circuit breaker catches error # Behavior: Returns stale cache or None, app continues result = expensive_operation(1) # Returns stale/None instead of error ``` -------------------------------- ### Run Redis in Docker Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Docker command to run a Redis instance. ```bash # Or run Redis in Docker docker run -d -p 6379:6379 redis:latest ``` -------------------------------- ### Quick Start: Against Local Worker Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/E2E_TESTING_RESULTS.md Environment setup and pytest commands to run E2E tests against a local CacheKit worker. ```bash cd saas/tests/validation # Set environment export CACHEKITIO_API_URL="http://localhost:8787" export CACHEKITIO_API_TOKEN="ck_sdk_your_key_here" # Run all E2E tests pytest test_sdk_*.py -v # Run specific phase pytest test_sdk_e2e.py -v # Phase 1: Core pytest test_sdk_data_handling.py -v # Phase 2: Data pytest test_sdk_error_handling.py -v # Phase 3: Errors pytest test_sdk_performance.py -v # Phase 4: Performance ``` -------------------------------- ### Using @cache.io() Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Example of setting the API key environment variable and using the @cache.io() decorator. ```python import os from cachekit import cache os.environ["CACHEKIT_API_KEY"] = "ck_live_your_key_here" ``` -------------------------------- ### Troubleshooting: Redis Connection Error - Verify Connection String Format Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Examples of correct and incorrect Redis URL formats. ```bash # Verify connection string format export CACHEKIT_REDIS_URL=redis://localhost:6379/0 # NOT: redis:localhost:6379 (wrong) # NOT: redis/localhost:6379 (wrong) ``` -------------------------------- ### Redis Configuration Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/CONTRIBUTING.md An example of configuring CacheKit to use an external Redis instance for caching in a production setup. ```python from cachekit import cache import redis # Your production setup redis_client = redis.Redis(host='prod-redis', port=6379) @cache(backend=redis_client) def production_function(): return fetch_from_production() ``` -------------------------------- ### Direct Cache Access Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/performance.md Demonstrates using the StandardCacheHandler API directly to bypass decorator overhead for ultra-low-latency scenarios. ```python from cachekit.cache_handler import StandardCacheHandler handler = StandardCacheHandler(backend=redis_backend) # Direct cache access (no decorator overhead) found, value = handler.get("my_key") if not found: value = expensive_function() handler.put("my_key", value, ttl=3600) ``` -------------------------------- ### Memcached backend setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/README.md Example of using cachekit with the Memcached backend. ```python from cachekit import cache from cachekit.backends.memcached import MemcachedBackend # pip install cachekit[memcached] backend = MemcachedBackend() # Defaults to 127.0.0.1:11211 @cache(backend=backend) def expensive_api_call(user_id: int): return fetch_user_data(user_id) ``` -------------------------------- ### Secure Production: Encryption Enabled Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Environment variables for a secure production setup with encryption enabled. ```bash export CACHEKIT_REDIS_URL=redis://redis-primary:6379/0 export CACHEKIT_MASTER_KEY=$(openssl rand -hex 32) export CACHEKIT_ENABLE_COMPRESSION=true export LOG_LEVEL=WARNING ``` -------------------------------- ### With Encryption Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/comparison.md Environment variable setup for enabling encryption with cachekit. ```bash export CACHEKIT_MASTER_KEY="your_hex_encoded_key" ``` -------------------------------- ### Redis Backend Usage Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Example of using the Redis backend with the @cache decorator. ```python from cachekit import cache @cache # Uses Redis backend by default def fetch_data(): return expensive_computation() ``` -------------------------------- ### Redis Connection Pooling Configuration Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Python code demonstrating how to configure Redis connection pooling with CacheKit. ```python import redis.connection redis_client = redis.Redis( connection_pool=redis.ConnectionPool( host='redis.company.com', port=6379, db=0, max_connections=50, socket_keepalive=True, health_check_interval=30 ) ) ``` -------------------------------- ### Installation with uv Source: https://github.com/cachekit-io/cachekit-py/blob/main/README.md Install cachekit using uv (recommended). ```bash uv add cachekit ``` -------------------------------- ### SDK Installation Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/E2E_TESTING_RESULTS.md Command to install the CacheKit SDK. ```bash cd cachekit make install # or: uv sync ``` -------------------------------- ### Performance Test Commands Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Bash commands to run built-in performance tests and benchmarks. ```bash # Run the built-in performance tests pytest tests/performance/ -v # Or run benchmarks uv run python -m benchmarks.cli quick --rust-only ``` -------------------------------- ### Run tests to verify setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/CONTRIBUTING.md Command to run the test suite to verify the development setup. ```bash make test ``` -------------------------------- ### ByteStorage Compression Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Demonstrates how to use the Rust-implemented compress_bytes function from Python, showing the PyO3 boundary. ```Python from cachekit_rust import compress_bytes # Rust function compressed = compress_bytes(data) # PyO3 handles conversion ``` ```Rust #[pyfunction] fn compress_bytes(data: &[u8]) -> PyResult> { // Rust implementation with LZ4 } ``` -------------------------------- ### Default Serializer Optimization Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of using the default serializer with the @cache decorator. ```python @cache # Default serializer is perfect - optimize elsewhere def fetch_data(key): return important_data() ``` -------------------------------- ### Robust Function with Error Handling Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of a CacheKit decorated function with error handling for robustness. ```python from cachekit import cache @cache(ttl=3600) def robust_function(data): try: return process_data(data) except Exception as e: logger.error(f"Processing failed: {e}") raise ``` -------------------------------- ### Quick Start Source: https://github.com/cachekit-io/cachekit-py/blob/main/llms.txt Demonstrates various cache decorator presets for different use cases. ```python from cachekit import cache @cache # Uses Redis backend by default def get_user(user_id: int): return db.fetch(user_id) @cache.minimal # Speed-critical: no reliability overhead def get_price(symbol: str): return fetch_price(symbol) @cache.production # Reliability-critical: circuit breaker + adaptive timeouts def process_payment(amount): return gateway.charge(amount) @cache.secure # Security-critical: client-side AES-256-GCM encryption def get_patient(id: int): return db.fetch_patient(id) ``` -------------------------------- ### Install dependencies Source: https://github.com/cachekit-io/cachekit-py/blob/main/CONTRIBUTING.md Command to install project dependencies using uv and make. ```bash uv sync && make install ``` -------------------------------- ### CachekitIO Cloud Decorator Usage Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of using the @cache.io decorator for CachekitIO Cloud, with a note about its alpha status. ```python from cachekit import cache @cache.io(ttl=3600) # cachekit.io is in closed alpha — request access at https://cachekit.io def get_user(user_id: int): return fetch_from_db(user_id) ``` -------------------------------- ### Basic Redis Cache Decorator Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md A simple example of using the @cache decorator with a TTL for a function that fetches user data. ```python from cachekit import cache @cache(ttl=3600) def get_user(user_id: int): return fetch_from_db(user_id) ``` -------------------------------- ### Redis Docker Setup and Environment Variable Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Commands to run Redis in a Docker container and set the REDIS_URL environment variable. ```bash docker run -p 6379:6379 redis export REDIS_URL="redis://localhost:6379" ``` -------------------------------- ### File / L1-Only Cache Decorator Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of using the @cache decorator with backend=None for an in-memory, L1-only cache, suitable for local development. ```python from cachekit import cache @cache(ttl=60, backend=None) # L1-only: in-memory, no Redis needed def get_user(user_id: int): return fetch_from_db(user_id) ``` -------------------------------- ### Migration Example: Single-Process to Multi-Pod Deployment Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/comparison.md Illustrates how CacheKit allows seamless transition from single-process development (no Redis) to multi-pod production environments (with Redis) by simply removing the `backend=None` argument. ```python # Development (single process, no Redis) @cache(backend=None, ttl=300) def expensive_operation(x): return compute(x) # Staging → Production (Redis added, just remove backend=None) # Same decorator, same function, automatically distributed @cache(ttl=300) # REDIS_URL env var makes this distributed def expensive_operation(x): return compute(x) ``` -------------------------------- ### Production-Ready Function with Reliability Features Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Example of a function decorated with cache settings including TTL, namespace, refresh behavior, and circuit breaker. ```python from cachekit import cache from cachekit.config.decorator import CircuitBreakerConfig @cache( ttl=3600, namespace="critical_service", refresh_ttl_on_get=True, ttl_refresh_threshold=0.3, circuit_breaker=CircuitBreakerConfig(enabled=True) ) def critical_business_function(request_id: str): """Production-ready function with reliability features.""" return process_business_logic(request_id) ``` -------------------------------- ### Run benchmarks Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/performance.md Commands to run component-level profiling, end-to-end decorator overhead, production-realistic scenarios, and serializer comparison benchmarks. ```bash # Component-level profiling uv run pytest tests/performance/test_cache_profiler.py -v -s # End-to-end decorator overhead uv run pytest tests/performance/test_end_to_end_latency.py -v -s # Production-realistic scenarios uv run pytest tests/performance/test_production_realism.py -v -s # Serializer comparison uv run pytest tests/performance/test_serializer_benchmarks.py -v -s ``` -------------------------------- ### Basic Usage Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/file.md Demonstrates how to initialize and use the FileBackend with default configuration. ```python from cachekit.backends.file import FileBackend from cachekit.backends.file.config import FileBackendConfig from cachekit import cache # Use default configuration config = FileBackendConfig() backend = FileBackend(config) @cache(backend=backend) def cached_function(): return expensive_computation() ``` -------------------------------- ### Prerequisites: Worker running Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README_SDK_E2E.md Commands to navigate to the saas directory and start the Worker. ```bash cd saas make dev # Starts Worker at http://localhost:8787 ``` -------------------------------- ### Type Hints Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Example of using type hints in a cache decorator function. ```python from typing import Callable from cachekit.types import Serializer def cache_decorator( redis_url: str, ttl: int = 3600, serializer: Serializer | None = None, ) -> Callable[[F], F]: """Decorate a function for caching.""" ... ``` -------------------------------- ### E002: Invalid Key Format - Invalid examples Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/troubleshooting.md Examples of invalid CACHEKIT_MASTER_KEY formats that will cause E002. ```bash export CACHEKIT_MASTER_KEY="my-secret-key" # Not hex export CACHEKIT_MASTER_KEY="abcd1234" # Too short ``` -------------------------------- ### Error Message Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Illustrates how cachekit provides explicit error messages for serialization issues, guiding users to the correct fix. ```diff - TypeError: Object of type 'User' is not JSON serializable + ValueError: Cannot serialize Pydantic model. Use .model_dump() to convert. ``` -------------------------------- ### Install Dependencies Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README.md Command to install project dependencies using uv. ```bash cd cachekit/tests/integration/saas uv sync --all-extras ``` -------------------------------- ### Environment Variable Configuration Examples Source: https://github.com/cachekit-io/cachekit-py/blob/main/llms.txt Shows example environment variables for configuring Redis, Memcached, File, CachekitIO, and encryption settings. ```bash # Redis CACHEKIT_REDIS_URL=redis://localhost:6379 CACHEKIT_DEFAULT_TTL=3600 # Memcached CACHEKIT_MEMCACHED_SERVERS=mc1:11211,mc2:11211 CACHEKIT_MEMCACHED_KEY_PREFIX=myapp: # File CACHEKIT_FILE_CACHE_DIR=/tmp/cache CACHEKIT_FILE_MAX_SIZE_MB=500 # CachekitIO CACHEKIT_API_KEY=your-api-key CACHEKIT_API_URL=https://api.cachekit.io # Encryption CACHEKIT_MASTER_KEY=hex-encoded-32-byte-key ``` -------------------------------- ### Check installed serializer Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/troubleshooting.md Prints the currently active default serializer for cachekit. ```python from cachekit.serializers import DEFAULT_SERIALIZER print(f"Active serializer: {DEFAULT_SERIALIZER}") ``` -------------------------------- ### CachekitConfig Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/api-reference.md Demonstrates how to instantiate CachekitConfig, either by loading from environment variables or by overriding specific fields. ```python from cachekit.config import CachekitConfig # Load from environment variables (recommended) config = CachekitConfig() # Or override specific fields config = CachekitConfig( default_ttl=7200, l1_enabled=True, l1_max_size_mb=100, ) ``` -------------------------------- ### Automatic tracking of HTTP GET operation Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/PERFORMANCE.md Example of how the CacheClient class automatically wraps HTTP GET operations with performance tracking using a global tracker. ```python def get(self, namespace: str, key: str) -> requests.Response: """GET a value from cache""" url = f"{self.base_url}/cache/get/{namespace}/{key}" with global_tracker.timed_operation("HTTP_GET"): return self.session.get(url) ``` -------------------------------- ### Arrow Serializer for DataFrames Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/performance.md Example of using ArrowSerializer for efficient serialization of large DataFrames. ```python from cachekit.serializers import ArrowSerializer @cache(serializer=ArrowSerializer()) def get_large_dataset(date: str): return load_dataframe(date) # 5-10x faster serialization ``` -------------------------------- ### Redis Connection Test Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Python code to test a basic Redis connection. ```python import redis try: client = redis.Redis(host='localhost', port=6379, db=0) client.ping() print("Redis connection successful") except redis.ConnectionError: print("Redis connection failed - check if Redis is running") ``` -------------------------------- ### Configuration via Python Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/file.md Illustrates how to configure the FileBackend using Python objects for cache directory, size limits, and permissions. ```python import tempfile from pathlib import Path from cachekit.backends.file import FileBackend from cachekit.backends.file.config import FileBackendConfig # Custom configuration config = FileBackendConfig( cache_dir=Path(tempfile.gettempdir()) / "myapp_cache", max_size_mb=2048, max_value_mb=200, max_entry_count=50000, lock_timeout_seconds=10.0, permissions=0o600, dir_permissions=0o700, ) backend = FileBackend(config) ``` -------------------------------- ### Quick Start Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/features/distributed-locking.md Shows a practical example of using the `@cache` decorator for a function that performs an expensive operation, with distributed locking active by default on compatible backends like RedisBackend. ```python from cachekit import cache @cache(ttl=300) # Locking active on LockableBackend (e.g. RedisBackend) def get_report(date): return db.generate_report(date) # Expensive operation # Multiple pods calling simultaneously on cache miss # Only one executes generate_report() report = get_report("2025-01-15") ``` -------------------------------- ### Long TTL Configuration Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/performance.md Example of setting a long TTL for immutable or infrequently changing data. ```python @cache(ttl=86400) # 24 hours def get_historical_data(symbol: str, date: str): return fetch_historical(symbol, date) # Immutable data ``` -------------------------------- ### CachekitIO Environment Variables Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Configuration options for the CachekitIO backend using environment variables. ```bash # Required: API key for authentication (ck_live_... format) CACHEKIT_API_KEY=ck_live_your_key_here # Optional: API endpoint (default: https://api.cachekit.io) CACHEKIT_API_URL=https://api.cachekit.io # Optional: Request timeout in seconds (default: 5.0, must be > 0) CACHEKIT_TIMEOUT=5.0 # Optional: Maximum retry attempts for transient errors (default: 3, minimum: 0) CACHEKIT_MAX_RETRIES=3 # Optional: HTTP connection pool size (default: 10, must be > 0) CACHEKIT_CONNECTION_POOL_SIZE=10 # Optional: Allow custom API hostname - disables SSRF hostname allowlist (default: false) # Only set to true when pointing at a private test server CACHEKIT_ALLOW_CUSTOM_HOST=false ``` -------------------------------- ### Migration Example: From aiocache to cachekit Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/comparison.md Demonstrates migrating from `aiocache` to CacheKit, highlighting CacheKit's ability to handle both sync and async contexts with the same decorator. ```python # OLD (aiocache) from aiocache import cached import asyncio @cached(cache=RedisCache) async def get_user(user_id): return await db.get_user(user_id) # NEW (cachekit) - sync-first approach from cachekit import cache @cache(ttl=3600) def get_user(user_id): return db.get_user(user_id) # Works in sync/async contexts ``` -------------------------------- ### Cargo Vet Exemption Configuration Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Example TOML snippet for adding cargo-vet exemptions. ```toml [[exemptions.foo]] version = "1.0.0" criteria = "safe-to-deploy" notes = "Used only in tests" ``` -------------------------------- ### Running tests against Development SaaS Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/E2E_TESTING_RESULTS.md Commands to set up the environment and run SDK E2E and data handling tests against the development CacheKit SaaS. ```bash cd saas/tests/validation # Set environment export CACHEKITIO_API_URL="https://api.dev.cachekit.io" export CACHEKITIO_API_TOKEN="ck_live_your_dev_key_here" # Run Phase 1+2 (stable against remote) pytest test_sdk_e2e.py test_sdk_data_handling.py -v ``` -------------------------------- ### Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/cachekitio.md Set the CACHEKIT_API_KEY environment variable for authentication. ```bash export CACHEKIT_API_KEY="ck_live_..." ``` -------------------------------- ### TTL Inspection (async only) Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/cachekitio.md Examples of getting the remaining TTL and refreshing the TTL of a key asynchronously. ```python backend = CachekitIOBackend() remaining = await backend.get_ttl("my-key") # seconds remaining, or None refreshed = await backend.refresh_ttl("my-key", ttl=300) # update TTL in place ``` -------------------------------- ### Quick Start Example Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/features/adaptive-timeouts.md A simple example showing the @cache decorator with ttl, implying adaptive timeout is active. It highlights that the system monitors Redis P95 latency and adjusts the timeout automatically. ```python from cachekit import cache @cache(ttl=300) # Adaptive timeout active def expensive_query(x): return db.query(x) # Monitors Redis P95 latency automatically # Adjusts timeout based on observed latency result = expensive_query(1) ``` -------------------------------- ### Local Development Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README.md Environment variables and commands to set up a local development environment for running integration tests. ```bash # In another terminal: export CACHEKIT_API_KEY="test_key_for_local_dev" export CACHEKIT_API_URL="http://localhost:8787" cd cachekit/tests/integration/saas uv run pytest -v ``` -------------------------------- ### Level 4: Advanced Control - TTL Refresh and Threshold Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md This snippet demonstrates advanced control features like TTL refresh on get and TTL refresh threshold for long-lived cache entries. ```python from cachekit import cache # Namespace for cache organization and TTL refresh @cache( ttl=7200, namespace="tenant_data", refresh_ttl_on_get=True ) def get_tenant_data(tenant_id, request): return process_tenant_request(tenant_id, request) # TTL refresh for long-lived cache entries @cache( ttl=86400, refresh_ttl_on_get=True, ttl_refresh_threshold=0.3 ) def get_user(user_id): return fetch_user(user_id) ``` -------------------------------- ### Prerequisites: Test dependencies Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README_SDK_E2E.md Command to install test dependencies from a requirements file. ```bash cd saas/tests/validation pip install -r requirements.txt ``` -------------------------------- ### Test Serializer Independently Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/troubleshooting.md Provides an example of how to use CacheKit's StandardSerializer to encode and decode data. ```python from cachekit.serializers import StandardSerializer serializer = StandardSerializer() # Test serialization data = {"key": "value"} encoded = serializer.serialize(data) print(f"Encoded: {encoded[:50]}...") # Test deserialization decoded = serializer.deserialize(encoded) print(f"Decoded matches: {decoded == data}") ``` -------------------------------- ### Writing New Tests: Using Fixtures Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README_SDK_E2E.md Example of using a test function factory fixture to create and test a function. ```python def test_with_factory(test_function_factory, clean_cache): """Test using function factory.""" # Create test function compute = test_function_factory( name="compute", computation=lambda x: x ** 2 ) # Test assert compute(5) == 25 ``` -------------------------------- ### Short TTL Configuration Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/performance.md Example of setting a short TTL for frequently changing data requiring high freshness. ```python @cache(ttl=60) # 1 minute def get_real_time_price(symbol: str): return fetch_current_price(symbol) ``` -------------------------------- ### Configuration via Environment Variables Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/file.md Shows how to configure the FileBackend using environment variables for cache directory, size limits, lock timeouts, and file permissions. ```bash # Directory for cache files export CACHEKIT_FILE_CACHE_DIR="/var/cache/myapp" # Size limits export CACHEKIT_FILE_MAX_SIZE_MB=1024 # Default: 1024 MB export CACHEKIT_FILE_MAX_VALUE_MB=100 # Default: 100 MB (max single value) export CACHEKIT_FILE_MAX_ENTRY_COUNT=10000 # Default: 10,000 entries # Lock configuration export CACHEKIT_FILE_LOCK_TIMEOUT_SECONDS=5.0 # Default: 5.0 seconds # File permissions (octal, owner-only by default for security) export CACHEKIT_FILE_PERMISSIONS=0o600 # Default: 0o600 (owner read/write) export CACHEKIT_FILE_DIR_PERMISSIONS=0o700 # Default: 0o700 (owner rwx) ``` -------------------------------- ### Enable compression Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/configuration.md Enables compression for large values, recommended for values over 1KB. Also allows setting the compression level (1-9). ```bash # Enable compression (recommended for >1KB values) export CACHEKIT_ENABLE_COMPRESSION=true # Compression level (1-9, higher = more compression) export CACHEKIT_COMPRESSION_LEVEL=6 # Default ``` -------------------------------- ### Development SaaS Environment Setup Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/E2E_TESTING_RESULTS.md Environment variables and pytest command for running end-to-end tests against the development SaaS API. ```bash $ export CACHEKITIO_API_URL="https://api.dev.cachekit.io" $ pytest test_sdk_e2e.py test_sdk_data_handling.py -v ===================== 26 passed, 1 skipped in 18.57s ======================= ``` -------------------------------- ### With Intent Presets Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/backends/none.md Shows how to use intent presets like `minimal` and `secure` with `backend=None`. ```python from cachekit import cache # Speed-critical, no backend @cache.minimal(backend=None, ttl=60) def fast_lookup(key: str) -> dict: return fetch_data(key) # With encryption, no backend (L1 stores ciphertext) @cache.secure(backend=None, ttl=3600) def sensitive_data(user_id: int) -> dict: return get_pii(user_id) ``` -------------------------------- ### Incorrect Batching Expectation Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Illustrates why decorators don't optimize across multiple calls for batch processing. ```python # WRONG: Can't optimize across multiple calls @cache def batch_process(items): return [process(item) for item in items] ``` -------------------------------- ### Incorrect Local Caching Source: https://github.com/cachekit-io/cachekit-py/blob/main/docs/getting-started.md Demonstrates a common mistake of adding local caching which breaks multi-pod consistency. ```python # WRONG: Breaks multi-pod consistency local_cache = {} @cache def get_data(key): if key in local_cache: # NO! Pods will disagree return local_cache[key] ``` -------------------------------- ### Troubleshooting: 'Connection refused' error Source: https://github.com/cachekit-io/cachekit-py/blob/main/tests/integration/saas/README_SDK_E2E.md Steps to fix a 'Connection refused' error by ensuring the worker is running. ```bash cd saas make dev # Wait for "Ready on http://localhost:8787" ``` -------------------------------- ### Type Checking Errors Debug Command Source: https://github.com/cachekit-io/cachekit-py/blob/main/DEVELOPMENT.md Commands for running type checks and getting detailed errors. ```bash make type-check # basedpyright with detailed errors uv run basedpyright --verbose # Extra debug info ```