Cache-Aside (Lazy Loading)

cachingEasy
Applicability

When to Use

When read-heavy workloads need acceleration
When data can tolerate brief staleness
When you want simple cache management
Overview

How It Works

Cache-Aside is the most common caching pattern in MCP architectures. The agent checks Redis first for the requested data. On a cache miss, it fetches from PostgreSQL (or another source MCP server) and stores the result in Redis with a TTL. Subsequent reads hit the cache until the TTL expires. This pattern is simple to implement and works well for read-heavy workloads. The trade-off is that the first request after a cache miss or expiration will be slower. For write operations, the application writes to the database and invalidates the cache.
Implementation

Code Example

typescript
async function getWithCache(key, fetchFn, ttl = 300) {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);
  
  const data = await fetchFn();
  await redis.set(key, JSON.stringify(data), { EX: ttl });
  return data;
}

// Usage
const user = await getWithCache(
  `user:${id}`,
  () => postgres.query("SELECT * FROM users WHERE id=$1", [id]).then(r => r.rows[0]),
  300 // 5 minute TTL
);

Quick Info

Categorycaching
ComplexityEasy

Need Architecture Help?

Our team designs custom automation architectures.

Get in Touch