-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbackoff.py
More file actions
49 lines (41 loc) · 1.39 KB
/
backoff.py
File metadata and controls
49 lines (41 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
Exponential backoff implementation for WebSocket reconnection.
This module provides utilities for implementing exponential backoff strategies
when reconnecting to failed WebSocket connections.
"""
import asyncio
import logging
from typing import AsyncIterator
logger = logging.getLogger(__name__)
async def exp_backoff(
max_retries: int,
base: float = 1.0,
factor: float = 2.0,
sleep: bool = False,
) -> AsyncIterator[float]:
"""
Generate exponential backoff delays for retry attempts.
Args:
max_retries: Maximum number of retry attempts
base: Base delay in seconds for the first retry
factor: Multiplicative factor for each subsequent retry
sleep: If True, sleep for the delay before yielding
Yields:
float: Delay in seconds for each retry attempt
Example:
>>> import asyncio
>>> async def example():
... delays = []
... async for delay in exp_backoff(max_retries=3, base=1.0, factor=2.0):
... delays.append(delay)
... return delays
>>> delays = asyncio.run(example())
>>> delays
[1.0, 2.0, 4.0]
"""
for attempt in range(max_retries):
delay = base * (factor**attempt)
logger.debug(f"Backoff attempt {attempt + 1}/{max_retries}: {delay}s delay")
if sleep:
await asyncio.sleep(delay)
yield delay