Advanced Caching

The Aurelia Fetch Client includes a sophisticated caching system that provides fine-grained control over request caching, cache storage, and cache lifecycle management. This guide covers the complete caching API, including the Cache Service, event system, and storage backends.

Overview

The caching system consists of several key components:

  • CacheInterceptor: An interceptor that automatically caches GET requests

  • CacheService: A service that manages cached data and publishes cache events

  • ICacheStorage: An interface for implementing custom storage backends

  • Built-in Storage Backends: Memory, LocalStorage, SessionStorage, and IndexedDB implementations

  • Cache Events: A comprehensive event system for monitoring cache behavior

Basic Cache Configuration

Simple Caching Setup

import { IHttpClient, CacheInterceptor } from '@aurelia/fetch-client';
import { DI, resolve } from '@aurelia/kernel';

export class CachedApiService {
  private http = resolve(IHttpClient);

  constructor() {
    // Create cache interceptor with basic configuration
    const cacheInterceptor = DI.getGlobalContainer().invoke(CacheInterceptor, [{
      cacheTime: 300_000,  // Cache valid for 5 minutes
      staleTime: 60_000,   // Data becomes stale after 1 minute
    }]);

    this.http.configure(config => config.withInterceptor(cacheInterceptor));
  }

  async getUser(id: string) {
    // This request will be automatically cached
    const response = await this.http.get(`/api/users/${id}`);
    return response.json();
  }
}

Cache Configuration Options

The cache interceptor accepts several configuration options:

Understanding Cache Timing

The difference between staleTime and cacheTime:

  • staleTime: After this period, data is considered "stale" but can still be returned while being refreshed in the background

  • cacheTime: After this period, data is completely expired and will not be returned; a fresh fetch is required

Flow:

  1. 0-1 minute: Fresh data returned from cache

  2. 1-5 minutes: Stale data returned from cache, background refresh triggered

  3. After 5 minutes: No cached data available, fresh fetch required

Cache Service API

The CacheService provides direct access to the cache and its event system.

Accessing the Cache Service

Cache Service Methods

set() and get()

Store and retrieve typed data:

setItem() and getItem()

Store and retrieve complete cache items with metadata:

delete() and clear()

Remove cached data:

Cache Events System

The cache service publishes events for all cache operations, enabling powerful monitoring and debugging capabilities.

Available Cache Events

Subscribing to Cache Events

Practical Event Monitoring Examples

Cache Performance Monitoring

Cache Debugging Dashboard

Background Refresh

Enable automatic background cache refresh to keep data fresh without user-triggered requests.

Basic Background Refresh

Conditional Background Refresh

Storage Backends

The cache system supports multiple storage backends for different use cases.

Memory Storage (Default)

Fast, temporary storage that doesn't persist across page reloads:

Characteristics:

  • Fast read/write operations

  • No persistence across page reloads

  • No storage size limits (constrained by available memory)

  • Best for: Temporary caching during a single session

LocalStorage Backend

Persistent storage that survives browser restarts:

Characteristics:

  • Data persists across browser sessions

  • ~5-10MB storage limit (varies by browser)

  • Synchronous API

  • Best for: User preferences, small datasets that should persist

SessionStorage Backend

Session-scoped storage that persists across page refreshes but not browser restarts:

Characteristics:

  • Data persists across page reloads within the same session

  • Cleared when browser tab is closed

  • ~5-10MB storage limit (varies by browser)

  • Best for: Session-specific data, temporary form state

IndexedDB Backend

Large-scale persistent storage:

Characteristics:

  • Large storage capacity (typically hundreds of MB or more)

  • Asynchronous API

  • Data persists across sessions

  • Best for: Large datasets, offline-first applications

Choosing the Right Storage Backend

Use Case
Recommended Backend
Reason

API responses for current page

MemoryStorage

Fast, no persistence needed

User preferences

BrowserLocalStorage

Needs to persist across sessions

Shopping cart

BrowserSessionStorage

Session-scoped but survives refresh

Large datasets, offline support

BrowserIndexDBStorage

Large capacity, persistent

Temporary form data

BrowserSessionStorage

Session-scoped

Authentication tokens

BrowserLocalStorage

Needs to persist, security handled elsewhere

Custom Storage Implementation

Implement your own storage backend for specialized needs:

Complete Caching Example

Here's a comprehensive example combining multiple caching features:

Best Practices

1. Choose Appropriate Cache Times

2. Monitor Cache Performance

Always implement cache monitoring in development to optimize cache configuration:

3. Use Background Refresh Strategically

Enable background refresh for frequently accessed data:

4. Handle Cache Invalidation

Invalidate cache when data changes:

Summary

The Aurelia Fetch Client caching system provides:

  • Multiple storage backends: Memory, LocalStorage, SessionStorage, IndexedDB

  • Comprehensive event system: 13 different cache events for monitoring

  • Background refresh: Automatic cache updating

  • Stale-while-revalidate: Serve stale data while fetching fresh data

  • Fine-grained control: Direct cache service access for manual management

This powerful caching system enables you to build high-performance applications with optimal data freshness and minimal network requests.

Last updated

Was this helpful?