BAB 45. QUEUE SYSTEM
Tujuan
Queue digunakan untuk proses yang tidak perlu dijalankan secara sinkron dengan HTTP request, sehingga response API tetap cepat meskipun ada proses berat di background.
Teknologi
| Environment | Driver |
|---|---|
| Development | database (simple, mudah debug) |
| Production | redis (performa tinggi, mendukung prioritas) |
Arsitektur Queue
flowchart LR
API["🌐 API Request"] --> SVC["⚙️ Service"]
SVC -->|"dispatch()"| Q[("🗄️ Queue\n(Redis/DB)")]
Q --> W1["👷 Worker 1"]
Q --> W2["👷 Worker 2"]
Q --> W3["👷 Worker 3"]
W1 --> DB[("💾 MySQL")]
W2 --> FCM["📲 FCM"]
W3 --> MAIL["📧 Email"]
style Q fill:#b45309,color:#fff
style API fill:#4f63d2,color:#fff
Daftar Job
| Job | Prioritas | Fungsi |
|---|---|---|
RunAIMatchingJob | High | Menjalankan AI Matching Engine |
SendNotificationJob | High | Kirim push notification via FCM |
SendEmailJob | Medium | Kirim email notifikasi |
GenerateLeaderboardJob | Medium | Hitung ulang leaderboard harian |
CalculateSISJob | Medium | Hitung Social Impact Score |
GenerateReportJob | Low | Generate laporan PDF/Excel |
BackupDatabaseJob | Low | Backup database harian |
Implementasi Job
// app/Modules/Matching/Jobs/RunAIMatchingJob.php
class RunAIMatchingJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 10; // detik antar retry
public function __construct(
public readonly Request $request
) {}
public function handle(MatchingEngine $engine): void
{
$engine->run($this->request);
}
public function failed(Throwable $exception): void
{
// Notifikasi siswa jika semua retry gagal
NotificationService::sendToUser(
$this->request->student->user_id,
'Gagal mencari tutor',
'Silakan coba lagi atau ubah detail request.'
);
}
}
Dispatch Job dari Service
// Di RequestService::createRequest()
RunAIMatchingJob::dispatch($request)
->onQueue('high')
->delay(now()->addSeconds(2)); // Delay 2 detik untuk memastikan data tersimpan
Queue Priority
// .env
QUEUE_CONNECTION=redis
// Menjalankan worker dengan prioritas
// php artisan queue:work --queue=high,medium,low
Retry Policy
| Job | Max Tries | Backoff |
|---|---|---|
RunAIMatchingJob | 3 | 10 detik |
SendNotificationJob | 5 | 5 detik |
SendEmailJob | 3 | 30 detik |
GenerateReportJob | 2 | 60 detik |
BackupDatabaseJob | 1 | — |
Failed Jobs
Semua job yang gagal disimpan di tabel failed_jobs untuk investigasi.
// Melihat failed jobs
php artisan queue:failed
// Retry semua failed jobs
php artisan queue:retry all
// Flush semua failed jobs
php artisan queue:flush
Laravel Horizon (Production)
Laravel Horizon digunakan untuk monitoring queue di production:
flowchart LR
H["🔭 Horizon Dashboard"] --> M["📊 Monitoring"]
M --> JPS["Jobs Per Second"]
M --> FJ["Failed Jobs"]
M --> WL["Worker Load"]
M --> RT["Runtime Stats"]
Horizon dashboard dapat diakses di /horizon (hanya untuk admin).