Nextjs Cache API Instrumentation Observability Request Lifecycle
Definisi
cache() API (Cache Components / unstable_cache, dan cache() dari react) adalah mekanisme memoization di level module/request untuk men-cache hasil fungsi agar tidak dijalankan berulang dalam satu render. Instrumentation (instrumentation.ts + register()) adalah hook lifecycle saat server Node/Edge startup, cocok untuk inisialisasi observability (OpenTelemetry, logger).
Kapan dipakai
- cache(): fungsi mahal (fetch DB, compute) yang dipanggil berkali-kali dalam satu request tree tapi hasilnya sama; ingin dedupe otomatis.
- Instrumentation: inisialisasi tracer/metrics sekali saat proses start, bukan di tiap handler.
- Jangan pakai
cache()untuk data yang harus selalu fresh per-request tanpa revalidasi.
Cara kerja
cache() react
import { cache } from 'react';
export const getUser = cache(async (id: string) => {
const res = await db.user.findUnique({ where: { id } });
return res;
});
// dipanggil 5x di tree berbeda, hanya 1x jalaninstrumentation.ts
// file: instrumentation.ts (root atau src/)
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const { initTracing } = await import('./lib/tracing');
initTracing();
}
}Hubungkan dengan logging request
// middleware.ts
export function middleware(req: NextRequest) {
const start = Date.now();
const res = NextResponse.next();
res.headers.set('x-response-time', String(Date.now() - start));
return res;
}Struktur alur request
Loading diagram...
Contoh cache dengan revalidate
import { unstable_cache } from 'next/cache';
const getStats = unstable_cache(
async () => db.stats(),
['stats'],
{ revalidate: 60 }
);Catatan implementasi
cache()dari React berlaku per-request (dudu global antar request) — beda denganunstable_cacheyang bisa cross-request via data cache.register()hanya jalan di server; cekNEXT_RUNTIMEsebelum impor berat.- Hindari side-effect di dalam fungsi
cache()(logging, mutate) karena bisa dipanggil sekali lalu didedupe. - Untuk observability produksi, pasangkan dengan exporter (OTLP) bukan cuma console.
Kesalahan umum
- Menganggap cache() global: hasil tidak dibagikan antar request berbeda.
- Side-effect di fungsi cache: tidak jalan saat dedupe, log hilang.
- Instrumentation impor berat tanpa guard runtime: gagal di edge runtime.
- Tidak set revalidate: data stale menempel lama.