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
143 changes: 137 additions & 6 deletions growthbook/growthbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ def decrypt(encrypted_str: str, key_str: str) -> str:

return bytestring.decode("utf-8")


def _same_payload(a: Any, b: Any) -> bool:
"""Structural equality that, unlike ==, keeps JSON values of different
types apart: True == 1, False == 0 and 1 == 1.0 in Python, but they are
different settings. Values of different types are never the same, so an
unexpected type at worst fires listeners for an unchanged payload."""
if a is b:
return True
if type(a) is not type(b):
return False
if isinstance(a, dict):
return a.keys() == b.keys() and all(_same_payload(v, b[k]) for k, v in a.items())
if isinstance(a, (list, tuple)):
return len(a) == len(b) and all(_same_payload(x, y) for x, y in zip(a, b))
return bool(a == b)


class AbstractFeatureCache(ABC):
@abstractmethod
def get(self, key: str) -> Optional[Dict[str, Any]]:
Expand Down Expand Up @@ -1024,6 +1041,16 @@ 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]] = []
# The last payload dispatched to listeners. load_features() returns the
# cached payload on every hit, so a hit must not count as a refresh:
# _notify_feature_refresh compares against this by identity (the
# in-memory cache returns the same object) and then by type-strict
# content (custom caches, e.g. Redis, decode a new dict on every hit).
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 @@ -1102,8 +1129,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 @@ -1169,7 +1195,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 @@ -1188,7 +1219,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 @@ -1199,8 +1230,19 @@ def _features_event_handler(self, features: str) -> None:
key = self._api_host + "::" + self._client_key

if data is not None:
self._ingest_payload(data)
feature_repo.save_in_cache(key, data, self._cache_ttl)
# Cache first: a listener may call load_features(), which must get
# this payload from the cache, not the previous one it would then
# reapply over the update. A failed write (e.g. a custom cache that
# is down) must not cost us the update: the stream doesn't retry
# the event, so apply it anyway.
try:
feature_repo.save_in_cache(key, data, self._cache_ttl)
except Exception:
logger.exception("Could not cache the streamed payload; applying it anyway")
# 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)

def _dispatch_sse_event(self, event_data: Dict[str, Any]) -> None:
event_type = event_data.get('type')
Expand Down Expand Up @@ -1274,6 +1316,94 @@ 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 _same_payload(payload, self._last_refresh_payload):
# Same object, or a copy of it from a cache that decodes on every
# hit. Treating a copy as new would fire listeners on every
# load_features(), and a listener that loads features itself would
# keep the delivery loop below from ever finishing.
return
self._last_refresh_payload = payload
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 @@ -1376,6 +1506,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
Loading
Loading