A robust TypeScript email sending service with retry logic, circuit breakers, fallback mechanisms, and comprehensive monitoring dashboard.
- Retry Logic: Exponential backoff with configurable retry attempts
- Fallback Mechanism: Automatic provider switching on failure
- Idempotency: Prevents duplicate email sends using idempotency keys
- Rate Limiting: Token bucket implementation (100 emails/minute)
- Circuit Breaker: Prevents cascading failures with CLOSED/OPEN/HALF-OPEN states
- Queue System: Priority-based email processing with scheduling
- MockProvider A: Primary provider (125ms latency, 0.8% failure rate)
- MockProvider B: Fallback provider (89ms latency, 2.2% failure rate)
- Health Monitoring: Continuous provider health checks
- Real-time Stats: Emails sent, success rate, queue size, rate limit usage
- Provider Monitoring: Live status, latency, and success rates
- Email History: Recent email delivery tracking with status
- System Logs: Real-time log streaming with filtering
- Send Email Form: Interactive form with validation
server/
βββ services/
β βββ EmailService.ts # Main email orchestrator
β βββ CircuitBreaker.ts # Circuit breaker implementation
β βββ RateLimiter.ts # Rate limiting with sliding window
β βββ EmailQueue.ts # Priority queue management
β βββ MockEmailProviders.ts # Simulated email providers
βββ routes.ts # REST API endpoints
βββ storage.ts # In-memory data storage
βββ index.ts # Express server setup
client/src/
βββ components/
β βββ StatsGrid.tsx # Dashboard metrics display
β βββ SendEmailForm.tsx # Email sending form
β βββ ProviderStatus.tsx # Provider health monitoring
β βββ EmailHistory.tsx # Email delivery history
β βββ SystemLogs.tsx # Real-time system logs
β βββ Sidebar.tsx # Navigation sidebar
βββ pages/
β βββ Dashboard.tsx # Main dashboard page
βββ lib/
βββ queryClient.ts # React Query configuration
shared/
βββ schema.ts # Drizzle ORM schemas and types
- Node.js 20+
- npm or yarn
-
Clone the repository
git clone <repository-url> cd email-service
-
Install dependencies
npm install
-
Start development server
npm run dev
-
Access the application
- Dashboard: http://localhost:5000
- API: http://localhost:5000/api
POST /api/emails/send- Send email with retry logicGET /api/emails/recent- Get recent email historyGET /api/emails/:id- Get specific email details
GET /api/dashboard/stats- Dashboard statisticsGET /api/providers/status- Provider health statusGET /api/circuit-breaker/status- Circuit breaker stateGET /api/logs/recent- Recent system logs
Send Email:
curl -X POST http://localhost:5000/api/emails/send \
-H "Content-Type: application/json" \
-H "Idempotency-Key: unique-key-123" \
-d '{
"recipient": "user@example.com",
"subject": "Test Email",
"message": "Hello from the email service!",
"priority": "normal"
}'Get Dashboard Stats:
curl http://localhost:5000/api/dashboard/stats- CLOSED: Normal operation, all requests pass through
- OPEN: Failure threshold exceeded, requests fail fast
- HALF-OPEN: Testing recovery, limited requests allowed
- Exponential backoff: 1s, 2s, 4s, 8s (max 30s)
- Maximum 3 retry attempts per email
- Provider failover on consecutive failures
- Priority-based processing (high > normal > low)
- Scheduled retry with exponential delay
- Real-time processing every 1 second
- Emails Sent Today: Total daily email count
- Success Rate: Percentage of successful deliveries
- Queue Size: Pending emails in queue
- Rate Limit Usage: Current API usage percentage
- Status: Healthy/Degraded/Circuit Open
- Latency: Average response time
- Success Rate: Provider-specific success percentage
- Use the dashboard form to send test emails
- Monitor real-time stats and provider status
- Check system logs for detailed operation tracking
- Test idempotency by sending duplicate requests
# Send multiple emails to test rate limiting
for i in {1..10}; do
curl -X POST http://localhost:5000/api/emails/send \
-H "Content-Type: application/json" \
-d '{
"recipient": "test'$i'@example.com",
"subject": "Load Test '$i'",
"message": "Testing load handling",
"priority": "normal"
}'
doneNODE_ENV: Environment (development/production)PORT: Server port (default: 5000)
- Rate Limit: 100 emails per minute
- Circuit Breaker: 5 failures trigger open state
- Queue Processing: 1-second intervals
- Retry Attempts: Maximum 3 per email
- express: Web framework
- drizzle-orm: Type-safe ORM
- zod: Schema validation
- uuid: Unique ID generation
- react: Frontend framework
- @tanstack/react-query: Server state management
- wouter: Client-side routing
- typescript: Type checking
- vite: Build tool and dev server
- tsx: TypeScript execution
- tailwindcss: CSS framework
- @radix-ui: Headless UI components
EmailService: Email orchestration onlyCircuitBreaker: Failure detection and recoveryRateLimiter: Request rate managementEmailQueue: Queue operations
EmailProviderinterface allows new provider implementationsIStorageinterface supports different storage backends
- Services depend on abstractions (
IStorage,EmailProvider) - Concrete implementations injected via constructor
- 400: Validation errors with detailed field messages
- 500: Internal server errors with descriptive messages
- Rate Limit: 429 with retry-after information
- Circuit breaker prevents cascading failures
- Graceful degradation with provider fallback
- Comprehensive logging for debugging
- In-memory storage for fast access
- Efficient queue processing with priority sorting
- Real-time dashboard updates (30s intervals)
- Provider health caching
- Stateless service design
- Database-ready storage interface
- Horizontal scaling support
- Queue-based architecture
- Header-based duplicate prevention
- Unique key validation
- Safe retry operations
- Per-service rate limiting
- Sliding window algorithm
- Configurable limits
- Mock Providers: Real email providers would require API keys and different error handling
- In-Memory Storage: Production would use PostgreSQL or similar database
- Single Instance: Horizontal scaling would require distributed queue/state
- Development Focus: Optimized for demonstration rather than production deployment
- Responsive Design: Works on desktop and mobile
- Real-time Updates: Live dashboard refreshing
- Professional Theme: Clean, modern interface
- Interactive Forms: Validation and error handling
- Status Indicators: Visual system health monitoring
- Replace in-memory storage with PostgreSQL
- Add authentication and authorization
- Configure environment-specific settings
- Set up monitoring and alerting
- Implement distributed circuit breaker state
- Add comprehensive logging and metrics
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 5000
CMD ["npm", "start"]For questions or issues:
- Check the system logs in the dashboard
- Review API response messages
- Verify rate limiting status
- Monitor provider health status
Built with TypeScript, React, and modern web technologies for maximum reliability and developer experience.# ResilientMailer-test