$http Service Caching in AngularJS 1.8.2: Missing Timeout Constraint for Stale Data During Migration
0 reputation · 19 Oct 2024, 14:23 UTC
0 reputation · 19 Oct 2024, 14:23 UTC
When a small AngularJS application is migrated live, the $http service’s built‑in caching can return stale responses if the server data changes between requests. The cache is populated automatically when cache:true is set, but there is no built‑in timeout or invalidation policy.
To avoid downtime, the application must keep the UI in sync with the server after migration. The missing constraint is a mechanism to expire or refresh cached entries after a configurable period or event.
31275 reputation · 19 Oct 2024, 17:50 UTC
In AngularJS 1.8.2 there is no built-in timeout or TTL for $http caching. The safest migration-safe approach is to stop using cache:true for the affected endpoints and replace it with a custom $cacheFactory instance that stores a timestamped wrapper. A request/response interceptor then checks age against a configurable maxAge and bypasses or refreshes stale entries. For the live migration window, force a one-time eviction and then re-enable caching with the wrapper.
cache:true uses a $cacheFactory instance keyed by URL and params.Stale data after migration is likely because cached responses remain valid indefinitely until manually evicted. The UI will keep reading the old $cacheFactory entry even after the server has changed.
cache:true versus a custom cache object, and which $cacheFactory instance is shared.var ttlCache = $cacheFactory('apiTtlCache');
{data: response, ts: Date.now()} in ttlCache under the $http cache key.Date.now() - entry.ts to a configurable maxAge. If stale, delete the entry and let the request go to the server, or return the stale value and trigger a background refresh.ttlCache.removeAll() or remove keys for the migrated endpoints, then re-enable the TTL wrapper. This avoids serving pre-migration data.A custom interceptor can reliably track and invalidate stale entries. It adds a small CPU cost per hit for the timestamp check and a memory cost for the wrapper. Always-revalidate interceptors negate caching benefits and increase load during live migration, so use maxAge rather than forced revalidation.
Community wrappers for AngularJS 1.x historically added TTL semantics on top of $cacheFactory. Compatibility with 1.8.2 and current maintenance status is variable and must be verified before adoption. No officially supported TTL is provided by AngularJS core.
Assumption: you are on AngularJS 1.8.2 and the cache is client-side only. Verification needed: confirm which endpoints share a cache instance and whether they can be isolated. That detail changes whether a global interceptor or per-service cache is appropriate.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.