Skip to main content
Rest Generic Class includes a comprehensive caching layer that works with any Laravel cache store. This guide shows you how to configure caching, understand cache key generation, and manage cache invalidation.

Cache Architecture

The caching system is designed to:
  1. Support any Laravel cache store (Redis, database, file, Memcached, DynamoDB)
  2. Cache read operations (list_all, get_one) automatically
  3. Invalidate cache on writes using versioned keys
  4. Vary by request context (user, tenant, locale, query params)
  5. Allow per-request control with cache and cache_ttl parameters
Cache is disabled by default. You must explicitly enable it in configuration.

Quick Start

Configuration Reference

config/rest-generic-class.php

Environment Variables

Cache Store Options

Best for:
  • High-traffic APIs
  • Distributed applications (multiple servers)
  • Sub-millisecond cache hits
.env
Setup Redis:

Database

Best for:
  • Simple deployments
  • Shared hosting without Redis
  • When you need queryable cache data
.env
Create cache table:

File

Best for:
  • Development
  • Small applications
  • Single-server deployments
.env
File cache doesn’t work in multi-server deployments. Each server has its own cache, leading to inconsistencies.

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:
  1. Operation (list_all or get_one)
  2. Model class (e.g., App\Models\Product)
  3. Route (name or path)
  4. HTTP method (GET, POST, etc.)
  5. Query parameters (select, relations, oper, pagination, etc.)
  6. Vary headers (Accept-Language, X-Tenant-Id)
  7. Authenticated user ID
  8. Request parameters (from request body)
  9. Model cache version (for invalidation)
Example fingerprint:
This is hashed to create the cache key:
Any change in the fingerprint creates a different cache key. This ensures correct cache isolation.

Multi-Tenancy Support

The vary.headers configuration prevents cache pollution across tenants or locales.

Example: Multi-Tenant SaaS

Configuration:
config/rest-generic-class.php
Requests:
Each tenant gets a separate cache entry, preventing data leaks.

Example: Multi-Language API

Configuration:
config/rest-generic-class.php
Requests:

Cache Invalidation

Rest Generic Class uses versioned keys for automatic invalidation.

How It Works

  1. Each model has a version number stored in cache
  2. Version is included in every read cache key
  3. On write operations (create, update, destroy), version is bumped
  4. Old cache keys become unreachable (effectively invalidated)
Example:
This approach works across all cache stores, including those without tag support (file, database).

Version Storage

Versions are stored with keys like:
Versions are stored forever (no TTL), ensuring consistent invalidation.

Manual Invalidation

To manually clear cache for a model:
Or clear all cache:

Per-Request Cache Control

Override cache behavior on a per-request basis.

Disable Cache for One Request

This bypasses cache and queries the database directly (but doesn’t update cache).

Custom TTL for One Request

This request will be cached for 300 seconds (5 minutes) instead of the default.

Example: Fresh Data on Demand

For admin users who need real-time data:
For public users (cached):

Performance Impact

Benchmark Results

Test: List 100 products with category relation

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)
Disable cache for:
  • 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:
List all package keys:
Monitor cache operations in real-time:

Laravel Telescope

Enable cache monitoring in Telescope:
config/telescope.php
View cache operations at /telescope/cache.

Custom Logging

Log cache hits/misses:

Troubleshooting

Cache Not Working

Symptom: Identical requests are always slow Checks:
  1. Is cache enabled? REST_CACHE_ENABLED=true
  2. Is the store configured? Check config/cache.php
  3. Is the method cacheable? Check cacheable_methods config
  4. Are you testing with cache=false?
Debugging:

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:
Manually bump version if needed (see Manual Invalidation above).

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
Solutions:
  • 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
    Implements shouldUseCache(), 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