Cache Architecture
The caching system is designed to:- Support any Laravel cache store (Redis, database, file, Memcached, DynamoDB)
- Cache read operations (
list_all,get_one) automatically - Invalidate cache on writes using versioned keys
- Vary by request context (user, tenant, locale, query params)
- Allow per-request control with
cacheandcache_ttlparameters
Cache is disabled by default. You must explicitly enable it in configuration.
Quick Start
REST_CACHE_ENABLED=true
REST_CACHE_STORE=redis
REST_CACHE_TTL=60
REST_CACHE_TTL_LIST=60
REST_CACHE_TTL_ONE=30
'stores' => [
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
],
# First request (cache miss)
curl -X GET "http://api.example.com/api/v1/products" \
-H "Content-Type: application/json"
# Second request (cache hit)
curl -X GET "http://api.example.com/api/v1/products" \
-H "Content-Type: application/json"
Configuration Reference
config/rest-generic-class.php
Environment Variables
| Variable | Default | Description |
|---|---|---|
REST_CACHE_ENABLED | false | Master switch for package cache |
REST_CACHE_STORE | CACHE_STORE | Laravel store name |
REST_CACHE_TTL | 60 | Default TTL (seconds) |
REST_CACHE_TTL_LIST | 60 | TTL for list endpoints |
REST_CACHE_TTL_ONE | 30 | TTL for single-record endpoints |
Cache Store Options
Redis (Recommended for Production)
Best for:- High-traffic APIs
- Distributed applications (multiple servers)
- Sub-millisecond cache hits
.env
Database
Best for:- Simple deployments
- Shared hosting without Redis
- When you need queryable cache data
.env
File
Best for:- Development
- Small applications
- Single-server deployments
.env
Memcached
Best for:- Legacy systems already using Memcached
- High-performance in-memory caching
.env
How Cache Keys Work
Cache keys are generated from a fingerprint that includes:- Operation (
list_allorget_one) - Model class (e.g.,
App\Models\Product) - Route (name or path)
- HTTP method (GET, POST, etc.)
- Query parameters (
select,relations,oper,pagination, etc.) - Vary headers (
Accept-Language,X-Tenant-Id) - Authenticated user ID
- Request parameters (from request body)
- Model cache version (for invalidation)
Any change in the fingerprint creates a different cache key. This ensures correct cache isolation.
Multi-Tenancy Support
Thevary.headers configuration prevents cache pollution across tenants or locales.
Example: Multi-Tenant SaaS
Configuration:config/rest-generic-class.php
Example: Multi-Language API
Configuration:config/rest-generic-class.php
Cache Invalidation
Rest Generic Class uses versioned keys for automatic invalidation.How It Works
- Each model has a version number stored in cache
- Version is included in every read cache key
- On write operations (
create,update,destroy), version is bumped - Old cache keys become unreachable (effectively invalidated)
This approach works across all cache stores, including those without tag support (file, database).
Version Storage
Versions are stored with keys like:Manual Invalidation
To manually clear cache for a model:Per-Request Cache Control
Override cache behavior on a per-request basis.Disable Cache for One Request
Custom TTL for One Request
Example: Fresh Data on Demand
For admin users who need real-time data:Performance Impact
Benchmark Results
Test: List 100 products with category relation| Cache Store | First Request (Miss) | Second Request (Hit) | Improvement |
|---|---|---|---|
| No cache | 45ms | 45ms | - |
| Redis | 45ms | 2ms | 22.5x faster |
| Database | 45ms | 8ms | 5.6x faster |
| File | 45ms | 5ms | 9x faster |
When to Use Cache
✅ Enable cache for:- Read-heavy endpoints (product listings, category trees)
- Data that changes infrequently (settings, configurations)
- High-traffic public APIs
- Expensive queries (complex filters, multiple relations)
- Write-heavy endpoints (webhooks, real-time updates)
- User-specific data (shopping carts, notifications)
- Admin dashboards requiring fresh data
- Development/testing environments
Monitoring Cache
Redis Monitoring
Check cache hit rate:Laravel Telescope
Enable cache monitoring in Telescope:config/telescope.php
/telescope/cache.
Custom Logging
Log cache hits/misses:Troubleshooting
Cache Not Working
Symptom: Identical requests are always slow Checks:- Is cache enabled?
REST_CACHE_ENABLED=true - Is the store configured? Check
config/cache.php - Is the method cacheable? Check
cacheable_methodsconfig - Are you testing with
cache=false?
Stale Data After Updates
Symptom: GET returns old data after PUT/DELETE Cause: Cache version not bumped (transaction rollback?) Solution: Check logs for transaction errors:Cache Growing Too Large
Symptom: Cache store running out of memory Causes:- TTL too high
- Too many unique requests (different query params)
- Version keys accumulating
- Lower TTL:
REST_CACHE_TTL=30 - Use Redis maxmemory policy:
maxmemory-policy allkeys-lru - Periodically clear old versions:
Different Cache per Server
Symptom: Inconsistent responses in load-balanced setup Cause: Using file cache with multiple servers Solution: Switch to Redis or Memcached:.env
Next Steps
Advanced Filtering
Optimize cached queries with efficient filters
Bulk Operations
Understand cache invalidation with bulk updates
Performance Tuning
Advanced performance optimization techniques
Configuration Reference
Complete cache configuration options
Evidence
-
File:
src/Core/Services/BaseService.php
Lines: 1082-1212
ImplementsshouldUseCache(),rememberWithCache(),buildCacheKey(),resolveCacheTtl(),getCacheVersion(),bumpCacheVersion() -
File:
config/rest-generic-class.php
Lines: 37-52
Defines cache configuration structure -
File:
documentacion/doc-en/02-configuration/03-cache-strategy.md
Lines: 1-66
Explains cache strategy and store selection