Kembali ke Blog
Database·1 menit baca·25 November 2025

Redis sebagai Cache Layer di Aplikasi Node.js

Implementasi caching strategy menggunakan Redis untuk meningkatkan performa aplikasi backend.

TH
Tomi Hartanto·Senior Software Engineer

Mengapa Perlu Cache?

Query database itu mahal. Kalau data yang sama dibaca berulang kali, cache bisa mengurangi load database dan mempercepat response time secara drastis.

Cache Strategies

1. Cache-Aside (Lazy Loading)

Aplikasi cek cache dulu, kalau tidak ada baru query DB lalu simpan ke cache.

2. Write-Through

Setiap write ke DB, langsung update cache juga.

3. Write-Behind

Write ke cache dulu, kemudian async write ke DB.

Implementasi

import Redis from 'ioredis';

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

async function getCached<T>(
  key: string,
  fetchFn: () => Promise<T>,
  ttlSeconds = 300
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const data = await fetchFn();
  await redis.setex(key, ttlSeconds, JSON.stringify(data));
  return data;
}

// Usage
const user = await getCached(
  `user:${userId}`,
  () => prisma.user.findUnique({ where: { id: userId } }),
  60
);

Cache Invalidation

Hal tersulit di caching adalah invalidation. Beberapa pendekatan:

  • TTL-based (otomatis expired)
  • Event-based (invalidate saat data berubah)
  • Version-based (tambah version di key)

Kesimpulan

Redis caching bisa meningkatkan response time dari detik ke milidetik. Tapi ingat: cache invalidation adalah salah satu masalah tersulit di computer science.

TH

Tomi Hartanto

Senior Software Engineer

Backend developer dengan 8+ tahun pengalaman membangun sistem scalable. Menulis tentang arsitektur backend, database, dan DevOps.