import { QueueService } from './queues/queue.service';
@Injectable()
export class MyService {
constructor(private readonly queueService: QueueService) {}
async doSomethingAsync() {
// Send email asynchronously
await this.queueService.addJob('send-email', {
to: 'user@example.com',
subject: 'Welcome!',
template: 'welcome',
variables: { name: 'John' },
});
// Return immediately - processing happens in background
return { status: 'processing', message: 'Email queued for sending' };
}
}import { WorkerHealthCheckService } from './workers/health/worker-health-check.service';
@Get('/health/workers')
async getWorkersHealth() {
const health = await this.healthCheckService.performComprehensiveHealthCheck();
return {
totalWorkers: health.totalWorkers,
healthyWorkers: health.healthyWorkers,
successRate: `${health.poolStats.successRate.toFixed(2)}%`,
alerts: health.alerts
};
}| Job Name | Worker | Purpose |
|---|---|---|
send-email |
EmailWorker | Send emails |
process-image |
MediaProcessingWorker | Optimize images |
process-video |
MediaProcessingWorker | Transcode videos |
process-audio |
MediaProcessingWorker | Process audio |
consistency-check |
DataSyncWorker | Check data consistency |
replicate-data |
DataSyncWorker | Replicate data |
reconcile |
DataSyncWorker | Reconcile data |
backup-data |
BackupProcessingWorker | Full database backup |
call-webhook |
WebhooksWorker | Deliver webhook |
subscription-create |
SubscriptionsWorker | Create subscription |
subscription-renew |
SubscriptionsWorker | Renew subscription |
// Add job and don't wait for result
await this.queueService.addJob('send-email', emailData);// Add job and track progress
const job = await this.queueService.addJob('process-image', imageData);
const jobId = job.id;
// Later, check status
const status = await this.queueService.getJob(jobId);
const progress = await status.progress();// High priority job
await this.queueService.addJob('send-email', emailData, { priority: JobPriority.HIGH });
// Low priority job
await this.queueService.addJob('backup-data', backupData, { priority: JobPriority.LOW });// Schedule for specific time
const scheduledTime = new Date(Date.now() + 60 * 60 * 1000); // 1 hour from now
await this.jobSchedulerService.scheduleJob('send-email', emailData, scheduledTime);// Add multiple jobs at once
await this.queueService.addBulkJobs([
{ name: 'send-email', data: emailData1 },
{ name: 'send-email', data: emailData2 },
{ name: 'send-email', data: emailData3 },
]);const isHealthy = await this.healthCheckService.isPoolHealthy();
if (!isHealthy) {
// Scale up workers or alert
}const healthPercentage = await this.healthCheckService.getPoolHealthPercentage();
console.log(`Pool health: ${healthPercentage}%`);const anomalies = await this.healthCheckService.detectAnomalies();
anomalies.forEach((anomaly) => {
console.log(`${anomaly.workerId}: ${anomaly.message}`);
});@Cron('0 * * * * *') // Every minute
async autoScaleWorkers() {
const health = await this.healthCheckService.performComprehensiveHealthCheck();
for (const workerType of ['email', 'media-processing', 'webhooks']) {
const workers = this.workerOrchestration.getWorkersByType(workerType);
const stats = this.workerOrchestration.getPoolStatistics();
// Scale up if many jobs in queue
if (stats.totalJobsProcessed > 1000) {
await this.workerOrchestration.scaleWorkerPool(workerType, workers.length + 1);
}
// Scale down if low activity
if (stats.totalJobsProcessed < 100 && workers.length > 1) {
await this.workerOrchestration.scaleWorkerPool(workerType, workers.length - 1);
}
}
}Solution: Check worker health
const health = await this.healthCheckService.performComprehensiveHealthCheck();
console.log(health); // Check for alertsSolution: Check individual worker metrics
const metrics = this.workerOrchestration.getAllWorkerMetrics();
const highMemory = metrics.filter((m) => m.memoryUsage > 500);
console.log(`Workers with high memory:`, highMemory);Solution: Check anomalies
const anomalies = await this.healthCheckService.detectAnomalies();
const failures = anomalies.filter((a) => a.type === 'high-failure-rate');
console.log(`Workers with high failure rate:`, failures);Solution: Check execution times
const metrics = this.workerOrchestration.getAllWorkerMetrics();
const slow = metrics.filter((m) => m.averageExecutionTime > 5000);
console.log(`Slow workers:`, slow);addJob(name, data, options?)- Add single jobaddBulkJobs(jobs)- Add multiple jobsgetJob(jobId)- Get job status
routeJob(job)- Route job to workergetActiveWorkers()- Get all active workersgetWorkersByType(type)- Get workers by typegetAllWorkerMetrics()- Get all metricsgetPoolStatistics()- Get pool statsscaleWorkerPool(type, count)- Scale workers
performComprehensiveHealthCheck()- Full health checkgetWorkerHealth(workerId)- Worker healthgetAllWorkersHealth()- All health statusesisPoolHealthy()- Boolean health statusgetPoolHealthPercentage()- Health as percentagedetectAnomalies()- Find anomalies
- ✅ Use descriptive job names
- ✅ Monitor worker health regularly
- ✅ Set appropriate timeouts for job types
- ✅ Use bulk operations for many similar jobs
- ✅ Scale workers based on metrics
- ✅ Implement auto-scaling for production
- ✅ Use priority for critical jobs
- ✅ Clean up old completed jobs periodically
- Email: Use bulk operations for newsletters
- Media: Process videos during off-peak hours
- Backups: Schedule during low-traffic periods
- Webhooks: Use highest concurrency for delivery
- Subscriptions: Batch billing operations