Code Examples
Discover how to implement Reliable Queue in real-world scenarios.Copy, paste, and customize these production-ready examples.
Production-Ready Examples
Copy these battle-tested implementations and adapt them to your specific use cases
File Upload Queue
Reliable file uploads with retry logic, progress tracking, and concurrent processing.
1import { ReliableQueue } from '@aplanka/reliable-queue';23interface FileUploadData {4 id: string;5 fileName: string;6 fileSize: number;7 uploadUrl: string;8 metadata?: {9 userId: string;10 folder: string;11 tags?: string[];12 };13}1415// Create a file upload queue16const uploadQueue = new ReliableQueue<FileUploadData>({17 maxRetries: 3,18 retryDelay: 1000,19 exponentialBackoff: true,20 persistent: true,21 storageKey: 'file-upload-queue',22 concurrency: 2, // Upload 2 files concurrently23});2425// Set up the processor26uploadQueue.setProcessor(async (data) => {27 console.log('Uploading file:', data.fileName);2829 const formData = new FormData();30 formData.append('fileName', data.fileName);31 formData.append('fileSize', data.fileSize.toString());3233 if (data.metadata) {34 formData.append('metadata', JSON.stringify(data.metadata));35 }3637 const response = await fetch(data.uploadUrl, {38 method: 'POST',39 body: formData,40 });4142 if (!response.ok) {43 throw new Error(`Upload failed: ${response.status}`);44 }4546 console.log('File uploaded successfully:', data.fileName);47});4849// Add event handlers50uploadQueue.on('taskCompleted', (task) => {51 console.log('✅ File uploaded:', task.data.fileName);52});5354uploadQueue.on('taskFailed', (task, error) => {55 console.error('❌ Upload failed:', task.data.fileName, error.message);56});5758// Usage59export function addFileUpload(fileData: Omit<FileUploadData, 'id'>) {60 const id = `upload-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;61 return uploadQueue.add({ ...fileData, id });62}
React Data Processing
Interactive React component demonstrating queue integration with real-time updates.
1import React, { useState } from 'react';2import { useReliableQueue } from '@aplanka/reliable-queue';34interface ProcessingTask {5 id: string;6 type: 'email' | 'report' | 'export' | 'analysis';7 data: string;8 priority?: number;9}1011export function DataProcessingExample() {12 const [taskType, setTaskType] = useState<ProcessingTask['type']>('email');13 const [taskData, setTaskData] = useState('');1415 const {16 tasks,17 stats,18 addTask,19 retryTask,20 removeTask,21 clearFailed,22 retryAllTasks,23 } = useReliableQueue<ProcessingTask>({24 queueName: 'data-processing',25 maxRetries: 3,26 retryDelay: 1000,27 exponentialBackoff: true,28 persistent: true,29 concurrency: 2, // Process 2 tasks concurrently30 processor: async (data) => {31 console.log('Processing task:', data.type, data.id);3233 // Simulate different processing times34 const processingTime = {35 email: 500,36 report: 2000,37 export: 1500,38 analysis: 3000,39 }[data.type];4041 // Simulate API call that might fail42 if (Math.random() < 0.2) {43 throw new Error(`${data.type} processing failed`);44 }4546 await new Promise(resolve => setTimeout(resolve, processingTime));47 console.log(`${data.type} task completed:`, data.id);48 },49 });5051 const handleAddTask = () => {52 if (!taskData.trim()) return;5354 const taskId = `${taskType}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;5556 addTask({57 id: taskId,58 type: taskType,59 data: taskData.trim(),60 priority: taskType === 'email' ? 10 : taskType === 'report' ? 5 : 1,61 });6263 setTaskData('');64 };6566 return (67 <div style={{ padding: '20px' }}>68 <h2>Data Processing Queue</h2>6970 {/* Queue Statistics */}71 <div style={{ background: '#f5f5f5', padding: '10px', marginBottom: '20px' }}>72 <h3>Queue Statistics</h3>73 <div>74 <span>Total: {stats.total}</span>75 <span>Pending: {stats.pending}</span>76 <span>Processing: {stats.processing}</span>77 <span>Completed: {stats.completed}</span>78 <span>Failed: {stats.failed}</span>79 </div>80 </div>8182 {/* Task Input */}83 <div style={{ marginBottom: '20px' }}>84 <select85 value={taskType}86 onChange={(e) => setTaskType(e.target.value as ProcessingTask['type'])}87 >88 <option value="email">Email Processing</option>89 <option value="report">Report Generation</option>90 <option value="export">Data Export</option>91 <option value="analysis">Data Analysis</option>92 </select>9394 <input95 type="text"96 value={taskData}97 onChange={(e) => setTaskData(e.target.value)}98 placeholder="Enter task data..."99 onKeyPress={(e) => e.key === 'Enter' && handleAddTask()}100 />101102 <button onClick={handleAddTask}>103 Add {taskType} Task104 </button>105 </div>106107 {/* Task List */}108 <div>109 <h3>Processing Queue</h3>110 {tasks.length === 0 ? (111 <p>No tasks in queue</p>112 ) : (113 tasks.map((task) => (114 <div key={task.id} style={{ border: '1px solid #ddd', padding: '10px', margin: '5px' }}>115 <div>116 <strong>{task.data.data}</strong>117 <span> - {task.status}</span>118 {task.retryCount > 0 && <span> (Retries: {task.retryCount})</span>}119 </div>120121 {task.status === 'failed' && (122 <button onClick={() => retryTask(task.id)}>Retry</button>123 )}124125 {task.status !== 'processing' && (126 <button onClick={() => removeTask(task.id)}>Remove</button>127 )}128 </div>129 ))130 )}131 </div>132 </div>133 );134}
Email Queue System
Priority-based email processing with different retry strategies for different email types.
1import { ReliableQueue, QueueManager } from '@aplanka/reliable-queue';23interface EmailTask {4 to: string;5 subject: string;6 body: string;7 priority: 'low' | 'normal' | 'high' | 'urgent';8 templateId?: string;9 attachments?: string[];10}1112// Create specialized email queue13const emailQueue = new ReliableQueue<EmailTask>({14 maxRetries: 5, // Important emails should retry more15 retryDelay: 2000,16 exponentialBackoff: true,17 maxRetryDelay: 60000, // Max 1 minute delay18 concurrency: 3, // Send 3 emails concurrently19 persistent: true,20});2122emailQueue.setProcessor(async (emailData) => {23 console.log(`Sending email to ${emailData.to}`);2425 // Simulate email API call26 const response = await fetch('/api/send-email', {27 method: 'POST',28 headers: { 'Content-Type': 'application/json' },29 body: JSON.stringify(emailData),30 });3132 if (!response.ok) {33 const error = await response.text();34 throw new Error(`Email send failed: ${error}`);35 }3637 return response.json();38});3940// Add priority-based processing41emailQueue.on('taskCompleted', (task) => {42 console.log(`✅ Email sent to ${task.data.to}`);43 // Log to analytics, update user notification status, etc.44});4546// Usage examples47export function sendWelcomeEmail(userEmail: string, userName: string) {48 return emailQueue.add({49 to: userEmail,50 subject: 'Welcome to our platform!',51 body: `Hello ${userName}, welcome to our platform!`,52 priority: 'high',53 templateId: 'welcome-email',54 }, { priority: 10 }); // High priority55}5657export function sendPasswordReset(userEmail: string, resetToken: string) {58 return emailQueue.add({59 to: userEmail,60 subject: 'Password Reset Request',61 body: `Click here to reset: /reset?token=${resetToken}`,62 priority: 'urgent',63 templateId: 'password-reset',64 }, { priority: 100 }); // Highest priority65}6667export function sendNewsletter(subscribers: string[], content: string) {68 subscribers.forEach(email => {69 emailQueue.add({70 to: email,71 subject: 'Weekly Newsletter',72 body: content,73 priority: 'low',74 templateId: 'newsletter',75 }, { priority: 1 }); // Low priority76 });77}
Batch Processing
Process large batches of items with progress tracking and individual error handling.
1import { ReliableQueue } from '@aplanka/reliable-queue';23interface BatchJob {4 id: string;5 type: 'image-resize' | 'data-export' | 'report-generation';6 batchSize: number;7 items: any[];8 progress?: {9 processed: number;10 total: number;11 currentItem?: string;12 };13}1415const batchQueue = new ReliableQueue<BatchJob>({16 maxRetries: 2,17 retryDelay: 5000,18 exponentialBackoff: true,19 concurrency: 1, // Process batches one at a time20 persistent: true,21});2223batchQueue.setProcessor(async (job) => {24 console.log(`Starting batch job: ${job.type}`);2526 const results = [];2728 for (let i = 0; i < job.items.length; i++) {29 const item = job.items[i];3031 try {32 // Update progress (this would typically be saved to database)33 const progress = {34 processed: i,35 total: job.items.length,36 currentItem: item.id || item.name || `Item ${i + 1}`,37 };3839 console.log(`Processing ${progress.currentItem} (${progress.processed + 1}/${progress.total})`);4041 // Process individual item based on job type42 let result;43 switch (job.type) {44 case 'image-resize':45 result = await resizeImage(item);46 break;47 case 'data-export':48 result = await exportData(item);49 break;50 case 'report-generation':51 result = await generateReport(item);52 break;53 default:54 throw new Error(`Unknown job type: ${job.type}`);55 }5657 results.push({ item: item.id, result, status: 'success' });5859 } catch (error) {60 console.error(`Failed to process item ${item.id}:`, error);61 results.push({ item: item.id, error: error.message, status: 'failed' });62 }63 }6465 console.log(`Batch job completed: ${job.type}`);66 return {67 jobId: job.id,68 results,69 summary: {70 total: results.length,71 successful: results.filter(r => r.status === 'success').length,72 failed: results.filter(r => r.status === 'failed').length,73 }74 };75});7677// Helper functions (implement based on your needs)78async function resizeImage(image: any) {79 // Simulate image processing80 await new Promise(resolve => setTimeout(resolve, 1000));81 return { url: `/resized/${image.id}.jpg`, width: 800, height: 600 };82}8384async function exportData(data: any) {85 // Simulate data export86 await new Promise(resolve => setTimeout(resolve, 500));87 return { file: `/exports/${data.id}.csv`, size: 1024 };88}8990async function generateReport(reportConfig: any) {91 // Simulate report generation92 await new Promise(resolve => setTimeout(resolve, 2000));93 return { file: `/reports/${reportConfig.id}.pdf`, pages: 10 };94}9596// Usage97export function processBatchImages(images: any[]) {98 return batchQueue.add({99 id: `batch-${Date.now()}`,100 type: 'image-resize',101 batchSize: images.length,102 items: images,103 });104}
Start Building with Reliable Queue
Experience the power of reliable task processing with our interactive demo, or dive deep into the comprehensive documentation.
TypeScript Ready
Full type safety and IntelliSense support
Persistent Storage
Built-in persistence for reliability
Production Ready
Battle-tested in real applications