Skip to content
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,49 @@ client = GrowthBookClient(
)
```

### Feature Refresh Listeners

Both clients can notify your application whenever a new feature payload is
applied, so you can react to updates instead of polling:

```python
def on_refresh(payload):
log.info("features updated: %d flags", len(payload.get("features", {})))

unsubscribe = gb.add_feature_refresh_listener(on_refresh)
# ...later
unsubscribe()
```

The listener receives the raw payload dict (`features`, `savedGroups`, …) and
runs *after* it has been applied, so evaluating a feature from inside the
listener already sees the new definitions. It fires once per refresh — not once
per evaluation — covering HTTP loads, the stale-while-revalidate background
worker and streaming (SSE) updates. A listener that raises is logged and
skipped; it cannot break a refresh.

Listeners run one after another, in registration order, and payloads are
delivered in the order they were applied. A listener may update features
itself (`set_payload`, `load_features`, …). The newer payload is then applied
immediately, the remaining listeners receive only the newer one, and delivery
starts over with it, so no listener is handed a payload older than the applied
state. Keep listeners quick: a slow one delays the next refresh, so move heavy
work to a task.

On the async client the listener may be a plain function or a coroutine
function:

```python
async def on_refresh(payload):
await cache.invalidate()

unsubscribe = gb_client.add_feature_refresh_listener(on_refresh)
```

Remote-eval mode emits no events on the async client: payloads there are
per-user, so there is no client-wide "definitions changed" moment to report.
The sync client, which is already per-user, does fire them.

### 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
111 changes: 106 additions & 5 deletions growthbook/growthbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,6 +1005,15 @@ def __init__(
self._deferred_buffer: Optional[TrackingBuffer] = TrackingBuffer() if defer_tracking else None
self._assigned: Dict[str, Any] = {}
self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], None]] = set()
self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], None]] = []
# Identity of the last payload dispatched to listeners. The cache hands
# back the same object on every hit, and evaluation calls load_features()
# constantly, so an identity check is what keeps listeners firing once
# per actual refresh instead of once per evaluation.
self._last_refresh_payload: Optional[Dict[str, Any]] = None
# True while listeners run; a refresh started from inside a listener
# only applies its payload and leaves the delivery to the running loop.
self._dispatching_refresh = False
self._is_updating_features = False
# Serializes payload writers (set_features/set_payload/refreshes).
# Re-entrant because _ingest_payload calls set_features while holding
Expand Down Expand Up @@ -1083,8 +1092,7 @@ def _remote_eval_payload(self) -> Dict[str, Any]:

def _on_feature_update(self, features_data: Dict[str, Any]) -> None:
"""Callback to handle automatic feature updates from FeatureRepository"""
if features_data:
self._ingest_payload(features_data)
self._apply_and_notify(features_data if features_data else None)

def _ingest_payload(self, data: Dict[str, Any]) -> None:
"""Apply the sections present in a (decrypted) SDK payload.
Expand Down Expand Up @@ -1150,7 +1158,12 @@ def load_features(self, force_refresh: bool = False) -> None:
force_refresh=force_refresh,
)
if response is not None:
self._ingest_payload(response)
# In CDN mode the repository already dispatched this exact object
# via _on_feature_update; the identity check there makes the notify
# a no-op. It matters in remote-eval mode, where the repository
# deliberately skips its global callbacks and this is the only
# dispatch point.
self._apply_and_notify(response)

async def load_features_async(self, force_refresh: bool = False) -> None:
if not self._client_key:
Expand All @@ -1169,7 +1182,7 @@ async def load_features_async(self, force_refresh: bool = False) -> None:
)

if features is not None:
self._ingest_payload(features)
self._apply_and_notify(features)

def _features_event_handler(self, features: str) -> None:
decoded = json.loads(features)
Expand All @@ -1180,7 +1193,10 @@ def _features_event_handler(self, features: str) -> None:
key = self._api_host + "::" + self._client_key

if data is not None:
self._ingest_payload(data)
# The streaming path applies the payload itself and never goes
# through the repository's callbacks, so without this listeners
# would miss exactly the updates they exist to observe.
self._apply_and_notify(data)
feature_repo.save_in_cache(key, data, self._cache_ttl)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

def _dispatch_sse_event(self, event_data: Dict[str, Any]) -> None:
Expand Down Expand Up @@ -1255,6 +1271,90 @@ def set_features(self, features: Dict[str, Any]) -> None:
finally:
self._is_updating_features = False

def add_feature_refresh_listener(
self, listener: Callable[[Dict[str, Any]], None]
) -> Callable[[], None]:
"""Register a callable invoked whenever a new feature payload is applied
to this instance, so an app can react to updates without polling.

The listener receives the raw payload dict (``features``, ``savedGroups``,
…). It runs *after* the payload has been applied, so evaluating a feature
from inside the listener already sees the new definitions.

Fires once per refresh — not once per evaluation — for HTTP loads, the
stale-while-revalidate background worker and streaming (SSE) updates.
A listener that raises is logged and skipped; it can't break a refresh.
A listener may trigger a refresh itself: the remaining listeners then
get only the newer payload, never the one it superseded.

Returns a callable that unregisters the listener."""
if listener not in self._feature_refresh_listeners:
self._feature_refresh_listeners.append(listener)

def unsubscribe() -> None:
self.remove_feature_refresh_listener(listener)

return unsubscribe

def remove_feature_refresh_listener(
self, listener: Callable[[Dict[str, Any]], None]
) -> None:
if listener in self._feature_refresh_listeners:
self._feature_refresh_listeners.remove(listener)

def _apply_and_notify(self, payload: Optional[Dict[str, Any]]) -> None:
"""Apply a payload and dispatch it to the refresh listeners as one
unit, under the payload-writer lock.

Notifying outside the lock would let two refresh sources reorder:
one applies A, the other applies and notifies B, then the first
notifies A — so listeners see an older payload last, and a listener
that evaluates sees state that doesn't match the payload it was
handed. The lock is reentrant, and evaluation never takes it (reads
go through the published snapshot), so a listener is free to
evaluate."""
with self._payload_lock:
if payload is not None:
self._ingest_payload(payload)
self._notify_feature_refresh(payload)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None:
"""Dispatch a payload to the refresh listeners, once per distinct
payload object. Call this only after the payload has been applied."""
if payload is None:
# A failed refresh applied nothing, so the payload listeners last
# saw is unchanged. Clearing the marker here would make the next
# cache hit — which returns that same previously-notified object —
# look like a fresh payload and fire listeners a second time.
return
if payload is self._last_refresh_payload:
return
self._last_refresh_payload = payload
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if self._dispatching_refresh:
# A listener started this refresh, on this thread (we hold the
# payload lock). Delivering here would finish the newer payload
# before the outer loop resumes with the older one, so the running
# loop picks it up instead.
return

self._dispatching_refresh = True
try:
while True:
current = self._last_refresh_payload
for listener in list(self._feature_refresh_listeners):
if self._last_refresh_payload is not current:
# Superseded by a refresh from a listener: the rest
# get only the newer payload, never the older one.
break
try:
listener(current)
except Exception:
logger.exception("Error in feature refresh listener")
if self._last_refresh_payload is current:
return
finally:
self._dispatching_refresh = False

@deprecated("getFeatures is deprecated, use get_features instead")
def getFeatures(self) -> Dict[str, Feature]:
return self.get_features()
Expand Down Expand Up @@ -1340,6 +1440,7 @@ def destroy(self, timeout: float = 10) -> None:
# Clear all internal state
try:
self._subscriptions.clear()
self._feature_refresh_listeners.clear()
self._tracked.clear()
if self._deferred_buffer:
self._deferred_buffer.clear()
Expand Down
125 changes: 125 additions & 0 deletions growthbook/growthbook_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
if TYPE_CHECKING:
from .plugins.base import PluginLike
import asyncio
import contextvars
import threading
import time
import traceback
Expand Down Expand Up @@ -48,6 +49,13 @@

logger = logging.getLogger("growthbook.growthbook_client")

# Tokens of the refresh-listener dispatches the current code runs inside. A
# listener (and any task it creates) inherits this context, which is how a
# refresh started from a listener is told apart from a concurrent one.
_active_refresh_dispatches: "contextvars.ContextVar[Tuple[object, ...]]" = contextvars.ContextVar(
"growthbook_active_refresh_dispatches", default=()
)

class SingletonMeta(type):
"""One instance per (class, api_host, client_key). Two GrowthBookClients
talking to different proxies — or one CDN-mode and one remote-eval-mode
Expand Down Expand Up @@ -657,6 +665,17 @@ def __init__(
self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], Union[None, Awaitable[None]]]] = set()
self._subscriptions_lock = threading.Lock()

# Feature refresh listeners (sync or async callables)
self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], Any]] = []
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
self._feature_refresh_lock = threading.Lock()
# Serializes apply-then-notify so concurrent refreshes can't reorder
# listener events; see _feature_update_callback.
self._refresh_order_lock = asyncio.Lock()
# The latest applied payload, and the token of the dispatch currently
# delivering it; see _feature_update_callback.
self._latest_refresh_payload: Optional[Dict[str, Any]] = None
self._refresh_dispatch_token: Optional[object] = None

# Per-attributes-key inflight sticky bucket fetches. Concurrent evals
# with identical attributes coalesce onto one service fetch; distinct
# attributes fetch in parallel. No cross-eval result cache by default
Expand Down Expand Up @@ -810,6 +829,60 @@ def unsubscribe() -> None:
self._subscriptions.discard(callback)
return unsubscribe

def add_feature_refresh_listener(
self, listener: Callable[[Dict[str, Any]], Any]
) -> Callable[[], None]:
"""Register a callable invoked whenever a new feature payload is applied
to this client, so an app can react to updates without polling.

The listener receives the raw payload dict (``features``, ``savedGroups``,
…) and may be a plain function or a coroutine function; coroutines are
awaited. It runs *after* the payload has been applied to the global
context, so evaluating a feature from inside the listener already sees
the new definitions. A listener that raises is logged and skipped.
A listener may update the payload itself (``set_payload`` and so on):
the remaining listeners then get only the newer payload, never the one
it superseded.

Fires on the initial load and on every refresh, whether driven by
streaming (SSE) or HTTP polling. Remote-eval mode emits no events:
payloads there are per-user, so there is no client-wide "definitions
changed" moment to report.

Returns a callable that unregisters the listener."""
with self._feature_refresh_lock:
if listener not in self._feature_refresh_listeners:
self._feature_refresh_listeners.append(listener)

def unsubscribe() -> None:
self.remove_feature_refresh_listener(listener)

return unsubscribe

def remove_feature_refresh_listener(
self, listener: Callable[[Dict[str, Any]], Any]
) -> None:
with self._feature_refresh_lock:
if listener in self._feature_refresh_listeners:
self._feature_refresh_listeners.remove(listener)

async def _notify_feature_refresh(self, payload: Dict[str, Any]) -> None:
"""Dispatch a payload to the refresh listeners. Call only after the
payload has been applied to the global context. Stops once a newer
payload has been applied."""
with self._feature_refresh_lock:
listeners = list(self._feature_refresh_listeners)

for listener in listeners:
if self._latest_refresh_payload is not payload:
return
try:
result = listener(payload)
if asyncio.iscoroutine(result):
await result
except Exception:
logger.exception("Error in feature refresh listener")

def _fire_subscriptions(self, experiment: Experiment[Any], result: Result[Any]) -> None:
"""Thread-safe subscription notifications"""
with self._subscriptions_lock:
Expand Down Expand Up @@ -1185,6 +1258,52 @@ async def _feature_update_callback(self, features_data: Dict[str, Any]) -> None:
logger.warning("Warning: Received empty features data")
return

# Apply and notify as one unit. The ordering lock is distinct from the
# context lock on purpose: evaluation takes that one, so notifying
# under it would deadlock any listener that evaluates. Evaluation
# never takes this one, so holding it across the pair is safe — and it
# is what keeps two overlapping refreshes from notifying out of
# application order (apply A, apply+notify B, notify A).
token = self._refresh_dispatch_token
if token is not None and token in _active_refresh_dispatches.get():
# Started from a listener of the running dispatch, which holds the
# ordering lock: waiting for it would deadlock. Apply only; the
# running loop delivers this payload once the listener returns,
# so it can't be finished before the older one it interrupted.
await self._apply_payload(features_data)
self._latest_refresh_payload = features_data
return
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

async with self._refresh_order_lock:
await self._apply_payload(features_data)
self._latest_refresh_payload = features_data
# Outside the context lock, which _apply_payload has released.
await self._dispatch_feature_refresh()

async def _dispatch_feature_refresh(self) -> None:
"""Deliver the latest applied payload to the refresh listeners. Call
with the ordering lock held.

If a listener applies a newer payload, the remaining listeners get
only the newer one, then delivery starts over with it, so no listener
receives a payload older than one it has already seen or than the
applied state."""
token = object()
self._refresh_dispatch_token = token
reset = _active_refresh_dispatches.set(_active_refresh_dispatches.get() + (token,))
try:
while True:
current = self._latest_refresh_payload
if current is None:
return
await self._notify_feature_refresh(current)
if self._latest_refresh_payload is current:
return
finally:
_active_refresh_dispatches.reset(reset)
self._refresh_dispatch_token = None

async def _apply_payload(self, features_data: Dict[str, Any]) -> None:
async with self._context_lock: # serializes concurrent updaters only
prev = self._global_context
# Mirror JS setPayload: sections absent from the update carry
Expand Down Expand Up @@ -1443,6 +1562,12 @@ async def close(self) -> None:
self._tracked.clear()
with self._subscriptions_lock:
self._subscriptions.clear()
# Listener closures capture application objects; a closed client that
# kept them would hold those alive and, if reinitialized, fire
# callbacks registered in its previous lifecycle.
with self._feature_refresh_lock:
self._feature_refresh_listeners.clear()
self._latest_refresh_payload = None
# Clear context
async with self._context_lock:
self._global_context = None
Expand Down
Loading
Loading