Aller au contenu

Cache Utilities

Redis-backed caching layer for database query results. Uses IORedis with a remote Redis instance (connection details from Doppler).

getFromCacheOrDatabase

Location: cache-or-database.ts

Read-through cache pattern: tries Redis first, falls back to Postgres, then populates the cache for subsequent reads.

import { getFromCacheOrDatabase } from 'src/__new/lib/cache/cache-or-database'

const properties = await getFromCacheOrDatabase({
  cacheKey: 'recent-properties:list',
  cacheExpirationInSec: 60,
  getInDatabase: () => repository.getRecentProperties(),
  validator: recentPropertiesValidator, // optional
})

Parameters

Param Required Purpose
cacheKey yes Redis key (namespace your keys to avoid collisions)
cacheExpirationInSec yes TTL in seconds
getInDatabase yes Async function that queries Postgres
validator no idonttrustlikethat validator for cached JSON. Use when the cached shape includes dates or complex types that need remapping after JSON deserialization

Behavior with validator

When a validator is provided: 1. Read Redis once 2. If cache hit → validate against the validator 3. If validation passes → return the validated value (dates are properly remapped) 4. If validation fails → log a warning with error details, fetch from database, repopulate cache 5. If cache miss → fetch from database, write to cache

Without a validator, the cache hit is returned directly (no validation step).

When to use a validator

Use the validator param when your cached data contains: - Date fields (JSON serialization loses Date objects → need .map() to dayjs/Date) - Branded types that need validation - Schemas that evolved since the cache was populated (prevents stale shape from crashing downstream)

Cache write failures

Cache write errors are caught and logged — they never fail the request. The function always returns fresh DB data as a fallback.

RedisClient

Location: redis-client.ts

Low-level Redis operations. All JSON values are wrapped in { value: T } for forward-compatible extensibility.

Method Purpose
getValue<T>(key) Get and JSON-parse a cached object
setValue<T>(key, value) Set without expiration
setValueWithExp<T>(key, value, sec) Set with TTL in seconds
setValueWithExpMs<T>(key, value, ms) Set with TTL in milliseconds
deleteValue(key) Delete a key (logs warning on failure)
getValueAndValidate<T>(key, validator) Get + validate (throws on validation failure)
getValueWithExpiration<T>(key) Get value + remaining TTL
setPrimitiveValue(key, value) Store raw number/string (no JSON wrapping)
getPrimitiveValue<T>(key) Read raw number/string
incrementAndGet(key, n) Atomic INCRBY
incrementAndExpireAfter(key, date) INCR + EXPIRE at a given moment
decrementAndExpireAfter(key, date) DECR + EXPIRE at a given moment
addToHyperLogLog(key, ...elements) PFADD for cardinality estimation
getHyperLogLogCount(key) PFCOUNT

Caching conventions

  • Key format: {domain}:{identifier} (e.g. recent-properties:list, portfolio:boot:{userId})
  • Short TTLs (30–120s) for frequently-changing data on hot paths
  • Longer TTLs (5–30min) for near-static reference data
  • Always handle cache misses gracefully — the DB is the source of truth
  • Prefer getFromCacheOrDatabase over manual getValue + setValue pairs