Caching Strategy
Cache-aside architecture, CacheService tags-or-fallback helper, cache map, TTLs, invalidation, and query-budget sentinels.
Binding
No generic model-cache / cache-through-Eloquent layer. Invalidation risk in a financial system is unacceptable; N+1s are fixed at the query level. Strengthen explicit cache-aside instead.
Drivers
| Driver | Tags | Multi-get | Notes |
|---|---|---|---|
redis (production primary) |
Yes | MGET / pipeline |
db0=cache, db1=queues, db2=sessions, db3=reverb |
database (self-host fallback / some test envs) |
No | WHERE IN |
Cache reads count as SQL queries in perf audits |
array (tests) |
Yes (Laravel 13) | In-memory | Process-local only |
file |
No | Sequential | Dev only |
All tags-dependent call sites go through App\Services\CacheService, which degrades to untagged keys when Cache::supportsTags() is false and logs a once-per-process warning. Tag flushes on untagged warehouses use an explicit key list or callback; otherwise entries expire on TTL.
Redis connection lifecycle
Cache latency is dominated by connecting, not by the commands. A non-persistent socket dies with the process (or the Octane request sandbox) that opened it, so the first cache command of a request pays DNS + TCP + TLS + AUTH, and — if it lands on a socket the server has already half-closed — a retry backoff on top. Against a managed Redis that is a fixed floor on every authenticated page.
Three settings remove it. All are in config/database.php (redis) and config/octane.php, all are env-overridable, and a CI check pins them.
| Setting | Default | Why |
|---|---|---|
REDIS_PERSISTENT |
true |
Uses pconnect() instead of connect(), so the socket outlives the request. A persistent socket is per PHP process, so PHP-FPM and CLI keep today's behaviour minus the reconnect. |
persistent_id (per connection, not env) |
<app-slug>-{default,cache,queue,session,reverb} |
phpredis pools persistent sockets by host, port, timeout, persistent id and retry interval. All five connections share a host and port, so a shared id would give them one socket and the last SELECT <db> would win — cache reads would silently land in the queue or session database. Never collapse them. |
REDIS_CONNECT_TIMEOUT / REDIS_READ_TIMEOUT |
2.0 / 2.0 |
phpredis defaults to 0.0 — block forever. Safe to bound here because nothing issues a blocking Redis command: both redis queues set block_for => null and there are no SUBSCRIBE callers. Named REDIS_CONNECT_TIMEOUT because config/reverb.php already uses REDIS_TIMEOUT for the Reverb scaling client's own, deliberately long, timeout. |
REDIS_TCP_KEEPALIVE |
true |
Enables kernel probes on an idle socket, so one reaped by a managed Redis proxy is discovered before a request needs it. A toggle, not an interval — phpredis coerces the value to on/off and the probe timing stays at the OS default (~2 hours on Linux). Tune net.ipv4.tcp_keepalive_time on the host if you need probes sooner. |
REDIS_BACKOFF_BASE / REDIS_BACKOFF_CAP |
25 / 250 (ms) |
With a healthy persistent socket the retry path is an outlier; when it does fire it should cost ~25 ms, not the 100–1000 ms jitter window. |
config/octane.php adds redis to warm and keeps flush empty. Octane clones the base application into a per-request sandbox and discards it afterwards, so a RedisManager first resolved inside a request takes its open connections with it and the next request re-opens them. Warming resolves the manager in the base container, where every sandbox clone inherits the same instance. The package defaults warm cache and cache.store, which build the RedisStore but leave its connection lazy — hence the extra entry.
Tenant isolation is unaffected: it stays key-level via CacheService::qualify(). One backend, one connection, tenant-qualified keys. Do not move it to cache.prefix or to a per-tenant connection.
Checking it on a running instance
Time the same connection twice in one process, then again in the next request. The first number is the handshake; the second should be sub-millisecond, and on a warm worker with REDIS_PERSISTENT=true so should the first:
php artisan tinker --execute 'foreach ([1, 2] as $i) { $t = microtime(true); Redis::connection("cache")->ping(); printf("ping %d: %.2fms%s", $i, (microtime(true) - $t) * 1000, PHP_EOL); } printf("octane.server=%s LARAVEL_OCTANE=%s%s", config("octane.server"), var_export(getenv("LARAVEL_OCTANE"), true), PHP_EOL);'
A tinker process is not an Octane worker, so it always pays one handshake — it verifies the credentials, the timeouts and the round-trip cost, not the reuse. Reuse is visible in request traces: cache operations after the initial connection reuse that connection.
Request-scoped memoisation
Prefer $this->app->scoped() bindings for services that memoize in-memory within a request (Octane-safe — reset each request/job):
CustomFieldDefinitionResolver,WidgetDataCache,RateResolverAvailabilityService,ShortageDetector, status registries, and similar
Use once() for pure in-request closures. Use Cache::memo() only when the same durable cache key is read multiple times in one request and you still want the backend read on the first call.
Do not use singletons for request-memoising services under Octane.
Cache map
| Domain | Keys / tags | TTL | Invalidation | Stats domain |
|---|---|---|---|---|
| Settings | settings:all / tag settings |
Indefinite | Write via SettingsService::flush |
settings |
| Navigation | navigation:{userId} / tag navigation |
1h (default; tunable) | Registration, role, module changes | navigation |
| Dashboard widgets | dashboard:widget:… + generation key |
5 min (default; tunable) | Generation bump (WidgetDataCache::flush) |
widgets |
| Custom field schema | schema:document.* / tag schema-registry |
1h | Schema / CF definition writes | custom-fields |
| Status / API registries | *:statuses:all, api:endpoints, … / tags list-entries, … |
Indefinite or 1h | List-value / catalogue writes | registries |
| Account insights | accounts:insights:{id} / tag account-insights |
5 min (tunable) | Account financial mutations | insights |
| Line-item picker catalogue | catalogue-items:catalogue:{warehouseId|none} / tag catalogue-items-catalogue |
5 min | CatalogueItem, related item, or catalogue-item-price write (CatalogueItemSearchService::flushCatalogue) |
registries |
| i18n strings | i18n:strings:{locale} |
Indefinite | Language import / create | i18n |
| Exchange rates | exchange-rates:{base} |
24h (tunable) | Rate write | (via CurrencyService) |
| Permissions | Spatie built-in | Spatie | Role/permission writes | — |
| Plugin registry | plugin cache keys | Indefinite | Plugin lifecycle | — |
Hit / miss instrumentation
CacheService maintains cheap forever counters:
cache-stats:{domain}:hitscache-stats:{domain}:misses
Domains: settings, navigation, widgets, custom-fields, registries, insights, i18n. Exposed on the Admin → System → Caching panel.
Dev vs prod query counts
With CACHE_STORE=database, every cache get or put is itself a SQL query, so page query counts are noticeably higher than with Redis. Compare query counts only between installs using the same cache driver.
What we deliberately do not cache
- Eloquent models via a generic observer / trait layer
- Per-row financial snapshots beyond the named domain caches above
- Anything whose invalidation trigger cannot be named in this map
Dashboard permission contexts
Every core widget declares its invalidation domain on WidgetDefinition; plugin definitions can declare a domain too. WidgetDataCache reads that declaration rather than interpreting the widget name. Rental announcements invalidate rental, schedule, stock-capacity, audit-activity, overview and project widgets. Invoice and payment announcements invalidate finance, audit-activity, overview and project widgets. Activity create, update, complete and delete announcements invalidate the activity domain through the shared dashboard transport.
Plugin display names are cached under the registries domain using tenant-qualified keys. Saving or deleting a plugin clears that map on both tagged and untagged cache drivers; the widget registry remains request-scoped.
WidgetRegistry::visibilityKey() partitions shared widget results by owner status, effective permissions, role names, sorted warehouse access, cost visibility and viewer timezone. Every new input that changes visible rows or links must enter that hash in the same change. Definitions opt into sharing with sharedCache, aclSharedCache or sharedCacheWhen; the registry resolves those declarations into a ctx cache partition. Personal approvals, personal calendars, report execution, action links and audit widgets retain recipient keys. Audit widgets include sources whose policies depend on the actual recipient.
Context payloads are keyed by their own domain generation only, so a write in one domain leaves other domains' shared results warm. Links are authorised on read: links to an index page need only the route check, and links to specific records are checked through a small cache keyed on every domain generation, so a change to a linked record in any domain re-runs the link check without recomputing the payload. Personal results reauthorise their links on each read. Domain announcements invalidate results before broadcasting. A bounded, tenant-qualified list of recently seen contexts lets WarmDashboardWidgets recompute affected shared results after the response, with fresh recipient permissions; contexts whose permissions changed are ignored. Personal widgets are never warmed by that job. The job is unique per domain until it starts, so a burst of writes queues one warm-up. With a real queue, a stale shared result queues that warm-up instead of recomputing in the web worker after the response. A cold batch is computed under one lock; a concurrent viewer of the same cold batch waits up to three seconds for it and then reads the published result.
Metadata reads batch the domain and widget generations with the viewer's context index shard and its activity entry. Viewer activity uses a separate 15-minute entry with the latest viewer ID and read time, renewed at most once a minute; background warm-ups do not write it. Each domain index is split into sixteen shards by context hash, each capped at 40 contexts and sorted by viewer activity when a context is added. Warm reads update activity without locking or rewriting that index. With loaded permission and warehouse context, an equivalent viewer's warm database-cache batch uses at most three SQL queries: metadata, viewer activity when it is due for renewal, and payloads. With the database cache driver, the widget hit and miss counters are sampled one request in ten (counting ten times) so concurrent renders do not queue on one counter row. The bounded index persists while inactive activity entries expire; expired contexts perform no provider work.
computed_at records when a provider computed a result, including stale results served during revalidation. Refreshing one widget advances that widget's revision without advancing its siblings' domains. The dashboard client merges broadcast domains over 30 seconds and suspends refresh requests while hidden. A visible dashboard without a connected Echo transport refreshes every 120 seconds; a connected warehouse-scoped viewer relies on its warehouse feeds and does not poll. A refresh re-renders lazy groups in place, and only those showing an affected domain. The controller is exported from resources/js/dashboard-refresh.js for other consumers of the dashboard channel.
Dashboard money read models
PostgreSQL maintains dashboard_money_contributions and dashboard_money_totals in the source transaction. Each contribution records the verified total and balance verdict independently. Header changes recalculate the verdict against the frozen snapshot, precision and financial source evidence. Rental children, payments, postings, event sources and currency precision changes update or invalidate the affected contributions even when writes bypass model events. Soft deletion removes a contribution; restoration recomputes it. Rollback also rolls back the contribution and its totals.
Full-population credit utilisation and rental value by state read totals grouped by account, warehouse, lifecycle and base currency. Recipient warehouse and account privacy constraints apply before grouping or ranking. Windowed providers read the dashboard_total_current and dashboard_balance_current verdicts directly on each source row without repeating source-event probes. PostgreSQL verifies these flags before every source insert or update; submitted flag values cannot override the evidence. A base-currency setting change is checked when reading either model. Exact numeric sums and incomplete-row counters prevent partial or overflowing money from being displayed. SQLite retains the direct evidence query path for its small test fixtures. Composite invoice totals aggregate BIGINT inputs directly on PostgreSQL, which returns an exact NUMERIC sum; results outside the integer money boundary remain unavailable. Generic sums for FX arithmetic and credit magnitudes retain their numeric conversion.
DashboardMoneyReadModel::rebuild() rebuilds both PostgreSQL money models atomically, locks source writes during verification and restores trigger maintenance before committing. It is a repair operation, not part of widget reads. The opt-in native latency test records complete relational fixture counts, oracle checks, cold provider timings and EXPLAIN (ANALYZE, BUFFERS) evidence.
Paid-invoice behaviour uses dashboard_payment_contributions and dashboard_payment_monthly for exact counts and sums of rounded elapsed payment days. Invoice writes maintain those totals transactionally, including quiet reparenting and deletion. The existing linked-rental warehouse refresh updates their scope too. DashboardPaymentReadModel::rebuild() atomically reconstructs them. Each viewer-local month starts with its matching UTC-month total. Indexed raw fragments add the time included outside that UTC month and subtract the time excluded inside it. Signed counts and elapsed-day sums preserve timezone offsets, daylight-saving changes and empty periods exactly, without rounding a boundary. Currency evidence does not affect payment-day counts.