The TalentTrust backend implements a robust, durable queue-based background job system using BullMQ and Redis. This system offloads heavy asynchronous tasks from the main request-response cycle, improving API responsiveness and reliability.
- QueueManager: Central singleton managing all queues and workers
- Job Processors: Specialized handlers for each job type
- Queue Configuration: Environment-based Redis connection settings
- Job Types: Type-safe job definitions with validation
The system supports four primary job types:
- EMAIL_NOTIFICATION: Asynchronous email sending
- CONTRACT_PROCESSING: Heavy contract operations (create, update, finalize)
- REPUTATION_UPDATE: User reputation score calculations
- BLOCKCHAIN_SYNC: Blockchain data synchronization
Use the REST API to enqueue background jobs:
POST /api/v1/jobs
Content-Type: application/json
{
"type": "email-notification",
"payload": {
"to": "user@example.com",
"subject": "Welcome to TalentTrust",
"body": "Thank you for joining!"
},
"options": {
"priority": 1,
"delay": 0
}
}Response:
{
"jobId": "1234567890",
"type": "email-notification",
"status": "queued"
}GET /api/v1/jobs/{type}/{jobId}Response:
{
"id": "1234567890",
"name": "email-notification",
"state": "completed",
"data": { ... },
"returnvalue": { ... }
}GET /api/v1/jobs/dlq?type=email-notification&limit=50&offset=0
Authorization: Bearer demo-admin-tokenReturns failed jobs with metadata required for safe operations:
- failed reason
- attempts made
- original payload
- deterministic replay dedupe key (
replay:<jobType>:<originalJobId>)
POST /api/v1/jobs/dlq/reprocess
Authorization: Bearer demo-admin-token
Content-Type: application/json
{
"type": "email-notification",
"jobId": "123",
"reason": "Retry after provider outage resolved"
}Replay behavior:
- Reprocess only succeeds for jobs currently in
failedstate - Replays are idempotent via deterministic replay IDs
- Repeating the same replay request does not enqueue duplicates
- All view/reprocess operations are recorded in immutable audit log entries
import { QueueManager, JobType } from './queue';
const queueManager = QueueManager.getInstance();
// Initialize queues
await queueManager.initializeQueue(JobType.EMAIL_NOTIFICATION);
// Add a job
const jobId = await queueManager.addJob(
JobType.EMAIL_NOTIFICATION,
{
to: 'user@example.com',
subject: 'Hello',
body: 'World',
}
);
// Check status
const status = await queueManager.getJobStatus(JobType.EMAIL_NOTIFICATION, jobId);Configure Redis connection using environment variables:
REDIS_HOST=localhost # Default: localhost
REDIS_PORT=6379 # Default: 6379
REDIS_PASSWORD=secret # OptionalDefault job configuration (in src/queue/config.ts):
- Attempts: 3 retries on failure
- Backoff: Exponential backoff starting at 2 seconds
- Cleanup: Keep last 100 completed jobs, 1000 failed jobs
Handles email sending with validation:
- Validates email format
- Requires subject and body
- Returns email ID for tracking
Processes contract operations:
- create: Initialize new contract on blockchain
- update: Update contract metadata
- finalize: Complete contract and trigger payment
Calculates and updates user reputation:
- Validates rating range (1-5)
- Aggregates historical ratings
- Updates user profile
Synchronizes blockchain data:
- Supports Stellar and Soroban networks
- Processes blocks in batches
- Tracks sync progress
- DLQ viewer and reprocessor endpoints are admin-only
- Every access is authenticated and role-checked
- Replay requests require an explicit operator reason for accountability
- Both viewing and replay operations emit
ADMIN_ACTIONaudit records - Replay dedupe prevents accidental duplicate re-execution
All processors implement strict input validation:
- Email format validation
- Contract ID format checks
- Rating range validation
- Network type whitelisting
- Jobs retry up to 3 times with exponential backoff
- Failed jobs are logged with detailed error messages
- Graceful degradation on processor failures
- Support for password authentication
- Connection pooling with limits
- Secure environment variable configuration
- Malicious Job Payloads: Mitigated by strict validation in processors
- Queue Flooding: Rate limiting should be implemented at API level
- Redis Unauthorized Access: Use strong passwords and network isolation
- Job Data Exposure: Sensitive data should be encrypted before enqueueing
- Each worker processes up to 5 jobs concurrently
- Configurable per job type based on resource requirements
- Horizontal scaling: Multiple worker instances can process the same queue
- Redis cluster support for high availability
- Job prioritization for critical operations
Event listeners track:
- Job completion and failures
- Queue waiting times
- Active job counts
The queue system is tested using a hybrid approach of unit tests and integration tests.
For detailed information on how Redis is mocked and how to run integration tests, see the Redis Testing Guide.
- Unit tests for all processors
- Integration tests for API endpoints
- Configuration validation tests
- Error handling scenarios
- Edge cases and failure paths
Target: 95%+ test coverage
- Redis 6.0+ running and accessible
- Node.js 18+
- Environment variables configured
- Configure Redis with authentication
- Set appropriate environment variables
- Monitor queue metrics (length, processing time)
- Set up alerts for failed jobs
- Implement job result persistence if needed
- Configure log aggregation
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
command: redis-server --requirepass ${REDIS_PASSWORD}
backend:
build: .
environment:
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_PASSWORD: ${REDIS_PASSWORD}
depends_on:
- redis- Check Redis connection:
redis-cli ping - Verify environment variables are set
- Check worker logs for errors
- Review job payload validation
- Check processor error logs
- Verify external service availability (email, blockchain)
- Reduce
removeOnCompleteandremoveOnFailvalues - Implement job result cleanup
- Monitor Redis memory usage
- Job scheduling (cron-like patterns)
- Job dependencies and workflows
- Dead letter queue for permanently failed jobs
- Real-time job progress updates via WebSocket
- Admin dashboard for queue monitoring
- Rate limiting per job type