Menguji dampak caching terhadap performa: cache hit ratio, Redis/Memcached performance, CDN testing, dan strategi caching yang tepat untuk berbagai jenis data dan traffic patterns.

Setelah di episode 14 kita mengintegrasikan performance testing ke CI/CD, kini saatnya membahas strategi yang paling powerful untuk meningkatkan performa: caching. Caching adalah penyimpanan sementara hasil komputasi atau query di lokasi yang lebih cepat diakses — mengurangi latency secara dramatis untuk request yang berulang.
Cache yang efektif bisa mengurangi latency 90% atau lebih dan mengurangi load database secara signifikan. Tetapi caching juga menambah kompleksitas: stale data, cache invalidation, dan cache stampede. Testing caching membutuhkan pendekatan khusus yang berbeda dari testing aplikasi tanpa cache.
| Tanpa Cache | Dengan Cache | Improvement |
|---|---|---|
| Database query: 50ms | Redis GET: 1ms | 50x lebih cepat |
| API call external: 200ms | Cached response: 2ms | 100x lebih cepat |
| Full page render: 800ms | Cached HTML: 50ms | 16x lebih cepat |
Cache mengurangi beban pada bottleneck downstream (database, API external) — yang berarti sistem bisa melayani lebih banyak request dengan resource yang sama.
Cache hit ratio = jumlah cache hits / (hits + misses). Ratio tinggi (90%+) berarti cache bekerja efektif. Ratio rendah berarti banyak data yang tidak bisa di-cache atau cache terlalu kecil.
// k6: ukur cache hit ratio
import http from 'k6/http';
import { Counter } from 'k6/metrics';
const cacheHits = new Counter('cache_hits');
const cacheMisses = new Counter('cache_misses');
export default function () {
const res = http.get('https://api.example.com/products');
if (res.headers['X-Cache'] === 'HIT') {
cacheHits.add(1);
} else {
cacheMisses.add(1);
}
}# Cache hit ratio
rate(cache_hits_total[5m]) / (rate(cache_hits_total[5m]) + rate(cache_misses_total[5m]))Redis adalah in-memory data store yang sering digunakan sebagai cache. Untuk menguji Redis performance:
# Redis benchmark
redis-benchmark -h localhost -p 6379 -c 50 -n 100000 -d 256
# Hasil: SET operations per second, GET operations per second// k6: test aplikasi dengan cache
export const options = {
vus: 100,
duration: '5m',
};
export default function () {
// First request: cache miss (database hit)
// Subsequent requests: cache hit (Redis GET)
const res = http.get('https://api.example.com/products/1');
check(res, {
'status 200': (r) => r.status === 200,
'response time < 100ms': (r) => r.timings.duration < 100,
});
}Cache stampede terjadi ketika cache expired dan banyak request bersamaan mencoba membangun ulang cache — menyebabkan spike load ke database. Testing cache stampede:
// k6: test cache stampede scenario
export const options = {
stages: [
{ duration: '30s', target: 100 }, // Warm up cache
{ duration: '10s', target: 0 }, // Cache expires
{ duration: '30s', target: 200 }, // Stampede: semua request ke database
{ duration: '1m', target: 100 }, // Stabilize
],
};CDN (Content Delivery Network) adalah jaringan server tersebar yang menyimpan konten statis (images, CSS, JS) di lokasi geografis dekat dengan user. CDN mengurangi latency dan bandwidth server utama.
// k6: test CDN performance
export default function () {
const res = http.get('https://cdn.example.com/images/product.jpg');
check(res, {
'CDN status 200': (r) => r.status === 200,
'CDN cache HIT': (r) => r.headers['X-Cache'] === 'HIT',
'CDN latency < 50ms': (r) => r.timings.duration < 50,
});
}Pahami dan test headers caching:
# Cache-Control: berapa lama konten di-cache
Cache-Control: public, max-age=3600 # 1 jam
Cache-Control: public, max-age=31536000, immutable # 1 tahun
# ETag: validasi apakah konten berubah
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
# Vary: cache berdasarkan header tertentu
Vary: Accept-Encoding, Authorization# Test: invalidasi CDN dan impact terhadap latency
# 1. Warm CDN cache
for i in {1..100}; do
curl -s -o /dev/null -w "%{http_code} %{time_total}\n" https://cdn.example.com/image.jpg
done
# 2. Invalidate CDN cache
aws cloudfront create-invalidation --distribution-id EXXX --paths "/*"
# 3. Test ulang: latency harus naik (cache miss) lalu turun lagi
for i in {1..100}; do
curl -s -o /dev/null -w "%{http_code} %{time_total}\n" https://cdn.example.com/image.jpg
doneAplikasi mengecek cache dulu; jika miss, query database, lalu simpan ke cache:
async function getProduct(id) {
const cached = await redis.get(`product:${id}`);
if (cached) return JSON.parse(cached);
const product = await db.query('SELECT * FROM products WHERE id = $1', [id]);
await redis.setex(`product:${id}`, 3600, JSON.stringify(product));
return product;
}| Pattern | Deskripsi | Trade-off |
|---|---|---|
| Write-Through | Tulis ke cache dan database bersamaan | Data konsisten, write latency lebih tinggi |
| Write-Behind | Tulis ke cache, async ke database | Write cepat, risiko data loss |
TTL menentukan berapa lama data di-cache. TTL terlalu pendek = banyak cache miss. TTL terlalu panjang = data stale.
Di episode 15 ini kalian telah memahami caching & CDN testing:
Di episode 16 selanjutnya, kita akan membahas Cloud & Serverless Performance — testing cold start, autoscaling, dan performa aplikasi di infrastruktur cloud-native. Siapkan cloud account kalian!