Skip to content

feat: configurable polling interval, per-key pollers, refresh backoff - #173

Open
vazarkevych wants to merge 10 commits into
mainfrom
feat/polling-interval
Open

vazarkevych wants to merge 10 commits into
mainfrom
feat/polling-interval

Conversation

@vazarkevych

@vazarkevych vazarkevych commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

Background feature refresh had four problems:

  • The cache ate the interval (async). Polling went through load_features_async, which returns the cached payload while it's fresh, so any interval shorter than cache_ttl sent no requests. At a 50ms interval with a 60s cache_ttl, 0.6s of polling made 1 request before and 12 after.
  • One poller per process (sync). start_background_refresh() returned early if any refresh thread was running, so a second SDK connection got no background refreshes.
  • No backoff on failure. An unreachable CDN got a request every interval from every process. The usual failure is _fetch_features returning None, not raising, which is why this was easy to miss.
  • No interval validation. Event.wait() and asyncio.sleep() return immediately on a negative delay, so a negative interval was a tight request loop.

What changed

  • Options.polling_interval (seconds, async client, opt-in). Polling then bypasses the cache, and it runs alongside refresh_strategy rather than replacing it, so it works together with SSE:

    GrowthBookClient(Options(
        api_host="https://cdn.growthbook.io",
        client_key="sdk-abc123",
        refresh_strategy=FeatureRefreshStrategy.SERVER_SENT_EVENTS,
        polling_interval=60,
    ))

    A stream blocked by a proxy looks like a stream with no events yet, and polling keeps such an app refreshing. Polling has its own task, and stop_refresh() cancels both. A polled payload superseded by an SSE update during its fetch is dropped, so polling can't roll back newer flags. Remote-eval mode warns and ignores the option, since payloads there are per-user.

  • Per-key pollers (sync): one poller per (api_host, client_key), shared by all instances on that key. destroy() releases the instance's share, and the poller stops when the last instance is destroyed. Calling destroy() twice is safe. stop_background_refresh() takes an optional host and key to stop one poller; with no arguments it stops all of them, as before.

  • Connections stay isolated (sync): feature update callbacks can be registered for an (api_host, client_key), and GrowthBook does. Each connection now receives only its own payloads (they used to be broadcast to every connection in the process). Callbacks registered without a key still receive everything.

  • First instance's settings win: the first instance on a key sets the poller's interval, cache_ttl and decryption key. A later instance with a different interval gets a warning. Async works the same way, since there is one repository per key.

  • Backoff (sync and async): after a failure (None or an exception) the wait doubles from the interval up to 5 minutes or the interval, whichever is longer. Proportional jitter then stretches it by up to 2x, and it resets on the next success. It never goes below the interval and stays bounded however long an outage lasts. In async, an error in the update handler is logged but doesn't count as a failed fetch.

  • Validation: non-positive, non-finite, non-numeric or over-a-day values are rejected with a warning instead of clamped:

    • stale_ttl / refresh_interval: the poller stays off. A stale_ttl above a day used to poll and now doesn't.
    • polling_interval: the client refreshes as if it were unset.
  • The sync client keeps stale_while_revalidate + stale_ttl, which already fetches directly. The README documents it as the equivalent.

  • README: new "Polling" section.

Not included: automatic fallback from SSE to polling. It would start sending requests for every user whose stream is already silently broken, which is a traffic change that shouldn't ride along here. The option gives the same thing explicitly.

How to test

pytest tests/test_growthbook.py tests/test_growthbook_client.py -k "poll or poller or backoff or stale_ttl or background_refresh or update_handler or feature_update_callback or roll_back"

23 new tests:

  • async polling: cache bypass, capped without it, alongside SSE with real fetches, no rollback of an SSE update applied mid-fetch, None fetches back off, handler errors don't, a second polling_interval on the same key warns;
  • sync pollers: per key, connections receiving only their own payloads, unkeyed callbacks still hearing all, shared poller surviving one instance's destroy(), double destroy(), stale leases, a mismatched interval warns, invalid stale_ttl / interval;
  • backoff and validation: growth, cap, reset, never below the interval, no overflow after many failures, NaN and infinity rejected.

Full suite with current main merged: 1967 passed. The 2 cache fixture errors in test_growthbook_client.py also happen on main.

Size

Production code +373 / −75, tests +554 / −12, README +57. About 990 lines, more than half of it tests. If that's too much for one review, the sync part (per-key pollers, isolation, backoff) and the async polling_interval could be split.

Migration

None for existing configs, except a stale_ttl above one day, which now disables background refresh with a warning. Polling at a new interval is opt-in. stop_background_refresh() without arguments and add_feature_update_callback(callback) without a key behave as before.

start_background_refresh() returned early whenever *a* refresh thread was
already running, regardless of which connection it was polling for. The second
SDK connection in a process therefore got no background refreshes at all — it
silently relied on whatever the first key happened to fetch.

Pollers are now tracked per (api_host, client_key), each with its own stop
event. stop_background_refresh() gains optional api_host/client_key arguments
to stop a single connection; with no arguments it still stops everything, which
is what a full teardown wants. GrowthBook.destroy() now passes its own
connection, so destroying one instance no longer kills another instance's
poller.
The sync worker retried at the configured interval forever, so an unreachable
CDN kept costing a request every interval from every process. It now backs off
exponentially from the interval, capped at five minutes, and resets on the
first success.

