Background Jobs & Queue Processing Guide
Last Updated: 2026-01-10 Status: Enhanced Plan Reference: 018-background-jobs-queue-processing.md, 053-background-jobs-enhancement.md
Overview
The Background Jobs system handles asynchronous task processing using Laravel's queue system. It enables efficient handling of time-consuming operations like email sending, PDF generation, file processing, and scheduled tasks without blocking user requests. The enhanced monitoring dashboard provides real-time visibility into queue health, job metrics, and failed job management.
Table of Contents
- Queue Configuration
- Job Types
- How to Use
- Queue Monitoring Dashboard
- Job Metrics & Analytics
- Failed Job Management
- Priority & Throttling
- Technical Architecture
- Related Features
Queue Configuration
Queue Drivers
| Driver | Use Case | Configuration |
|---|---|---|
database | Default, reliable | Uses jobs table |
redis | High performance | Requires Redis |
sync | Development/testing | Runs immediately |
sqs | AWS production | Amazon SQS |
Environment Setup
QUEUE_CONNECTION=database
# For Redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
# For SQS
SQS_KEY=your-key
SQS_SECRET=your-secret
SQS_QUEUE=your-queue
SQS_REGION=us-east-1
# Monitored Queues (comma-separated)
QUEUE_MONITORED_QUEUES=default,high,low,emails
Queue Names
| Queue | Purpose | Priority |
|---|---|---|
default | General jobs | Normal |
high | Critical jobs | High |
low | Background tasks | Low |
emails | Email sending | Normal |
notifications | Push notifications | Normal |
Job Types
Email Jobs
| Job | Purpose |
|---|---|
SendInvoiceEmail | Send invoice to client |
SendNotificationEmail | General notifications |
SendWelcomeEmail | New user welcome |
SendReminderEmail | Payment reminders |
Processing Jobs
| Job | Purpose |
|---|---|
GeneratePdf | Create PDF documents |
ProcessFileUpload | Virus scan, thumbnails |
GenerateReport | Create reports |
ExportData | Large data exports |
Scheduled Jobs
| Job | Schedule |
|---|---|
SendOverdueReminders | Daily |
CleanupTempFiles | Daily |
GenerateAnalytics | Hourly |
EnforceRetention | Daily |
Notification Jobs
| Job | Purpose |
|---|---|
BroadcastNotification | Real-time push |
SendWebhook | Webhook delivery |
QueueNotification | Batch notifications |
How to Use
Dispatching Jobs
Immediate Dispatch:
SendInvoiceEmail::dispatch($invoice);
Delayed Dispatch:
SendReminderEmail::dispatch($invoice)->delay(now()->addHours(24));
Specific Queue:
GenerateReport::dispatch($params)->onQueue('low');
Chained Jobs:
Bus::chain([
new ProcessUpload($file),
new GenerateThumbnail($file),
new NotifyUser($user),
])->dispatch();
Using Job Metrics Middleware
Add the TrackJobMetrics middleware to jobs for automatic metrics collection:
use App\Jobs\Middleware\TrackJobMetrics;
class ProcessData implements ShouldQueue
{
public function middleware(): array
{
return [new TrackJobMetrics()];
}
public function handle(): void
{
// Job logic
}
}
Running Queue Workers
Development:
php artisan queue:work
Production (with options):
php artisan queue:work --queue=high,default,low --sleep=3 --tries=3
Process specific queue:
php artisan queue:work --queue=emails
Supervisor Configuration
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/path/to/worker.log
stopwaitsecs=3600
Queue Monitoring Dashboard
Navigate to Admin → Queues to access the comprehensive monitoring dashboard.
Dashboard Features
| Feature | Description |
|---|---|
| Summary Metrics | Total jobs today, throughput, success rate, failed count |
| Worker Status | Active workers, memory usage, uptime |
| Queue List | All queues with pending count, processing, throughput, health status |
| Recent Activity | Last 20 job executions with status and duration |
| Recent Failures | Quick view of failed jobs with error snippets |
Queue Health Status
| Status | Condition |
|---|---|
healthy | Low queue size, low fail rate |
busy | Queue size > 100 |
warning | Queue size > 1000 |
critical | Fail rate > 10% |
Real-Time Updates
The dashboard automatically refreshes every 30 seconds via AJAX polling. Access real-time metrics at:
GET /admin/queues/realtime
Job Metrics & Analytics
Analytics Dashboard
Navigate to Admin → Queues → Analytics for detailed job analytics.
Available Periods
| Period | Description |
|---|---|
1h | Last hour |
24h | Last 24 hours (default) |
7d | Last 7 days |
30d | Last 30 days |
Analytics Charts
| Chart | Description |
|---|---|
| Jobs Over Time | Completed vs failed jobs hourly |
| Success Rate | Doughnut chart of completion vs failure |
| Jobs by Queue | Bar chart of job distribution |
| Duration by Job Type | Horizontal bar chart of avg duration |
Job Type Performance Table
View detailed performance metrics per job type:
- Total count
- Average duration (ms)
- Average memory (MB)
- Fail rate (%)
Accessing Metrics Programmatically
use App\Services\Queue\QueueMetricsService;
$metrics = app(QueueMetricsService::class);
// Get summary for dashboard
$summary = $metrics->getSummary();
// Get analytics for a period
$analytics = $metrics->getJobAnalytics('24h');
// Get queue-specific metrics
$queueMetrics = $metrics->getQueueMetrics('high');
// Get hourly throughput
$throughput = $metrics->getThroughput('default');
Failed Job Management
Navigate to Admin → Queues → Failed Jobs for comprehensive failed job management.
Failed Jobs Dashboard
| Feature | Description |
|---|---|
| Statistics | Total failed, today, this week |
| Top Errors | Most common error messages |
| Filtering | By queue, search by payload/exception |
| Bulk Actions | Retry selected, delete selected |
Individual Job Details
View detailed information for each failed job:
- Job UUID, queue, connection
- Failure timestamp
- Full exception with stack trace
- Job payload (JSON formatted)
- Related failures for same job type
Actions
| Action | Description |
|---|---|
| Retry | Queue job for retry |
| Retry All | Retry all failed jobs |
| Delete | Remove single failed job |
| Delete Selected | Remove multiple selected jobs |
| Flush All | Delete all failed jobs |
Artisan Commands
# View failed jobs
php artisan queue:failed
# Retry specific job
php artisan queue:retry {uuid}
# Retry all failed
php artisan queue:retry all
# Clear all failed
php artisan queue:flush
Priority & Throttling
Navigate to Admin → Queues → Priorities for queue and throttle configuration.
Queue Priority
- Drag-and-drop to reorder queue priority
- Higher priority queues are processed first
- Configure workers per queue
- Pause/resume individual queues
Rate Limiting
Configure rate limits for specific job classes:
| Setting | Description |
|---|---|
| Max Per Minute | Maximum jobs per minute |
| Max Concurrent | Maximum simultaneous executions |
Programmatic Configuration
use App\Models\QueueConfig;
use App\Models\JobThrottle;
// Set queue priority and workers
$config = QueueConfig::forQueue('high');
$config->update([
'priority' => 10,
'workers' => 3,
'is_paused' => false,
]);
// Add job throttle
JobThrottle::create([
'job_class' => 'App\Jobs\SendEmail',
'per_minute' => 60,
'concurrent' => 5,
]);
Technical Architecture
Service Classes
| Service | Purpose |
|---|---|
QueueMonitorService | Queue status, worker info, recent jobs |
QueueMetricsService | Job metrics recording, analytics |
Models
| Model | Description |
|---|---|
JobMetric | Individual job execution metrics |
QueueConfig | Queue priority and worker settings |
JobThrottle | Rate limit configurations |
Database Schema
Table: job_metrics
| Column | Type | Description |
|---|---|---|
id | bigint | Primary key |
job_id | uuid | Unique job identifier |
queue | string | Queue name |
job_class | string | Fully qualified class name |
status | string | queued/processing/completed/failed |
queued_at | timestamp | When job was queued |
started_at | timestamp | When processing started |
completed_at | timestamp | When job completed |
duration_ms | float | Execution duration |
memory_mb | float | Memory usage |
exception | text | Error message if failed |
Table: queue_configs
| Column | Type | Description |
|---|---|---|
id | bigint | Primary key |
name | string | Queue name |
priority | integer | Processing priority |
workers | integer | Worker count |
is_paused | boolean | Queue paused status |
settings | json | Additional settings |
Table: job_throttles
| Column | Type | Description |
|---|---|---|
id | bigint | Primary key |
job_class | string | Job class name |
per_minute | integer | Max per minute |
concurrent | integer | Max concurrent |
is_active | boolean | Throttle active |
Routes
| Route | Description |
|---|---|
GET /admin/queues | Dashboard |
GET /admin/queues/analytics | Analytics view |
GET /admin/queues/priorities | Priority config |
GET /admin/queues/{queue} | Queue details |
POST /admin/queues/{queue}/toggle-pause | Pause/resume queue |
GET /admin/failed-jobs | Failed jobs list |
GET /admin/failed-jobs/{uuid} | Failed job details |
POST /admin/failed-jobs/{uuid}/retry | Retry failed job |
Middleware
The TrackJobMetrics middleware automatically records:
- Job start time and class
- Completion status and duration
- Memory usage
- Exception messages for failures
Best Practices
For Reliability
- Set appropriate timeouts for job execution
- Use unique job IDs to prevent duplicates
- Implement idempotency for retryable jobs
- Log job progress for debugging
- Handle failures gracefully
- Use metrics middleware for visibility
For Performance
- Use appropriate queues for job priority
- Batch similar operations together
- Avoid serializing large objects
- Set reasonable retry limits
- Monitor queue depth and scale workers
- Configure throttles for rate-limited APIs
For Monitoring
- Check dashboard daily for queue health
- Set up alerts for high failure rates
- Review analytics for performance trends
- Address failed jobs promptly
- Tune throttles based on external API limits
Troubleshooting
| Issue | Solution |
|---|---|
| Jobs not processing | Check queue worker is running |
| Jobs failing silently | Check failed_jobs table |
| Memory issues | Restart workers with --max-jobs |
| Timeout errors | Increase $timeout property |
| Duplicate jobs | Implement ShouldBeUnique |
| High fail rate | Check exception patterns in analytics |
| Queue backlog | Increase worker count in config |
Debug Mode
# Run single job for debugging
php artisan queue:work --once
# View job payload
php artisan queue:failed --json
Related Features
Dependencies
| Feature | Relationship |
|---|---|
| Notifications | Email queuing |
| Webhooks | Webhook delivery |
| Reports | Report generation |
Complementary Features
| Feature | Description |
|---|---|
| Admin Tools | Queue management |
| Activity Logging | Job logging |
| Performance Caching | Cache warming |
See Also
- Notifications - Email sending
- Admin Tools - Queue management
- Performance Caching - Caching