Skip to content
Open
Show file tree
Hide file tree
Changes from 8 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
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,63 @@ client = GrowthBookClient(
)
```

### Polling

`polling_interval` (seconds) makes the async client refresh features on a fixed
schedule:

```python
client = GrowthBookClient(Options(
api_host="https://cdn.growthbook.io",
client_key="sdk-abc123",
polling_interval=60,
))
```

Three things worth knowing:

**It runs alongside SSE, not instead of it.** Combine it with
`refresh_strategy=SERVER_SENT_EVENTS` and you get both. That is the point: a
stream blocked by a proxy or firewall looks exactly like a stream with no events
yet, so polling is what keeps such an app refreshing.

**The configured interval is the interval used.** Polling bypasses the feature
cache. Without `polling_interval` set, the built-in refresh goes through the
cache, so an interval shorter than `cache_ttl` issues no requests at all.

**Failures back off.** After a failed refresh the wait doubles from the
interval, up to five minutes or the interval itself, whichever is longer.
Jitter then stretches each wait by up to 2x, so the longest wait is ten minutes
(or twice the interval). It returns to the interval on the next success and
never retries faster than the configured interval.

Out-of-range values (non-positive, non-numeric, or longer than a day) are
rejected with a warning rather than clamped — a negative interval is a typo,
and reinterpreting it as "as fast as possible" turns a config slip into a
request flood. The client then refreshes as if `polling_interval` were unset:
the stream only with SSE, the default cache-bound 60s polling otherwise.

Remote-eval mode ignores it: payloads there are per-user, so there is no global
payload to poll for.

For the sync `GrowthBook` class the equivalent is
`stale_while_revalidate=True` with `stale_ttl` as the interval; it already
fetches directly rather than through the cache. `stale_ttl` is validated the
same way: an out-of-range value logs a warning and leaves the poller off.
That includes values over a day, which used to poll at that interval.

Instances on the same `api_host` and `client_key` share one poller. `destroy()`
releases the instance's share, and the poller stops when the last instance
using it is destroyed, so a per-request instance can be destroyed without
stopping refreshes for a long-lived one on the same key.
`feature_repo.stop_background_refresh()` is still a hard stop for everyone.

The first instance on a key sets the poller's interval, `cache_ttl` and
decryption key; a later instance asking for a different interval gets a warning
and the running poller. The async client works the same way: one feature
repository per key, so a second `GrowthBookClient` with its own
`polling_interval` is warned and keeps the first one's polling.

### Concurrency and Thread Safety

The async client is designed to be thread-safe and handle concurrent requests efficiently. You can safely use a single client instance across multiple coroutines. For web applications, you can create a single client instance at startup and share it across requests. Here's an example:
Expand Down
45 changes: 45 additions & 0 deletions growthbook/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import json
import logging
import math
import threading
from copy import deepcopy
from dataclasses import dataclass, field, replace
Expand Down Expand Up @@ -799,6 +800,12 @@ class Options:
# sticky_bucket_cache_size. Non-positive values disable caching.
sticky_bucket_cache_ttl: float = 0
sticky_bucket_cache_size: int = 1000
# Seconds between background feature refreshes. None keeps the historical
# behavior: polling only when refresh_strategy is STALE_WHILE_REVALIDATE,
# at a fixed 60s. Set it and polling runs at exactly this interval,
# bypassing the cache — and it runs alongside SSE rather than instead of
# it, so a stream blocked by a proxy still leaves the app refreshing.
polling_interval: Optional[float] = None


@dataclass
Expand Down Expand Up @@ -902,6 +909,44 @@ def build_remote_eval_payload(
}


MAX_POLLING_INTERVAL_SECONDS = 60 * 60 * 24 # a day; longer is a unit mix-up


def validate_polling_interval(
interval: Optional[float], name: str = "polling_interval"
) -> Optional[float]:
"""Return the interval to poll at, or None to leave polling off.

Out-of-range values are rejected with a warning rather than clamped: a
negative interval is a typo, and silently reinterpreting it as "poll as
fast as possible" is how a config slip turns into a request flood
(`Event.wait()` and `asyncio.sleep()` both return immediately on a negative
delay). Reporting it and leaving polling off is the safer failure."""
if interval is None:
return None
if not isinstance(interval, (int, float)) or isinstance(interval, bool):
logger.warning("Ignoring non-numeric %s: %r", name, interval)
return None
if not math.isfinite(interval):
# NaN slips past both range checks (every comparison is False), and
# Event.wait(nan) doesn't wait, so it would be a request flood too.
logger.warning("Ignoring non-finite %s: %r", name, interval)
return None
if interval <= 0:
logger.warning("Ignoring non-positive %s: %r", name, interval)
return None
if interval > MAX_POLLING_INTERVAL_SECONDS:
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
logger.warning(
"Ignoring %s of %r seconds: longer than the %d second maximum "
"(the value is in seconds, not milliseconds)",
name,
interval,
MAX_POLLING_INTERVAL_SECONDS,
)
return None
return float(interval)


def is_cloud_host(api_host: Optional[str]) -> bool:
"""True if api_host points at GrowthBook Cloud (which doesn't expose
/api/eval). Handles schemeless inputs like "cdn.growthbook.io" — naive
Expand Down
Loading
Loading