Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions backend/src/services/__tests__/cache-read-through.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CacheService } from '../cache.js';

function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}

function makeRedis() {
return {
get: vi.fn(async (_key: string): Promise<unknown> => null),
setEx: vi.fn(async (_key: string, _ttl: number, _value: string) => undefined),
set: vi.fn(async (_key: string, _value: string) => undefined),
del: vi.fn(async (_key: string | string[]) => undefined),
scan: vi.fn(async (_cursor: number, _options: { MATCH: string }) => ({ cursor: 0, keys: [] })),
};
}

function makeService(redis: ReturnType<typeof makeRedis>) {
return new CacheService({ warmOnStartup: false }, redis as never);
}

afterEach(() => {
vi.restoreAllMocks();
});

describe('CacheService read-through optimization', () => {
it('returns a loaded value without waiting for the cache write', async () => {
const redis = makeRedis();
const write = deferred<void>();
redis.setEx.mockReturnValue(write.promise);
const service = makeService(redis);

await expect(service.get('payment:1', async () => ({ id: 'payment:1' }))).resolves.toEqual({
id: 'payment:1',
});
expect(redis.setEx).toHaveBeenCalledOnce();
expect(service.getMetrics().sets).toBe(1);

// Release the detached write so the test leaves no pending promise behind.
write.resolve();
});

it('serves cache hits without invoking the loader', async () => {
const redis = makeRedis();
redis.get.mockResolvedValue(JSON.stringify({ status: 'settled' }));
const service = makeService(redis);
const loader = vi.fn(async () => ({ status: 'pending' }));

await expect(service.get('payment:2', loader)).resolves.toEqual({ status: 'settled' });
expect(loader).not.toHaveBeenCalled();
expect(service.getMetrics()).toMatchObject({ hits: 1, misses: 0 });
});

it('coalesces concurrent misses and performs one source load and cache write', async () => {
const redis = makeRedis();
const service = makeService(redis);
const load = deferred<{ amount: number }>();
const loader = vi.fn(() => load.promise);

const first = service.get('payment:3', loader);
const second = service.get('payment:3', loader);
await Promise.resolve();
load.resolve({ amount: 25 });

await expect(Promise.all([first, second])).resolves.toEqual([
{ amount: 25 },
{ amount: 25 },
]);
expect(loader).toHaveBeenCalledOnce();
expect(redis.setEx).toHaveBeenCalledOnce();
});

it('falls back to the source when Redis read fails', async () => {
const redis = makeRedis();
redis.get.mockRejectedValue(new Error('Redis unavailable'));
const service = makeService(redis);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);

await expect(service.get('payment:4', async () => ({ id: 'from-db' }))).resolves.toEqual({
id: 'from-db',
});
expect(service.getMetrics()).toMatchObject({ misses: 1, errors: 1 });
expect(redis.setEx).toHaveBeenCalledOnce();
error.mockRestore();
});

it('treats malformed cached JSON as a miss and refreshes the entry', async () => {
const redis = makeRedis();
redis.get.mockResolvedValue('{not-json');
const service = makeService(redis);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);

await expect(service.get('payment:5', async () => ({ status: 'fresh' }))).resolves.toEqual({
status: 'fresh',
});
expect(service.getMetrics()).toMatchObject({ misses: 1, errors: 1 });
expect(redis.setEx).toHaveBeenCalledOnce();
error.mockRestore();
});

it('propagates loader failures and allows a later retry', async () => {
const redis = makeRedis();
const service = makeService(redis);
const loader = vi.fn()
.mockRejectedValueOnce(new Error('database unavailable'))
.mockResolvedValueOnce({ status: 'recovered' });

await expect(service.get('payment:6', loader)).rejects.toThrow('database unavailable');
expect(redis.setEx).not.toHaveBeenCalled();
await expect(service.get('payment:6', loader)).resolves.toEqual({ status: 'recovered' });
expect(loader).toHaveBeenCalledTimes(2);
expect(redis.setEx).toHaveBeenCalledOnce();
});

it('does not fail the successful load when a cache write rejects', async () => {
const redis = makeRedis();
redis.setEx.mockRejectedValue(new Error('Redis write failed'));
const service = makeService(redis);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);

await expect(service.get('payment:7', async () => 'source-value')).resolves.toBe('source-value');
// Allow the detached set() promise to observe and record its rejected write.
await Promise.resolve();
await Promise.resolve();
expect(service.getMetrics()).toMatchObject({ sets: 1, errors: 1 });
error.mockRestore();
});
});
85 changes: 39 additions & 46 deletions backend/src/services/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import { getRedisCache } from '../middleware/cache.js';
import { eventBus } from '../domains/event-bus.js';
import type { RedisClientType } from 'redis';

