Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,57 @@ To use the built-in fetching and caching logic, in the `GrowthBook` constructor,

Then, call the `load_features()` method to initiate the HTTP request with a cache layer.

#### Request timeouts

Feature fetches and remote-eval calls are bounded by `request_timeout`
(seconds, applied to both connect and read), defaulting to 2 seconds. On
timeout the SDK falls back to its cache or an inline payload, so a slow or
unreachable endpoint bounds startup instead of blocking it.

```python
gb = GrowthBook(
api_host = "https://cdn.growthbook.io",
client_key = "sdk-abc123",
request_timeout = 5, # seconds; None waits indefinitely
)
```

`http_connect_timeout` and `http_read_timeout` override it per phase; either
can be set on its own and the other inherits `request_timeout`. A value of `0`
or below is rejected at construction rather than treated as "no timeout" —
pass `None` to opt out (the sync client then waits indefinitely, the async
client falls back to aiohttp's own 300-second limit). The same options apply
to `Options` for the async client, and are validated when `GrowthBookClient`
is constructed.

The bound is per attempt and, on the pool the SDK creates, there are no
retries: a request that times out fails over to the cache instead of being
re-sent. A pool you assign yourself keeps its own retry policy (see below).

Timeouts passed to `GrowthBook(...)` apply to that instance's requests only;
constructing another instance doesn't change them. Anything an instance
doesn't set falls back to the shared repository, so process-wide defaults can
still be set once:

```python
from growthbook import feature_repo

feature_repo.request_timeout = 5
```

The stale-while-revalidate background poller is shared by the process and
keeps the timeouts of the instance that started it. The async client shares one
feature repository per `(api_host, client_key)`, so a second `GrowthBookClient`
with the same host and key uses the timeouts of the first one.

A pool you assign to `feature_repo.http` (for example a `ProxyManager`) is kept
as is, including its retry policy; only the timeouts are applied per request.
Retries are disabled only on the pool the SDK creates itself.

**Upgrading:** requests used to wait indefinitely (sync) or up to 300 seconds
(async) by default. To keep that behavior, pass `request_timeout=None`, or set
`feature_repo.request_timeout = None` once for the whole process.
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

Here's a full example:

```python
Expand Down
62 changes: 60 additions & 2 deletions growthbook/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@

logger = logging.getLogger("growthbook")

# Seconds. Finite so a hung endpoint can't block startup forever; generous
# enough to survive a cold TLS handshake on a slow link. Stricter by design
# than SDKs that leave requests unbounded unless the caller sets a timeout.
DEFAULT_REQUEST_TIMEOUT = 2.0


class _Unset(Enum):
"""Sentinel type for "argument not passed", where None is itself a
meaningful value (e.g. request_timeout=None waits indefinitely)."""
TOKEN = 0


UNSET = _Unset.TOKEN

# Generic feature/experiment value type. Deliberately unbounded: a JSONValue
# bound would reject TypedDict/dataclass-shaped fallbacks (see JS SDK issue #1729,
# where the equivalent bound was shipped and then reverted).
Expand Down Expand Up @@ -771,8 +785,17 @@ class Options:
on_experiment_viewed: Optional[AsyncTrackingCallback] = None
on_feature_usage: Optional[AsyncFeatureUsageCallback] = None
tracking_plugins: Optional[List["PluginLike"]] = None
http_connect_timeout: Optional[int] = None
http_read_timeout: Optional[int] = None
# Seconds allowed for a feature fetch or remote-eval call — connect and
# read alike. Finite by default so a slow or black-hole endpoint bounds
# startup instead of blocking it: on timeout the SDK falls back to cache or
# an inline payload. Pass None to opt back into waiting forever; 0 or a
# negative value is rejected at construction rather than silently meaning
# "no timeout".
request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
# Finer-grained overrides. Either may be set on its own; whichever is None
# falls back to request_timeout.
http_connect_timeout: Optional[float] = None
http_read_timeout: Optional[float] = None
event_logger: Optional[AsyncEventLogger] = None
remote_eval: bool = False
cache_key_attributes: Optional[List[str]] = None
Expand Down Expand Up @@ -900,6 +923,41 @@ def is_cloud_host(api_host: Optional[str]) -> bool:
return host == "growthbook.io" or host.endswith(".growthbook.io")


def resolve_request_timeouts(
request_timeout: Optional[float],
connect_timeout: Optional[float] = None,
read_timeout: Optional[float] = None,
) -> Tuple[Optional[float], Optional[float]]:
"""Return the (connect, read) seconds to apply, validating as it goes.

Each specific override stands on its own; whichever is None inherits
request_timeout. `None` throughout means "wait forever" — an explicit
opt-out, never the result of a falsy 0.

Raises ValueError on a non-positive or non-numeric value. Rejecting rather
than clamping is deliberate: `timeout=0` reads as "no timeout" in several
HTTP stacks, so silently accepting it would turn a typo into the unbounded
wait this default exists to prevent."""
for name, value in (
("request_timeout", request_timeout),
("http_connect_timeout", connect_timeout),
("http_read_timeout", read_timeout),
):
if value is None:
continue
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{name} must be a number of seconds, got {value!r}")
if value <= 0:
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
raise ValueError(
f"{name} must be greater than 0, got {value!r}; "
"pass None to wait indefinitely"
)

connect = connect_timeout if connect_timeout is not None else request_timeout
read = read_timeout if read_timeout is not None else request_timeout
return connect, read


def validate_remote_eval_options(
client_key: Optional[str],
decryption_key: Optional[str],
Expand Down
Loading
Loading