Workers Pattern Consolidation - Complete Reference
Overview
This document describes the pattern consolidation refactorings applied to the hoox-setup workers monorepo. These changes eliminate code duplication and establish standardized patterns for common worker patterns including queue handling, cron scheduling, and exchange client implementations. Status: ✅ Production-ReadyLast Updated: June 4, 2026
Version: 1.0
What Changed
1. Queue Handler Factory ✅
Location:packages/shared/src/queue-handler.ts
What: A reusable factory for handling CloudFlare Queues with retry logic and exponential backoff.
Before: Each queue-based worker had inline retry/backoff logic (60+ lines per worker)
After: Single factory used across all workers (30 lines per worker)
Code Reduction:
trade-worker: 61 lines → 30 lines (51% reduction)- Consistent retry behavior across all queue-based workers
- ✅ Generic message type support (
<T>) - ✅ Exponential backoff with configurable delays
- ✅ Automatic retry logic with attempt tracking
- ✅ Dead-letter queue (DLQ) handling
- ✅ Built-in logging with optional logger
- ✅ Type-safe with TypeScript
- ✅ Reduced code duplication (51% reduction in trade-worker)
- ✅ Consistent retry behavior across workers
- ✅ Type-safe with generic message types
- ✅ Built-in logging with
loggeroption - ✅ Easier to test and maintain
workers/trade-worker- Uses factory for queue message handling
2. Cron Handler ✅
Location:packages/shared/src/cron-handler.ts
What: Standardized handler for scheduled/cron-triggered workers with consistent logging and error handling.
Before: Custom logging in each scheduled worker, inconsistent patterns
After: Standardized logging with automatic duration measurement
Usage Example:
- ✅ Automatic execution time measurement
- ✅ Structured logging with event details
- ✅ Consistent error handling and logging
- ✅ Generic environment type support (
<Env>) - ✅ Optional logger instance
- ✅ Consistent logging across all scheduled workers
- ✅ Automatic duration measurement
- ✅ Structured error logging with context
- ✅ Cleaner handler code
- ✅ Easier debugging with standardized logs
workers/agent-worker- Uses factory for 5-minute cron routineworkers/report-worker- Uses factory for report generation cron
3. Exchange Client Base Class ✅
Location:packages/shared/src/exchanges/
What: Abstract base class for exchange implementations (Binance, Bybit, MEXC) with common functionality.
Files:
base-exchange-client.ts- Abstract class with 6 abstract methodstypes.ts- TypeScript types for exchangesindex.ts- Barrel exports
validateApiCredentials(): Promise<boolean>- Verify API credentials are validexecuteTrade(params: TradeParams): Promise<OrderResponse>- Execute a tradegetMarkPrice(symbol: string): Promise<number>- Get current mark pricegetOpenPositions(symbol?: string): Promise<Position[]>- Get open positionsclosePosition(symbol: string, positionId?: string): Promise<OrderResponse>- Close a positiongetWalletBalance(): Promise<number>- Get wallet balance
makeRequest(method: string, path: string, data?: any): Promise<any>- Make HTTP request (subclass implements)getErrorMessagePrefix(): string- Get error message prefix for logging
- ✅ Type-safe configuration and responses
- ✅ Consistent interface across exchanges
- ✅ Helper methods for common operations
- ✅ Crypto signature support (HMAC-SHA256)
- ✅ Testnet/sandbox support
- ✅ Consistent interface for all exchange implementations
- ✅ Type-safe configuration and responses
- ✅ Reusable across multiple workers
- ✅ Helper methods for URL building, signing, etc.
- ✅ Easier to add new exchanges
workers/trade-worker- Exchange clients (Binance, Bybit, MEXC) extend shared base class
Migration Guide
For New Workers with Queues
If you’re building a new worker that needs queue handling:- Define your message type as a TypeScript interface
- Set
maxRetriesandbackoffDelaysas constants - Implement
onMessagewith your processing logic - Implement
onDLQfor dead-letter handling - The factory handles all retry logic and logging
For New Scheduled Workers
If you’re building a new worker with scheduled/cron triggers:- Define your
Envtype with all bindings - Set
nameto your worker name for logging - Implement
handlerwith your cron logic - The factory handles logging and duration measurement
- Errors are logged with context and re-thrown
For New Exchange Clients
If you’re adding a new exchange:- Extend
BaseExchangeClientwith your exchange name - Implement all 6 abstract methods
- Implement
makeRequestwith your exchange-specific logic - Use the base class constructor to initialize credentials
- Return typed responses for type safety
Testing
All refactored patterns are fully tested:Test Files
packages/shared/src/__tests__/queue-handler.test.ts- 5 test casespackages/shared/src/__tests__/cron-handler.test.ts- 5 test casespackages/shared/src/__tests__/exchanges.test.ts- 3 test cases
Running Tests
Test Coverage
All patterns have comprehensive test coverage:Files Modified
Created Files
packages/shared/src/queue-handler.ts- Queue handler factory (92 lines)packages/shared/src/cron-handler.ts- Cron handler factory (77 lines)packages/shared/src/exchanges/base-exchange-client.ts- Base class (209 lines)packages/shared/src/exchanges/types.ts- Exchange types (20 lines)packages/shared/src/exchanges/index.ts- Barrel exportspackages/shared/src/__tests__/queue-handler.test.ts- Queue testspackages/shared/src/__tests__/cron-handler.test.ts- Cron testspackages/shared/src/__tests__/exchanges.test.ts- Exchange tests
Modified Files
packages/shared/src/index.ts- Added exports for new utilitiesworkers/trade-worker/src/index.ts- Updated to usecreateQueueHandlerworkers/agent-worker/src/index.ts- Updated to usecreateCronHandlerworkers/report-worker/src/index.ts- Updated to usecreateCronHandlerworkers/trade-worker/src/mexc-client.ts- Updated importsworkers/trade-worker/src/binance-client.ts- Updated importsworkers/trade-worker/src/bybit-client.ts- Updated imports
Impact Summary
Best Practices Going Forward
1. Use createQueueHandler for all queue-based workers
- No manual retry/backoff logic
- Consistent error handling and logging
- Type-safe with generic message types
2. Use createCronHandler for all scheduled workers
- Standardized logging format
- Automatic duration measurement
- Consistent error handling
3. Extend BaseExchangeClient for new exchanges
- Type-safe configuration
- Consistent interface across exchanges
- Reusable helper methods
4. Keep helper/utility functions organized
- Factories in
packages/shared/src/for framework concerns (queues, cron) - Helpers in
logic/directories for domain logic (trade execution, notifications) - Types in
types.tsorexchanges/types.tsfor shared types
5. Test all patterns before committing
- All pattern tests are in
packages/shared/__tests__/ - Worker tests cover integration
- Run
bun testbefore committing
Troubleshooting
Queue Handler Issues
Problem: Messages not being retried- Check
maxRetriesis greater than 0 - Verify
backoffDelaysarray has enough entries - Ensure
onMessagethrows error on failure
- Verify
onDLQis implemented - Check that
maxRetriesis being exceeded - Ensure message attempts counter is working
Cron Handler Issues
Problem: Logs not appearing- Verify
loggeris passed to handler - Check logger implementation has
infoanderrormethods - Ensure logger is properly initialized
- Duration is always measured automatically
- Check logger output for
durationMsfield - Verify handler is actually being called
Exchange Client Issues
Problem: API credentials validation failing- Verify
apiKeyandapiSecretare correct - Check exchange API endpoint is accessible
- Ensure
makeRequestis properly implemented
- Verify
TradeParamsare correct for exchange - Check exchange API documentation for parameter names
- Ensure proper error handling in
executeTrade
Related Documentation
Changelog
Version 1.0 (June 4, 2026)
- ✅ Queue handler factory implemented
- ✅ Cron handler factory implemented
- ✅ Exchange client base class extracted
- ✅ All workers refactored to use new patterns
- ✅ Comprehensive test coverage added
- ✅ Documentation completed
Status: Production-Ready
Last Updated: June 4, 2026
Maintainer: Hoox Development Team