Lewati ke konten utama

BAB 52. CACHING STRATEGY

Tujuan

Caching digunakan untuk mengurangi beban database, mempercepat response API, dan meningkatkan skalabilitas sistem saat jumlah pengguna bertambah.


Teknologi

EnvironmentDriverKeterangan
DevelopmentfileMudah di-debug, tidak perlu Redis
ProductionredisPerforma tinggi, mendukung TTL dan pub/sub

Objek yang Di-cache

ObjekCache KeyTTLInvalidasi
Profil penggunauser:{id}10 menitSaat profil diupdate
Daftar skillskills:all60 menitSaat skill master berubah
Mata pelajaransubjects:school:{id}24 jamSaat admin update mapel
Leaderboardleaderboard:school:{id}5 menitSetelah SIS dihitung ulang
Dashboard statistikdashboard:student:{id}5 menitSetelah sesi selesai
Academic year aktifacademic_year:school:{id}60 menitSaat admin ganti tahun ajaran
Data sekolahschool:{id}60 menitSaat admin update data sekolah

Arsitektur Cache

flowchart LR
C["📱 Client"] --> API["🌐 Laravel API"]
API --> CACHE{{"🗄️ Redis Cache"}}
CACHE -->|"Cache Hit ✅"| R1["⚡ Response\n(cepat)"]
CACHE -->|"Cache Miss ❌"| DB[("💾 MySQL")]
DB --> CACHE
CACHE --> R2["📤 Response\n(disimpan ke cache)"]

style CACHE fill:#dc2626,color:#fff

Implementasi di Laravel

// app/Modules/Students/Services/StudentService.php

public function getProfile(int $studentId): Student
{
return Cache::remember(
"user:{$studentId}",
now()->addMinutes(10),
fn () => Student::with(['user', 'classroom', 'skills'])->findOrFail($studentId)
);
}

public function updateProfile(int $studentId, array $data): Student
{
$student = $this->repository->update($studentId, $data);

// Invalidasi cache setelah update
Cache::forget("user:{$studentId}");

return $student;
}

Leaderboard Cache

// app/Modules/Leaderboard/Services/LeaderboardService.php

public function getLeaderboard(int $schoolId): Collection
{
return Cache::remember(
"leaderboard:school:{$schoolId}",
now()->addMinutes(5),
fn () => Student::where('school_id', $schoolId)
->orderByDesc('sis_score')
->limit(100)
->get()
);
}

Strategi Invalidasi Cache

Cache dihapus secara otomatis via Laravel Observer saat data berubah:

// app/Modules/Students/Observers/StudentObserver.php

class StudentObserver
{
public function updated(Student $student): void
{
Cache::forget("user:{$student->id}");
Cache::forget("leaderboard:school:{$student->school_id}");
Cache::forget("dashboard:student:{$student->id}");
}
}

Keuntungan Caching

KeuntunganDampak
Kurangi query DBDatabase tidak kelebihan beban
Response lebih cepatUser experience lebih baik
ScalableMendukung banyak pengguna bersamaan
Leaderboard real-time semuUpdate 5 menit sekali, terasa real-time