export interface CacheConfig {
defaultTtl: number; // seconds
Expand Down Expand Up @@ -42,6 +41,7 @@ const DEFAULT_CONFIG: CacheConfig = {

class CacheService {
private config: CacheConfig;
private redis: ReturnType<typeof getRedisCache>;
private metrics: CacheMetrics = {
hits: 0,
misses: 0,
Expand All @@ -53,10 +53,12 @@ class CacheService {
};
private warmers: Map<string, CacheWarmer> = new Map();
private invalidationRules: Map<string, string[]> = new Map(); // event -> cache keys to invalidate
private inFlightLoads = new Map<string, Promise<unknown>>();
private metricsInterval?: NodeJS.Timeout;

constructor(config?: Partial<CacheConfig>) {
constructor(config?: Partial<CacheConfig>, redis: ReturnType<typeof getRedisCache> = getRedisCache()) {
this.config = { ...DEFAULT_CONFIG, ...config };
this.redis = redis;
}

/**
Expand Down Expand Up @@ -96,7 +98,7 @@ class CacheService {
// Subscribe to events
if (eventBus) {
for (const [event] of this.invalidationRules) {
eventBus.on(event, (data) => {
eventBus.on(event, () => {
const keys = this.invalidationRules.get(event) || [];
this.invalidateKeys(keys).catch(console.error);
});
Expand All @@ -105,38 +107,44 @@ class CacheService {
}

/**
* Get value from cache with fallback to loader
* Read through Redis and coalesce concurrent cache misses for the same key.
* The cache write is deliberately detached from the result path: a slow or
* unavailable cache must not add its latency to the successful source read.
*/
async get<T>(key: string, loader?: () => Promise<T>, ttl?: number): Promise<T | null> {
const cacheKey = this.buildKey(key);

try {
const redis = await getRedisCache();
const cached = await redis.get(cacheKey);

if (cached) {
const cached: unknown = await this.redis.get(cacheKey);
if (cached !== null && cached !== undefined) {
this.metrics.hits++;
return JSON.parse(cached) as T;
}

this.metrics.misses++;

// If loader provided, fetch and cache
if (loader) {
const value = await loader();
if (value !== null && value !== undefined) {
await this.set(key, value, ttl);
}
return value;
return (typeof cached === 'string' ? JSON.parse(cached) : cached) as T;
}

return null;
} catch (error) {
// Cache failures are non-fatal; use the source loader when available.
this.metrics.errors++;
console.error(`[Cache] Error getting key ${cacheKey}:`, error);
// Return null on error, caller should handle fallback
return null;
}

this.metrics.misses++;
if (!loader) return null;

const inFlight = this.inFlightLoads.get(cacheKey);
if (inFlight) return inFlight as Promise<T>;

const loadPromise = (async () => {
const value = await loader();
if (value !== null && value !== undefined) {
// set() owns cache-write error handling. Do not await it on the read path.
void this.set(key, value, ttl);
}
return value;
})().finally(() => {
this.inFlightLoads.delete(cacheKey);
});

this.inFlightLoads.set(cacheKey, loadPromise);
return loadPromise;
}

/**
Expand All @@ -147,17 +155,16 @@ class CacheService {
const finalTtl = Math.min(ttl || this.config.defaultTtl, this.config.maxTtl);

try {
const redis = await getRedisCache();
const serialized = JSON.stringify(value);
this.metrics.sets++;

// Track size
this.metrics.avgSizeBytes = (this.metrics.avgSizeBytes + Buffer.byteLength(serialized)) / 2;

if (finalTtl > 0) {
await redis.setEx(cacheKey, finalTtl, serialized);
await this.redis.setEx(cacheKey, finalTtl, serialized);
} else {
await redis.set(cacheKey, serialized);
await this.redis.set(cacheKey, serialized);
}
} catch (error) {
this.metrics.errors++;
Expand All @@ -172,8 +179,7 @@ class CacheService {
const cacheKey = this.buildKey(key);

try {
const redis = await getRedisCache();
await redis.del(cacheKey);
await this.redis.del(cacheKey);
this.metrics.deletes++;
} catch (error) {
this.metrics.errors++;
Expand All @@ -186,26 +192,24 @@ class CacheService {
*/
async invalidateKeys(patterns: string[]): Promise<void> {
try {
const redis = await getRedisCache();

for (const pattern of patterns) {
const scanPattern = this.buildKey(pattern.replace(/\*/g, '*'));
const scanPattern = this.buildKey(pattern);

// Use SCAN to avoid blocking
let cursor = 0;
do {
const result = await redis.scan(cursor, { MATCH: scanPattern });
const result = await this.redis.scan(cursor, { MATCH: scanPattern });
cursor = result.cursor;

if (result.keys.length > 0) {
await redis.del(result.keys);
await this.redis.del(result.keys);
this.metrics.deletes += result.keys.length;
}
} while (cursor !== 0);
}
} catch (error) {
this.metrics.errors++;
console.error(`[Cache] Error invalidating patterns:`, error);
console.error('[Cache] Error invalidating patterns:', error);
}
}

Expand Down Expand Up @@ -301,16 +305,5 @@ export async function getCacheService(config?: Partial<CacheConfig>): Promise<Ca

export { CacheService };


/**
* #732: Redis Caching with Intelligent Invalidation - Enhanced
* Intelligent cache invalidation is already implemented above via:
* - Event-driven invalidation rules (setupInvalidationRules)
* - Pattern-based invalidation with wildcards
* - Cache warming for critical data
* - Metrics tracking (hit rate, size, errors)
* - TTL management with configurable limits
*/

// Export singleton for easy access
export const cacheService = getCacheService();
Loading