Skip to main content
This page demonstrates practical caching strategies using the Rest Generic Class package’s built-in cache support.

Overview

The package provides automatic caching for read operations (list_all and get_one) with support for:
  • Multiple cache stores (Redis, Database, File, Memcached)
  • Request-aware cache keys (query params, user context, tenant ID)
  • Automatic cache invalidation on write operations
  • Per-request cache control

Cache Strategy Overview

How Cache Keys Work

Cache keys include:
  • Model name - Isolates different models
  • Operation type - list or show
  • Route signature - URL path
  • Query parameters - select, relations, oper, pagination
  • User context - Authenticated user ID
  • Headers - Accept-Language, X-Tenant-Id
  • Model version - Bumped on any write operation
Cache keys are automatically generated using SHA256 hashing of normalized request parameters. Different query params = different cache entries.

Setup Examples

Scenario 1: Basic Redis Cache Setup

1

Install Redis Driver

2

Configure Redis Connection

Edit config/database.php:
3

Enable Cache in Laravel

Edit config/cache.php:
4

Enable Package Cache

Add to .env:

Scenario 2: Database Cache (No Redis)

Goal: Use database caching when Redis is not available.
1

Create Cache Table

2

Configure Cache Store

Database caching is slower than Redis but works without additional infrastructure. Use Redis for production environments with high traffic.

Scenario 3: File Cache (Development)

Goal: Simple file-based caching for local development.

Multi-Tenant Caching

Scenario 4: Tenant-Aware Cache Keys

Goal: Prevent cache leakage between tenants in a multi-tenant application.
1

Add Tenant Middleware

Create app/Http/Middleware/SetTenantContext.php:
2

Register Middleware

Add to app/Http/Kernel.php:
3

Make API Requests with Tenant Header

The package automatically includes X-Tenant-Id in cache keys, ensuring tenant isolation without additional configuration.

Scenario 5: Per-Tenant Cache TTL

Goal: Different cache durations for different tenant tiers.

Request-Level Cache Control

Scenario 6: Bypass Cache for Fresh Data

Goal: Disable cache for specific requests that need real-time data.

Scenario 7: Custom TTL Per Request

Goal: Override default cache duration for specific queries.
cache_ttl is specified in seconds. This overrides both REST_CACHE_TTL_LIST and REST_CACHE_TTL_ONE for this specific request.

Scenario 8: Long-Lived Cache for Static Data

Goal: Cache rarely-changing data (categories, settings) for extended periods.

Cache Invalidation

Scenario 9: Automatic Invalidation on Write

How it works: Any create, update, or delete operation automatically bumps the model’s cache version, invalidating all cached entries for that model.

Scenario 10: Manual Cache Clear

Goal: Clear cache manually when needed (e.g., after bulk imports).

Performance Optimization

Scenario 11: Optimizing High-Traffic Endpoints

Goal: Maximize cache hit rate for popular product listings.
1

Identify High-Traffic Queries

2

Increase Cache TTL for Popular Endpoints

3

Use Redis with Eviction Policy

Edit redis.conf:
4

Monitor Cache Hit Rate

Scenario 12: Warming Cache After Deployment

Goal: Pre-populate cache with common queries after deployment.

Cache Monitoring

Scenario 13: Tracking Cache Effectiveness

Goal: Monitor cache hit/miss rates to optimize configuration.

Language-Aware Caching

Scenario 14: Multi-Language Cache Isolation

Goal: Separate cache entries for different languages.
The Accept-Language header is automatically included in cache keys, ensuring Spanish and English responses are cached separately.

Common Caching Patterns

Scenario 15: Cache Stampede Prevention

Goal: Prevent multiple requests from regenerating the same cache simultaneously.

Configuration Reference

Troubleshooting

Cache not invalidating after updatesEnsure write operations go through the BaseService methods (create, update, destroy). Direct Eloquent queries bypass cache invalidation.❌ Wrong: Product::where('id', 5)->update(['price' => 99])✅ Correct: $productService->update(5, ['price' => 99])
Different cache entries for same queryJSON parameter order affects cache keys. Normalize your client-side requests:
Queue workers using stale cacheRestart queue workers after cache configuration changes:

Next Steps