This document describes the Circuit Breaker implementation for Toast Notifications in the teachLink_web application. The Circuit Breaker pattern prevents cascading failures and provides fallback behavior when the toast notification system is overwhelmed.
The Circuit Breaker operates in three states:
-
CLOSED (Normal Operation)
- All toast notifications pass through normally
- Failures are tracked but don't block operations
- Circuit opens when failure threshold is reached
-
OPEN (Circuit Tripped)
- Toast notifications are blocked
- Fallback behavior is triggered
- System waits for timeout before attempting recovery
-
HALF_OPEN (Recovery Testing)
- Limited operations allowed to test system health
- Circuit closes if success threshold is reached
- Circuit reopens if failures continue
The Circuit Breaker uses the following configuration:
{
failureThreshold: 5, // Number of failures before opening
successThreshold: 2, // Number of successes to close circuit
timeout: 60000, // Time in ms before attempting recovery (1 minute)
monitoringPeriod: 10000, // Time window for failure counting (10 seconds)
maxConcurrentRequests: 10 // Maximum concurrent toast operations
}-
CircuitBreaker Class (
src/utils/circuitBreaker.ts)- Manages circuit state transitions
- Tracks metrics and failure history
- Executes operations with circuit protection
- Provides fallback mechanisms
-
ToastContext Integration (
src/context/ToastContext.tsx)- Wraps toast operations with Circuit Breaker
- Provides metrics access via
getCircuitBreakerMetrics() - Allows manual reset via
resetCircuitBreaker() - Shows fallback toast when circuit is open
import { useToast } from '@/context/ToastContext';
function MyComponent() {
const { addToast, getCircuitBreakerMetrics, resetCircuitBreaker } = useToast();
// Normal usage - Circuit Breaker handles protection automatically
addToast('Operation successful', 'success');
// Check circuit breaker metrics
const metrics = getCircuitBreakerMetrics();
console.log('Circuit state:', metrics.state);
// Manually reset circuit breaker if needed
resetCircuitBreaker();
}The Circuit Breaker tracks the following metrics:
state: Current circuit state (CLOSED, OPEN, HALF_OPEN)failureCount: Current failure count in monitoring windowsuccessCount: Current success count in recovery modelastFailureTime: Timestamp of last failurelastStateChange: Timestamp of last state transitiontotalRequests: Total number of requests processedtotalFailures: Total number of failurestotalSuccesses: Total number of successes
When the Circuit Breaker is OPEN:
- Toast notifications are suppressed
- A warning is logged to console
- A simplified fallback toast is shown: "Notifications temporarily limited"
- Maximum of 2 fallback toasts are displayed simultaneously
This prevents UI clutter while informing users of the temporary limitation.
Located in src/utils/__tests__/circuitBreaker.test.ts:
- Initial state verification
- Successful operation handling
- Failure tracking and circuit opening
- Fallback behavior
- Recovery (HALF_OPEN state)
- Concurrent request limiting
- Metrics tracking
- Reset functionality
Located in src/context/__tests__/ToastContext.circuitBreaker.test.tsx:
- Circuit breaker metrics availability
- Toast operation tracking
- Circuit breaker reset
- Normal toast rendering
- Different toast type handling
- Toast suppression when circuit is open
- Warning logging
The Circuit Breaker implementation is designed for minimal performance impact:
- O(1) State Checks: State transitions are constant time operations
- Efficient Failure Tracking: Uses array with automatic cleanup of old entries
- Non-blocking: Operations fail fast when circuit is open
- Memory Efficient: Limits concurrent requests and toast queue size
- Minimal Overhead: Only adds logging and state management overhead
The Circuit Breaker implementation maintains accessibility:
- Fallback toasts use the same accessible Toast component
- Role="alert" is preserved on all toast notifications
- ARIA labels remain intact
- Screen readers receive notification of temporary limitations
- No impact on keyboard navigation
The Circuit Breaker enhances security:
- Rate Limiting: Prevents toast spam attacks
- Resource Protection: Limits concurrent operations to prevent DoS
- Fail-Safe: Graceful degradation under load
- No Sensitive Data Exposure: Metrics don't expose sensitive information
- Console Logging: Only logs non-sensitive operation details
The Circuit Breaker logs important events:
[Toast Circuit Breaker] Toast notification suppressed- When circuit is open[Toast Circuit Breaker] Error- When unexpected errors occur
Access real-time metrics via the getCircuitBreakerMetrics() function:
const metrics = getCircuitBreakerMetrics();
if (metrics.state === 'OPEN') {
console.log('Circuit is open, last failure:', metrics.lastFailureTime);
}- Don't Suppress Errors: Let the Circuit Breaker handle failures naturally
- Monitor Metrics: Use metrics to identify patterns and adjust configuration
- Test Failure Scenarios: Verify fallback behavior works as expected
- Adjust Configuration: Tune thresholds based on application load
- Manual Reset: Use
resetCircuitBreaker()only when necessary (e.g., after fixing issues)
If the circuit opens frequently:
- Check for error conditions in toast operations
- Increase
failureThresholdif failures are expected - Increase
timeoutto allow more recovery time - Review
monitoringPeriodto adjust failure counting window
If toasts are not appearing:
- Check circuit state via
getCircuitBreakerMetrics() - Look for console warnings about suppressed notifications
- Verify
maxConcurrentRequestsis not too low - Consider manually resetting the circuit breaker
If performance is impacted:
- Verify Circuit Breaker is not the bottleneck (check metrics)
- Reduce
monitoringPeriodfor faster cleanup - Lower
maxConcurrentRequestsif system is overloaded - Review console logging frequency
Potential improvements for the Circuit Breaker:
- Adaptive Thresholds: Automatically adjust thresholds based on load
- Metrics Dashboard: Visual monitoring of circuit breaker state
- Custom Fallbacks: Allow custom fallback behavior per toast type
- Circuit Breaker Events: Emit events for state changes
- Persistence: Save metrics across page reloads
- Integration with Monitoring: Send metrics to external monitoring services
- Circuit Breaker Pattern - Martin Fowler
- Microsoft Circuit Breaker Pattern
- Resilience4j Circuit Breaker
- Initial implementation of Circuit Breaker for Toast Notifications
- Integration with ToastContext
- Comprehensive unit and integration tests
- Documentation and usage examples