# Redis for Notifications Only (Option 3)

## 🎯 **Description**

Hybrid implementation that uses **Redis only for notification queues** while maintaining **Pusher for real-time broadcasting**.

## 🏗️ **Architecture**

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Frontend      │    │   Backend       │    │   Redis         │
│                 │    │                 │    │                 │
│  Pusher Echo    │◄───┤  Pusher Event  │    │  notifications  │
│  (JavaScript)   │    │  (Broadcasting) │    │  queue          │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                ▲
                                │
                       ┌─────────────────┐
                       │   Database      │
                       │                 │
                       │  Other Jobs     │
                       │  (sync queues)  │
                       └─────────────────┘
```

## 🚀 **Notification Flow**

1. **Create Alert**: `CreateAlertRedis::create()`
2. **Dispatch Job**: `ProcessNotificationJob` → Redis Queue
3. **Process Job**: Create alert in DB + Update cache
4. **Broadcast**: `AlertsBroadcast` → Pusher
5. **Frontend**: Receives notification via Pusher Echo

## 📁 **Created Files**

- `src/App/Jobs/ProcessNotificationJob.php` - Job to process notifications
- `src/Domain/Alerts/Actions/CreateAlertRedis.php` - Optimized action
- `config/horizon.php` - Configuration for supervisor-7 for notifications

## ⚙️ **Configuration**

### **1. Environment Variables (.env)**

```env
# Redis for notification queues
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_DB=0

# Pusher for broadcasting (keep existing)
PUSHER_APP_ID=your_pusher_app_id
PUSHER_APP_KEY=your_pusher_app_key
PUSHER_APP_SECRET=your_pusher_app_secret
PUSHER_APP_CLUSTER=your_pusher_cluster

# IMPORTANT: DO NOT change QUEUE_CONNECTION
QUEUE_CONNECTION=sync

# Horizon handles workers automatically
# No additional configuration needed
```

### **2. Horizon Configuration**

```php
// config/horizon.php
'supervisor-7' => [
    'connection' => 'redis',
    'queue' => ['notifications'],
    'balance' => 'auto',
    'autoScalingStrategy' => 'time',
    'maxProcesses' => 2, // Local: 2, Production: 4
    'maxTime' => 0,
    'maxJobs' => 0,
    'memory' => 128,
    'tries' => 3,
    'timeout' => 30,
    'nice' => 0,
],
```

## 🚀 **Usage**

### **Create Individual Notification**

```php
use Domain\Alerts\Actions\CreateAlertRedis;

CreateAlertRedis::create([
    'title' => 'New notification',
    'message' => 'You have a new notification',
    'model' => 'User',
    'model_id' => 123,
    'level' => 'info'
]);
```

### **Create Bulk Notifications**

```php
$notifications = [
    [
        'title' => 'Notification 1',
        'message' => 'Message 1',
        'model' => 'User',
        'model_id' => 1
    ],
    [
        'title' => 'Notification 2',
        'message' => 'Message 2',
        'model' => 'User',
        'model_id' => 2
    ]
];

CreateAlertRedis::createBulk($notifications, $userId);
```

## 🔧 **Commands**

### **Horizon Management**

```bash
# Start Horizon (automatically handles all queues)
php artisan horizon

# View Horizon dashboard
http://your-domain/horizon

# Stop Horizon
php artisan horizon:terminate

# Restart Horizon
php artisan horizon:terminate && php artisan horizon

# Check if Horizon is running
pgrep -f horizon
```

### **Monitoring**

```bash
# View jobs in queue
redis-cli llen notifications

# View Redis information
redis-cli info

# View notification logs
tail -f storage/logs/laravel.log | grep ProcessNotificationJob

# Monitor Redis in real-time
redis-cli monitor
```

## ✅ **Advantages**

- ✅ **Minimal change**: Only affects notifications
- ✅ **Low risk**: If Redis fails, only notifications are affected
- ✅ **Simple implementation**: Only create specific jobs
- ✅ **Maintains stability**: Other jobs continue working the same
- ✅ **Easy rollback**: You can return to database queues easily
- ✅ **Better performance**: Redis is faster for queues
- ✅ **Scalability**: You can process more notifications
- ✅ **Horizon integrated**: Professional dashboard for monitoring
- ✅ **Auto-scaling**: Horizon handles workers automatically
- ✅ **Centralized management**: All queues in one place
- ✅ **No autostart**: Horizon handles everything automatically
- ✅ **Clean configuration**: No unnecessary code

## ⚠️ **Considerations**

- ⚠️ **Redis required**: You need Redis installed and running
- ⚠️ **Horizon required**: You must run `php artisan horizon`
- ⚠️ **Mixed system**: You have two different queue systems
- ⚠️ **Monitoring**: You need to monitor both Redis and database queues

## 🔄 **Gradual Migration**

1. **Install Redis** and configure
2. **Configure Horizon** with supervisor-7
3. **Use CreateAlertRedis** for new notifications
4. **Keep CreateAlert** for compatibility
5. **Test in development** before production
6. **Gradually migrate** other jobs if necessary

## 🆘 **Troubleshooting**

### **Redis not responding**
```bash
# Check status
redis-cli ping

# Restart Redis
sudo systemctl restart redis-server
```

### **Jobs not processing**
```bash
# Check queue
redis-cli llen notifications

# Check if Horizon is running
pgrep -f horizon

# View logs
tail -f storage/logs/laravel.log | grep ProcessNotificationJob

# View Horizon dashboard
http://your-domain/horizon
```

### **Rollback to database queues**
```php
// Change from CreateAlertRedis to CreateAlert
use Domain\Alerts\Actions\CreateAlert;
```
