mirzaaghazadeh / smart-failover
A comprehensive Laravel package for automatic failover handling across databases, caches, queues, and other services with intelligent routing and minimal code integration.
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 17
Watchers: 0
Forks: 1
Open Issues: 0
pkg:composer/mirzaaghazadeh/smart-failover
Requires
- php: ^8.1
- illuminate/cache: ^9.0|^10.0|^11.0|^12.0
- illuminate/database: ^9.0|^10.0|^11.0|^12.0
- illuminate/log: ^9.0|^10.0|^11.0|^12.0
- illuminate/queue: ^9.0|^10.0|^11.0|^12.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
- laravel/framework: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.88
- larastan/larastan: ^2.9|^3.0
- mockery/mockery: ^1.4
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.0|^10.0|^11.0
- vimeo/psalm: ^6.13
README
The Ultimate Laravel Package for Bulletproof Service Failover
Never let a service failure bring down your application again
๐ Documentation โข ๐ Quick Start โข ๐ก Examples โข ๐ฅ Health Monitoring โข ๐ค Contributing
๐ Table of Contents
- ๐ฏ Why SmartFailover?
- โจ Features
- ๐ Quick Start
- โ๏ธ Configuration
- ๐ก Usage Examples
- ๐ฅ Health Monitoring
- ๐ Notifications & Alerts
- ๐ Dashboard Integration
- ๐งช Testing
- ๐ Performance
- ๐ Security
- ๐ค Contributing
- ๐ License
๐ฏ Why SmartFailover?
The Problem ๐ฐ
graph TD A[Your Laravel App] --> B[Single Database] A --> C[Single Cache] A --> D[Single Queue] B --> E[๐ฅ Database Fails] C --> F[๐ฅ Cache Fails] D --> G[๐ฅ Queue Fails] E --> H[๐ด App Crashes] F --> H G --> H style H fill:#ff6b6b style E fill:#ff6b6b style F fill:#ff6b6b style G fill:#ff6b6bLoading
The Solution ๐
graph TD A[Your Laravel App] --> B[SmartFailover] B --> C[Primary DB] B --> D[Backup DB] B --> E[Primary Cache] B --> F[Backup Cache] B --> G[Primary Queue] B --> H[Backup Queue] C --> I[๐ฅ Fails] I --> J[โ Auto Switch to Backup] E --> K[๐ฅ Fails] K --> L[โ Auto Switch to Backup] G --> M[๐ฅ Fails] M --> N[โ Auto Switch to Backup] J --> O[๐ข App Stays Online] L --> O N --> O style O fill:#51cf66 style J fill:#51cf66 style L fill:#51cf66 style N fill:#51cf66Loading
SmartFailover transforms your single-point-of-failure Laravel application into a resilient, self-healing system that automatically switches to backup services when primary ones fail.
๐ฏ Key Benefits
Before SmartFailover | After SmartFailover |
---|---|
๐ฅ Single database failure = App down | โ Automatic failover to backup database |
๐ Manual intervention required | ๐ Zero-downtime automatic switching |
๐ฐ No visibility into service health | ๐ Real-time health monitoring |
๐ฅ Panic when services fail | ๐ Sleep peacefully with alerts |
โจ Features
๐ก๏ธ Bulletproof Service Protection
Service | Primary | Fallbacks | Health Checks |
---|---|---|---|
๐๏ธ Database | MySQL, PostgreSQL | Multiple backups | โ Connection tests |
๐ Cache | Redis, Memcached | Array, File | โ Read/Write tests |
๐ฌ Queue | SQS, Redis | Database, Sync | โ Job dispatch tests |
๐ง Mail | SMTP, SES | Mailgun, Log | โ Connection tests |
๐พ Storage | S3, GCS | Local, FTP | โ File operations |
๐ฏ Smart Features
๐ Auto Failover | ๐ฅ Health Monitoring | ๐ Smart Alerts | ๐๏ธ Easy Integration |
---|---|---|---|
Instant switching when services fail | Real-time service health checks | Slack, Telegram, Email notifications | Minimal code changes required |
Exponential backoff retry logic | Performance metrics tracking | Intelligent alert throttling | Fluent API design |
Graceful degradation support | HTTP health endpoints | Custom notification channels | Laravel-native integration |
๐ Quick Start
๐ฆ Installation
# 1๏ธโฃ Install the package composer require mirzaaghazadeh/smart-failover # 2๏ธโฃ Publish configuration php artisan vendor:publish --provider="Mirzaaghazadeh\SmartFailover\SmartFailoverServiceProvider" --tag="config" # 3๏ธโฃ Configure your services (optional) php artisan vendor:publish --provider="Mirzaaghazadeh\SmartFailover\SmartFailoverServiceProvider" --tag="migrations"
โก 30-Second Setup
// That's it! Start using SmartFailover immediately: use Mirzaaghazadeh\SmartFailover\Facades\SmartFailover; // Wrap your existing code with failover protection SmartFailover::db('mysql', ['mysql_backup']) ->cache('redis', ['memcached']) ->execute(function() { // Your existing Laravel code works unchanged! $user = User::create($userData); Cache::put('user_' . $user->id, $user, 3600); return $user; });
๐ That's it! Your app is now bulletproof!
โ๏ธ Configuration
๐ง Basic Configuration
The config/smart-failover.php
file is your control center:
<?php return [ // ๐๏ธ Database Failover 'database' => [ 'primary' => 'mysql', 'fallbacks' => ['mysql_backup', 'sqlite_fallback'], 'health_check_interval' => 30, // seconds 'retry_attempts' => 3, 'retry_delay' => 1000, // milliseconds ], // ๐ Cache Failover 'cache' => [ 'primary' => 'redis', 'fallbacks' => ['memcached', 'array'], 'health_check_interval' => 15, 'retry_attempts' => 2, ], // ๐ฌ Queue Failover 'queue' => [ 'primary' => 'sqs', 'fallbacks' => ['redis', 'database'], 'health_check_interval' => 60, 'retry_attempts' => 3, ], // ๐ Notifications 'notifications' => [ 'slack' => [ 'webhook_url' => env('SMART_FAILOVER_SLACK_WEBHOOK'), 'channel' => '#alerts', ], 'telegram' => [ 'bot_token' => env('SMART_FAILOVER_TELEGRAM_BOT_TOKEN'), 'chat_id' => env('SMART_FAILOVER_TELEGRAM_CHAT_ID'), ], ], ];
๐ Environment Variables
Add these to your .env
file:
# Slack Notifications SMART_FAILOVER_SLACK_WEBHOOK=https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK # Telegram Notifications SMART_FAILOVER_TELEGRAM_BOT_TOKEN=your_bot_token SMART_FAILOVER_TELEGRAM_CHAT_ID=your_chat_id # Health Check Settings SMART_FAILOVER_HEALTH_ENABLED=true SMART_FAILOVER_HEALTH_CACHE_TTL=60
๐ก Usage Examples
๐ฏ The Magic One-Liner
use Mirzaaghazadeh\SmartFailover\Facades\SmartFailover; // Protect ALL your services in one beautiful line SmartFailover::db('mysql', ['mysql_backup']) ->cache('redis', ['memcached', 'array']) ->queue('sqs', ['redis', 'database']) ->execute(function() { // Your normal Laravel code - unchanged! $order = Order::create($orderData); Cache::put('order_' . $order->id, $order, 3600); ProcessOrderJob::dispatch($order); return $order; });
๐๏ธ Database Failover Examples
๐ Click to see Database Examples
// โ Simple Database Failover SmartFailover::db('mysql_primary', ['mysql_backup']) ->execute(function() { return User::where('active', true)->get(); }); // โ With Graceful Degradation SmartFailover::db('mysql_primary', ['mysql_backup']) ->gracefulDegradation(function() { // Return cached data when all databases fail return Cache::get('users_fallback', collect()); }) ->execute(function() { return User::all(); }); // โ Advanced Retry Logic SmartFailover::db('mysql_primary', ['mysql_backup']) ->retryAttempts(5) ->retryDelay(2000) // 2 seconds ->retryMultiplier(1.5) // Exponential backoff ->execute(function() { return User::with('orders')->paginate(50); });
๐ Cache Failover Examples
๐ Click to see Cache Examples
// โ Multi-Level Cache Failover SmartFailover::cache('redis', ['memcached', 'array']) ->execute(function() { Cache::put('user_preferences', $preferences, 3600); return Cache::get('user_preferences'); }); // โ Direct Cache Manager Usage use Mirzaaghazadeh\SmartFailover\Services\CacheFailoverManager; $cacheManager = app(CacheFailoverManager::class); $cacheManager->setStores('redis', ['memcached']); // Store with automatic failover $cacheManager->put('user_123', $userData, 3600); // Retrieve with automatic failover $userData = $cacheManager->get('user_123'); // โ Cache with Fallback Data SmartFailover::cache('redis', ['memcached']) ->gracefulDegradation(function() { return [ 'user_preferences' => config('app.default_preferences'), 'settings' => config('app.default_settings'), ]; }) ->execute(function() { return [ 'user_preferences' => Cache::get('user_prefs'), 'settings' => Cache::get('app_settings'), ]; });
๐ฌ Queue Failover Examples
๐ Click to see Queue Examples
// โ Queue Failover SmartFailover::queue('sqs', ['redis', 'database']) ->execute(function() { ProcessOrderJob::dispatch($order); SendEmailJob::dispatch($user, $email); }); // โ Direct Queue Manager Usage use Mirzaaghazadeh\SmartFailover\Services\QueueFailoverManager; $queueManager = app(QueueFailoverManager::class); $queueManager->setConnections('sqs', ['redis']); // Dispatch with failover $queueManager->push(new ProcessOrderJob($order)); $queueManager->later(60, new SendReminderJob($user));
๐ง Mail & Storage Examples
๐ Click to see Mail & Storage Examples
// โ Mail Failover use Mirzaaghazadeh\SmartFailover\Services\MailFailoverManager; $mailManager = app(MailFailoverManager::class); $mailManager->setMailers('ses', ['smtp', 'mailgun']); // Send with automatic failover $mailManager->send(new WelcomeEmail($user)); $mailManager->queue(new NewsletterEmail($subscribers)); // โ Storage Failover use Mirzaaghazadeh\SmartFailover\Services\StorageFailoverManager; $storageManager = app(StorageFailoverManager::class); $storageManager->setDisks('s3', ['local', 'backup_s3']); // Store file with failover $storageManager->put('uploads/file.jpg', $fileContents); // Retrieve file with failover $contents = $storageManager->get('uploads/file.jpg'); // Sync file across all disks $results = $storageManager->sync('important/backup.sql', $sqlDump);
๐ฅ Health Monitoring
๐ Real-Time Health Dashboard
SmartFailover automatically creates health endpoints for monitoring:
# ๐ HTTP Health Endpoints GET /health # Overall health status GET /health/detailed # Detailed health information GET /health/database # Database-specific health GET /health/cache # Cache-specific health GET /health/queue # Queue-specific health
๐ Health Response Example
{ "status": "healthy", "timestamp": "2024-01-15T10:30:00Z", "services": { "database": { "mysql_primary": { "status": "healthy", "response_time": 12.5, "last_checked": "2024-01-15T10:30:00Z", "details": "Connection successful" }, "mysql_backup": { "status": "healthy", "response_time": 15.2, "last_checked": "2024-01-15T10:30:00Z" } }, "cache": { "redis": { "status": "healthy", "response_time": 2.1, "memory_usage": "45.2MB" }, "memcached": { "status": "degraded", "response_time": 150.5, "warning": "High response time" } } }, "summary": { "total_services": 4, "healthy_services": 3, "degraded_services": 1, "unhealthy_services": 0, "average_response_time": 45.1 } }
๐ฅ๏ธ CLI Health Commands
# ๐ Check overall health php artisan smart-failover:health # ๐ฏ Check specific service php artisan smart-failover:health --service=database # ๐ Detailed health information php artisan smart-failover:health --detailed # ๐ JSON output for monitoring tools php artisan smart-failover:health --json # ๐งช Test failover scenarios php artisan smart-failover:test all php artisan smart-failover:test database --simulate-failure
๐ Notifications & Alerts
๐ฌ Slack Integration
// config/smart-failover.php 'notifications' => [ 'slack' => [ 'webhook_url' => env('SMART_FAILOVER_SLACK_WEBHOOK'), 'channel' => '#alerts', 'username' => 'SmartFailover Bot', 'emoji' => ':warning:', 'throttle_minutes' => 5, // Prevent spam ], ],
๐ฑ Telegram Integration
'notifications' => [ 'telegram' => [ 'bot_token' => env('SMART_FAILOVER_TELEGRAM_BOT_TOKEN'), 'chat_id' => env('SMART_FAILOVER_TELEGRAM_CHAT_ID'), 'throttle_minutes' => 5, 'parse_mode' => 'Markdown', ], ],
๐ง Email Alerts
'notifications' => [ 'email' => [ 'to' => ['admin@example.com', 'devops@example.com'], 'subject' => '๐จ SmartFailover Alert', 'throttle_minutes' => 10, 'template' => 'smart-failover::alert', ], ],
๐ฏ Custom Notification Channels
use Mirzaaghazadeh\SmartFailover\Services\NotificationManager; $notificationManager = app(NotificationManager::class); // Add custom notification channel $notificationManager->addChannel('discord', function($message, $context) { // Your custom Discord notification logic Http::post('https://discord.com/api/webhooks/YOUR_WEBHOOK', [ 'content' => "๐จ **SmartFailover Alert**\n{$message}", 'embeds' => [ [ 'title' => 'Service Status', 'description' => $context['details'], 'color' => $context['status'] === 'healthy' ? 0x00ff00 : 0xff0000, ] ] ]); });
๐ Dashboard Integration
๐จ Laravel Nova Integration
// In your Nova dashboard use Mirzaaghazadeh\SmartFailover\Services\HealthCheckManager; use Laravel\Nova\Cards\Help; public function cards(Request $request) { $healthManager = app(HealthCheckManager::class); $health = $healthManager->getHealthResponse(); return [ (new Help) ->heading('SmartFailover Status') ->content(" <div class='flex items-center space-x-4'> <div class='flex-1'> <div class='text-lg font-semibold text-green-600'> {$health['summary']['healthy_services']}/{$health['summary']['total_services']} Services Healthy </div> <div class='text-sm text-gray-600'> Avg Response Time: {$health['summary']['average_response_time']}ms </div> </div> <div class='w-4 h-4 rounded-full " . ($health['status'] === 'healthy' ? 'bg-green-500' : 'bg-red-500') . "'></div> </div> "), ]; }
๐๏ธ Filament Integration
// In your Filament widget use Mirzaaghazadeh\SmartFailover\Services\HealthCheckManager; use Filament\Widgets\StatsOverviewWidget as BaseWidget; use Filament\Widgets\StatsOverviewWidget\Stat; class SmartFailoverStatsWidget extends BaseWidget { protected function getStats(): array { $healthManager = app(HealthCheckManager::class); $health = $healthManager->checkAll(); return [ Stat::make('Service Health', $health['summary']['healthy_services'] . '/' . $health['summary']['total_services']) ->description('Healthy Services') ->descriptionIcon($health['status'] === 'healthy' ? 'heroicon-m-check-circle' : 'heroicon-m-x-circle') ->color($health['status'] === 'healthy' ? 'success' : 'danger'), Stat::make('Response Time', number_format($health['summary']['average_response_time'], 1) . 'ms') ->description('Average response time') ->descriptionIcon('heroicon-m-clock') ->color('info'), Stat::make('Uptime', '99.9%') ->description('Last 30 days') ->descriptionIcon('heroicon-m-arrow-trending-up') ->color('success'), ]; } }
๐งช Testing
๐ฌ Built-in Testing Tools
# ๐งช Test all configured services php artisan smart-failover:test all # ๐ฏ Test specific service php artisan smart-failover:test database --primary=mysql --fallback=mysql_backup # ๐ฅ Simulate failure scenarios php artisan smart-failover:test cache --simulate-failure # ๐ Performance testing php artisan smart-failover:test queue --performance --iterations=100
๐งช Unit Testing Your Failover Logic
use Mirzaaghazadeh\SmartFailover\Facades\SmartFailover; use Tests\TestCase; class FailoverTest extends TestCase { /** @test */ public function it_fails_over_to_backup_database_when_primary_fails() { // Simulate primary database failure DB::shouldReceive('connection')->with('mysql_primary')->andThrow(new Exception('Connection failed')); DB::shouldReceive('connection')->with('mysql_backup')->andReturn(true); $result = SmartFailover::db('mysql_primary', ['mysql_backup']) ->execute(function() { return User::count(); }); $this->assertNotNull($result); } /** @test */ public function it_sends_notifications_on_failover() { Notification::fake(); // Trigger failover scenario SmartFailover::db('mysql_primary', ['mysql_backup']) ->execute(function() { throw new Exception('Primary DB failed'); }); Notification::assertSentTo( config('smart-failover.notifications.email.to'), SmartFailoverAlert::class ); } }
๐ Performance Testing
// Benchmark failover performance $startTime = microtime(true); SmartFailover::db('mysql_primary', ['mysql_backup']) ->cache('redis', ['memcached']) ->execute(function() { // Your application logic return User::with('orders')->limit(1000)->get(); }); $executionTime = (microtime(true) - $startTime) * 1000; echo "Failover execution time: {$executionTime}ms";
๐ Performance
โก Optimized for Speed
Feature | Performance Impact | Optimization |
---|---|---|
๐ Connection Pooling | -50% overhead | Reuse connections |
๐ Async Health Checks | -80% request latency | Background monitoring |
๐พ Result Caching | -90% repeated checks | Smart caching |
๐ฏ Lazy Loading | -30% memory usage | Load on demand |
๐ Connection Pooling
// Connections are automatically pooled and reused SmartFailover::db('mysql_primary', ['mysql_backup']) ->poolConnections(true) // Default: true ->execute(function() { // Multiple queries use the same connection User::all(); Order::all(); Product::all(); });
๐ Async Health Checks
// config/smart-failover.php 'health_checks' => [ 'async' => true, // Run health checks in background 'interval' => 30, // Check every 30 seconds 'cache_results' => true, // Cache health check results 'cache_ttl' => 60, // Cache for 60 seconds 'parallel_checks' => true, // Check services in parallel ],
๐ Performance Monitoring
use Mirzaaghazadeh\SmartFailover\Services\PerformanceMonitor; $monitor = app(PerformanceMonitor::class); // Get performance metrics $metrics = $monitor->getMetrics(); /* [ 'average_response_time' => 45.2, 'total_requests' => 1250, 'failover_count' => 3, 'success_rate' => 99.8, 'services' => [ 'database' => ['response_time' => 12.5, 'success_rate' => 100], 'cache' => ['response_time' => 2.1, 'success_rate' => 99.5], ] ] */
๐ Security
๐ก๏ธ Security Best Practices
๐ Credential Management | ๐ซ Access Control | ๐ Audit Logging |
---|---|---|
Environment variables only | Rate limit health endpoints | Log all failover events |
No credentials in logs | IP whitelist for monitoring | Secure log storage |
Encrypted connection strings | Authentication required | Compliance ready |
๐ Secure Configuration
// config/smart-failover.php 'security' => [ 'health_endpoints' => [ 'enabled' => true, 'middleware' => ['auth', 'throttle:60,1'], // Require auth + rate limiting 'ip_whitelist' => ['127.0.0.1', '10.0.0.0/8'], // Restrict access ], 'logging' => [ 'log_credentials' => false, // Never log sensitive data 'encrypt_logs' => true, // Encrypt log files 'audit_trail' => true, // Full audit trail ], 'notifications' => [ 'encrypt_webhooks' => true, // Encrypt webhook payloads 'verify_ssl' => true, // Verify SSL certificates ], ],
๐ Audit Logging
// All failover events are automatically logged use Mirzaaghazadeh\SmartFailover\Services\AuditLogger; $auditLogger = app(AuditLogger::class); // Get audit trail $events = $auditLogger->getEvents([ 'service' => 'database', 'event_type' => 'failover', 'date_from' => '2024-01-01', 'date_to' => '2024-01-31', ]); /* [ [ 'timestamp' => '2024-01-15T10:30:00Z', 'service' => 'database', 'event_type' => 'failover', 'primary' => 'mysql_primary', 'fallback' => 'mysql_backup', 'reason' => 'Connection timeout', 'user_id' => 123, 'ip_address' => '192.168.1.100', ] ] */
๐ค Contributing
๐ We Love Contributors!
๐ How to Contribute
- ๐ด Fork the repository
- ๐ฟ Create your feature branch (
git checkout -b feature/amazing-feature
) - โ
Test your changes (
composer test
) - ๐ Commit your changes (
git commit -m 'Add amazing feature'
) - ๐ Push to the branch (
git push origin feature/amazing-feature
) - ๐ Open a Pull Request
๐งช Development Setup
# Clone the repository git clone https://github.com/mirzaaghazadeh/SmartFailover.git cd SmartFailover # Install dependencies composer install # Run tests composer test # Run code quality checks composer lint composer analyze
๐ Contribution Guidelines
- โ Write tests for new features
- โ Follow PSR-12 coding standards
- โ Update documentation
- โ Add changelog entries
- โ Ensure backward compatibility
๐ License
MIT License - see the LICENSE.md file for details
Feel free to use SmartFailover in your commercial and open-source projects
๐จโ๐ป Author & Support
๐ Created by Navid Mirzaaghazadeh
๐ฌ Get Help
- ๐ Documentation
- ๐ Report Issues
- ๐ก Feature Requests
- ๐ฌ Discussions
๐ Acknowledgments
Special Thanks To:
- ๐ Laravel Framework - For providing an excellent foundation
- ๐ฅ Laravel Community - For inspiration and feedback
- ๐ค All Contributors - Who help improve this package
- โ Coffee - For making this possible
โญ If SmartFailover helps your project, please give it a star!
Made with โค๏ธ for the Laravel Community
Never let a service failure bring down your application again!