Lewati ke konten utama

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​

EnvironmentDriver
Developmentdatabase (simple, mudah debug)
Productionredis (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​

JobPrioritasFungsi
RunAIMatchingJobHighMenjalankan AI Matching Engine
SendNotificationJobHighKirim push notification via FCM
SendEmailJobMediumKirim email notifikasi
GenerateLeaderboardJobMediumHitung ulang leaderboard harian
CalculateSISJobMediumHitung Social Impact Score
GenerateReportJobLowGenerate laporan PDF/Excel
BackupDatabaseJobLowBackup 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​

JobMax TriesBackoff
RunAIMatchingJob310 detik
SendNotificationJob55 detik
SendEmailJob330 detik
GenerateReportJob260 detik
BackupDatabaseJob1—

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).