Skip to main content
The retry module provides reliability patterns to handle transient network failures and prevent cascading errors.

Circuit Breaker

The circuit breaker pattern prevents repeated attempts to access a failing service, giving it time to recover.

States

The circuit breaker has three states:
  • Closed: Normal operation, all requests allowed
  • Open: Too many failures, requests blocked immediately
  • Half-Open: Testing if service recovered, limited requests allowed

CircuitBreaker

Thread-safe circuit breaker implementation with atomic state transitions.
Parameters:
  • threshold: Number of failures before opening (default: 5)
  • timeout: Seconds to wait before testing recovery (default: 60)
Properties:
  • state: Current state (“closed”, “open”, “half_open”)
  • failures: Current failure count
  • last_failure_time: Timestamp of last failure
Example:

get_circuit_breaker

Get the global circuit breaker instance used by tif1.
Returns:
  • Global CircuitBreaker instance
Example:

reset_circuit_breaker

Reset the global circuit breaker to closed state with zero failures.
Example:

Circuit breaker methods

call(func, *args, **kwargs)

Execute a function with circuit breaker protection.
Parameters:
  • func: Function to execute
  • *args: Positional arguments for func
  • **kwargs: Keyword arguments for func
Returns:
  • Result from func
Raises:
  • Exception: If circuit breaker is open or func raises
Example:

record_success()

Manually record a successful operation.
Example:

record_failure()

Manually record a failed operation.
Example:

check_and_update_state()

Check current state and update if timeout elapsed.
Returns:
  • Tuple of (should_proceed, current_state)
Example:

Retry Decorator

retry_with_backoff

Decorator for automatic retry with exponential backoff and jitter.
Parameters:
  • max_retries: Maximum retry attempts (default: 3)
  • backoff_factor: Exponential backoff multiplier (default: 2.0)
  • jitter: Add random jitter to backoff (default: True)
  • exceptions: Tuple of exceptions to catch (default: all exceptions)
Backoff Formula:
Example:

Custom exception handling


Configuration

Configure circuit breaker and retry behavior via global config:
Configuration Keys:

Complete Examples

Monitor circuit breaker


Custom retry logic


Graceful Degradation


Retry with Progress


Best Practices

  1. Monitor circuit breaker state: Check before critical operations.
  1. Reset after fixing issues: Don’t wait for timeout if you know service is back.
  1. Use appropriate thresholds: Higher for transient errors, lower for persistent failures.

Troubleshooting

Circuit breaker stuck open

Too many retries

Adjust the max_retries parameter when using the @retry_with_backoff decorator:

Slow retries

Reduce the backoff factor globally or per-function:

Circuit breaker too sensitive

Last modified on March 5, 2026