VISEN GROUP
Technology & Engineering

Architecting High-Performance Caching: Choosing the Right Data Synchronization Pattern

November 4, 20263 min readUncategorized

In high-throughput distributed applications, memory caching (Redis / Memcached) is the primary defense mechanism protecting relational databases from workload saturation. However, improper caching patterns introduce stale data reads, cache pollution, and race conditions during database updates.

Choosing the correct caching pattern depends on your workload’s read/write ratio and data consistency tolerance.

1. Comparative Breakdown of Primary Caching Patterns

PATTERN 1: CACHE-ASIDE (LAZY LOADING)
[App] ──1. Read Cache──► [Redis] (Miss)
  │
  └──2. Read DB ───────► [PostgreSQL]
  │
  └──3. Populate Cache ─► [Redis]

PATTERN 2: WRITE-THROUGH
[App] ──1. Write ──────► [Cache Layer] ──2. Sync Write ──► [PostgreSQL]

PATTERN 3: WRITE-BEHIND (WRITE-BACK)
[App] ──1. Fast Write ──► [Cache Layer] ──2. Async Queue ──► [PostgreSQL]

2. Deep Dive: Architectural Trade-Offs

MetricCache-Aside (Lazy Loading)Write-ThroughWrite-Behind (Write-Back)
Read LatencySub-ms on Hit; High on MissAlways Sub-millisecondAlways Sub-millisecond
Write LatencyStandard DB write latencyHigher (Slower synchronous write to both)Extremely Low (Instant cache response)
Data ConsistencyEventual (Requires key invalidation)Strong / Near-ImmediateRisk of data loss if Redis crashes before flush
Best Used ForRead-heavy web applications, user profilesFinancial ledgers, critical user settingsHigh-throughput logging, live view counters

3. Production Code: Cache-Aside with Safe Cache Invalidation

When updating data in a Cache-Aside strategy, always delete (invalidate) the cache key instead of updating it in place. Updating a cache key directly introduces race conditions when two concurrent writes finish in a different order than they started.

TypeScript

import Redis from "ioredis";
import { db } from "./db";

const redis = new Redis(process.env.REDIS_URL!);

export class UserProfileService {
  private static getCacheKey(userId: string): string {
    return `user:profile:v1:${userId}`;
  }

  /**
   * Cache-Aside Read Flow
   */
  static async getUserProfile(userId: string) {
    const key = this.getCacheKey(userId);

    // 1. Attempt Cache Fetch
    const cachedData = await redis.get(key);
    if (cachedData) {
      return JSON.parse(cachedData);
    }

    // 2. Database Fallback on Cache Miss
    const query = "SELECT id, email, full_name, bio FROM users WHERE id = $1";
    const { rows } = await db.query(query, [userId]);
    const user = rows[0];

    if (!user) return null;

    // 3. Populate Cache with a Jittered TTL (Prevents Cache Stampede)
    const baseTTL = 3600; // 1 hour
    const jitter = Math.floor(Math.random() * 300); // 0-300s variance
    await redis.set(key, JSON.stringify(user), "EX", baseTTL + jitter);

    return user;
  }

  /**
   * Safe Write Invalidation Flow
   */
  static async updateUserBio(userId: string, newBio: string) {
    const key = this.getCacheKey(userId);

    // 1. Update Core Database First
    await db.query("UPDATE users SET bio = $1, updated_at = NOW() WHERE id = $2", [newBio, userId]);

    // 2. INVALIDATE (DELETE) Cache Key
    // Do NOT call redis.set() here to avoid write race conditions
    await redis.del(key);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *