Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,68 @@ Retries are disabled only on the pool the SDK creates itself.
or `GrowthBookClient(Options(request_timeout=None))`. For sync clients only,
you can also set `feature_repo.request_timeout = None` once for the whole process.

#### Retries

When a feature fetch fails, the call that made it returns at once with the
best available features (cache, an inline payload, or defaults), and the fetch
is retried in the background, waiting 1, 2, 4, 8 and 16 seconds between
attempts. Retries never extend startup. A successful retry applies the features
as a normal load would; after the last one the SDK stops and keeps what it has.
Each retry is logged:

```
Feature fetch failed. Retry attempt 2/5 in 2000ms.
```

```python
gb = GrowthBook(
api_host = "https://cdn.growthbook.io",
client_key = "sdk-abc123",
max_fetch_retries = 5, # 0 disables retrying
fetch_retry_max_delay = 16, # seconds; caps the doubling
)
```

**Only failures that can resolve on their own are retried:** connection
errors, timeouts, 429 and 5xx. A 401, 403 or 404 (a wrong or revoked client
key, a wrong `api_host`), a response that isn't a valid payload, or one that
fails to decrypt is reported once and not retried, and a retry that hits one
of these stops the loop.

**One retry loop per client key.** All `GrowthBook` instances with the same
`api_host` and `client_key` share one loop, so an outage doesn't multiply
requests by the number of instances (e.g. one per web request). The first
instance to fail starts it, with its settings; a success reaches every
instance on the key, and only those. A destroyed instance doesn't receive the
result, and the loop stops early once every instance on the key has been
destroyed.

The async client takes the same two options in `Options`. There, a failed
`initialize()` still returns `False`, and a later successful retry installs the
features and starts refreshing.

**Not retried:** remote evaluation. Its responses are per user, so
`preload_remote_eval()` and the sync remote-eval load make one attempt; on
failure, evaluations fall back to defaults and fetch again on their own cache
miss. Likewise a refresh triggered by evaluating a feature (no SSE or
background refresh configured) isn't retried in the background: the next
evaluation tries again anyway.

#### Forcing a refresh

To fetch features now regardless of the cache's freshness:

```python
gb.load_features(force_refresh=True) # sync
await client.refresh_features() # async; force_refresh=True by default
```

Evaluations keep using the current features until the response arrives. If
`initialize()` failed, a successful `refresh_features()` completes it: the
pending retry stops and background refresh starts. In remote-eval mode,
`refresh_features()` drops the cached per-user responses so each user's next
evaluation refetches.

Here's a full example:

```python
Expand Down
57 changes: 57 additions & 0 deletions growthbook/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,58 @@
# than SDKs that leave requests unbounded unless the caller sets a timeout.
DEFAULT_REQUEST_TIMEOUT = 2.0

# Bounded retry of a failed feature fetch: 1s, 2s, 4s, 8s, 16s, then stop and
# keep the best available features (cache or inline payload). Retries run in
# the background — the first attempt alone bounds startup.
DEFAULT_MAX_FETCH_RETRIES = 5
DEFAULT_FETCH_RETRY_MAX_DELAY = 16.0
FETCH_RETRY_INITIAL_DELAY = 1.0


def validate_fetch_retry_options(max_retries: Any, max_delay: Any) -> None:
"""Raise ValueError for an unusable retry configuration. 0 retries is
valid and disables retrying."""
if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
raise ValueError(
f"max_fetch_retries must be a non-negative integer, got {max_retries!r}"
)
if (
isinstance(max_delay, bool)
or not isinstance(max_delay, (int, float))
or not math.isfinite(max_delay)
or max_delay <= 0
):
raise ValueError(
f"fetch_retry_max_delay must be a positive number of seconds, got {max_delay!r}"
)


def is_retryable_status(status: int) -> bool:
"""429 and 5xx are worth retrying. Any other 4xx (a wrong or revoked
client key, an unknown endpoint) gets the same answer next time, so
retrying it only adds requests and log lines."""
return status == 429 or status >= 500


def fetch_retry_delay(attempt: int, max_delay: float) -> float:
"""Seconds to wait before retry number `attempt` (1-based): doubles from
FETCH_RETRY_INITIAL_DELAY, capped at `max_delay`. Deterministic, so the
logged delay is the delay actually waited."""
return float(min(FETCH_RETRY_INITIAL_DELAY * (2 ** (attempt - 1)), max_delay))


def log_fetch_retry(attempt: int, total: int, delay: float) -> None:
logger.warning(
"Feature fetch failed. Retry attempt %d/%d in %dms.", attempt, total, round(delay * 1000)
)


def log_fetch_retries_exhausted(total: int) -> None:
logger.error(
"Feature fetch failed after %d retries; keeping the best available "
"features (cache or inline payload).", total
)


class _Unset(Enum):
"""Sentinel type for "argument not passed", where None is itself a
Expand Down Expand Up @@ -825,6 +877,11 @@ class Options:
# aiohttp's own limit); 0, a negative or a non-finite value is rejected at
# construction rather than silently meaning "no timeout".
request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT
# Also appended, after request_timeout, for the same reason.
# Background retries after a failed initial fetch (see
# DEFAULT_MAX_FETCH_RETRIES). 0 disables retrying.
max_fetch_retries: int = DEFAULT_MAX_FETCH_RETRIES
fetch_retry_max_delay: float = DEFAULT_FETCH_RETRY_MAX_DELAY


@dataclass
Expand Down
Loading
Loading