Jitter is proportional rather than a flat window, so many clients retrying the
same host spread out instead of re-colliding on the next tick. The helper is
shared-shaped (`backoff_delay(base, attempt, cap)`) so the async client's
BackoffStrategy can be folded into it later; it is left alone here to keep this
commit to the failure path that had no backoff at all.

Note the ordinary failure path is `_fetch_features` returning None rather than
raising — the previous code only logged there, which is why the missing backoff
was easy to overlook.
`Options.polling_interval` (seconds) makes the async client refresh features on
a fixed schedule. Previously the built-in HTTP refresh ran at a hardcoded 60s
with no way to configure it.

Two properties make the option mean what it says:

It bypasses the feature cache. The existing loop went through
`load_features_async`, which returns the cached payload when it is still fresh,
so any interval shorter than `cache_ttl` issued no requests at all — it re-read
the cache and slept again. Verified: at a 50ms interval with a 60s cache_ttl,
0.6s of polling made 1 request before this change and 12 after.

It is orthogonal to `refresh_strategy` rather than another strategy value, so
it runs alongside SSE. That is the case worth supporting: a stream blocked by a
proxy is indistinguishable from a stream with no events yet, and polling is
what keeps such an app refreshing. Enabling it is opt-in, so no existing
deployment changes its traffic on upgrade.

Out-of-range values are rejected with a warning rather than clamped.
`Event.wait()` and `asyncio.sleep()` both return immediately on a negative
delay, so silently reinterpreting a typo as "poll as fast as possible" would
turn a config slip into a request flood; leaving polling off and saying so is
the safer failure.

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

The sync class keeps `stale_while_revalidate` + `stale_ttl`, which already
fetches directly rather than through the cache; it is documented as the
equivalent rather than given a second spelling.
…nterval

- Polling gets its own task (`_poll_task`). `_start_sse_refresh` had already
  set `_refresh_task`, so with SSE + `polling_interval` the HTTP loop returned
  immediately and never polled. `stop_refresh` now cancels and awaits both.
- The async loop treated a `None` fetch (the ordinary failure path) as
  success and reset the backoff. Both `None` and exceptions now count as
  failures and use `backoff_delay(interval, failures)`, the same helper as
  the sync worker, instead of `BackoffStrategy`, whose 1s start would retry
  faster than the configured interval.
- `backoff_delay` clipped below `base` when the interval exceeded the
  300s cap; the cap is now `max(cap, base)`.
- The SSE + polling test stubs only the network and asserts fetches happen.
destroy() stopped the poller for every instance on the same key, so
destroying a per-request instance stopped refreshes for a long-lived one.
Instances now take a lease on the shared poller and it stops when the last
lease is released; a lease on a poller that was hard-stopped since can't
stop its replacement, and a second destroy() is a no-op.

stale_ttl is the sync poller's interval and was used unchecked, so
stale_ttl=-1 was a tight request loop. It now goes through the same
validation as polling_interval: out-of-range values log a warning and
leave the poller off.
…er errors out of backoff

- backoff_delay raised OverflowError once failures reached 1024
  (base * 2**n no longer fits a float). After a multi-day outage or a
  wrong client key the sync worker then spun without waiting and the
  async poll task died. Cap the exponent.
- Async polling counted an exception from the update handler as a failed
  fetch and backed off although the CDN answered. Log it separately.
- Instances on one key share a poller, so a later instance's interval was
  silently ignored (sync and async). Warn when it differs and document
  that the first instance's settings apply.
- README: describe the real backoff range (jitter up to 2x), what an
  invalid polling_interval falls back to, and that stale_ttl over a day
  no longer polls.
@greptile-apps

greptile-apps Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; the callback-removal race is fixed.

Reviews (4) · Last reviewed commit: "fix: guard feature update callback chang..." · Reviewed by Greptile

Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook_client.py Resolved
Comment thread growthbook/common_types.py Resolved
…ck SSE, reject NaN intervals

- The feature update callback list is shared by every connection in the
  process, and each key's poller broadcast to all of it, so two SDK
  connections kept overwriting each other's flags. Callbacks can now be
  registered for an (api_host, client_key); GrowthBook does, and pollers
  and loads notify with their key. Unkeyed callbacks still hear everything.
- With SSE and polling, an inline SSE payload applied while a poll's fetch
  was in flight could be overwritten by the poll's older response. Count
  applied updates and drop a polled payload superseded during its fetch.
- validate_polling_interval accepted NaN (both range checks are False),
  and Event.wait(nan) doesn't wait. Reject non-finite values.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook.py Resolved
Routing callbacks by connection went through a dict keyed by the callback,
so an unhashable callable (e.g. a non-frozen dataclass with __call__)
raised TypeError in notify and stopped every later callback. Store each
callback with its connection as a pair in the existing list instead; add
and remove keep the identity-then-equality match of the old `in` check.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook.py Resolved
add/remove find an entry and then change it by index. Instances destroyed
from two threads could shift the list in between, deleting a live client's
callback or failing with IndexError; the list.remove() this replaced did
the search and delete in one call. Guard both with a lock and snapshot the
list under it before notifying.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant