Skip to content

Instantly share code, notes, and snippets.

@futzlarson
Last active April 6, 2026 18:49
Show Gist options
  • Select an option

  • Save futzlarson/5403ac2f6e9cd843bce09930214c9702 to your computer and use it in GitHub Desktop.

Select an option

Save futzlarson/5403ac2f6e9cd843bce09930214c9702 to your computer and use it in GitHub Desktop.
Caching

Master Data Caching Strategy (M1–M6)

The application has 140 master_* tables containing reference data (statuses, types, priorities, etc.). These are queried millions of times but rarely change — some are truly static (genders, states, countries), others are modified every few weeks (task statuses, case statuses).

Approach: Cache::flexible() (Laravel 11's stale-while-revalidate) at the model level via a shared trait.

  // Trait added to all Master* models
  Cache::flexible('master_smart_texts:pluck', [3600, 86400], fn () => ...);
  • Fresh for 1 hour — guaranteed current data
  • Stale-but-served for 24 hours — if the cache expires, users get the stale value instantly while it refreshes in the background. No one waits for a DB query.
  • Event-based invalidation — when an admin modifies a master record, the cache busts immediately via model saved/deleted events. Doesn't rely on TTL alone.

Why not rememberForever? Some tables do get modified (task statuses was changed 5 days ago). The 1-hour fresh window ensures changes propagate even if we miss an invalidation edge case.

Implementation:

  1. Create CachesMasterData trait — provides cachedPluck(), cachedGet() methods (~1 file)
  2. Add trait to ~20 master models that are actually queried
  3. Find-and-replace call sites across ~230 files (mechanical — same patterns repeated)
  4. Extend existing CachesIdByName trait to also use Cache::flexible for cross-request persistence
  5. Dashboard chart widgets (11 files) — same Cache::flexible wrap on expensive aggregate queries

What this eliminates:

  • 179 master data queries per page load across all routes
  • 3.5M+ redundant queries per 2 days from Livewire interactions
  • Dashboard from 2,446ms TTFB to potentially ~200ms (chart queries cached)

Production-ready: Redis is already configured as the cache store in all non-local environments. No infrastructure changes needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment