From b450fd95c2f389db983221c37307a89557cbd091 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:26:25 +0000 Subject: [PATCH 1/7] docs: document high performance flag targeting and fallback providers --- README.md | 147 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c4ceed7..b972f98 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,8 @@ Initialization waits for the first flag definitions to load. Subsequent flag rea local and in-memory. If Reflag can't be reached at startup, the client doesn't raise. Instead, -`client.status` is `"degraded"` and flag reads return their defaults. Check +`client.status` is `"degraded"` and flag reads return their defaults, or `"fallback"` if a +[fallback provider](#fallback-providers) supplied saved definitions. Check `client.status` in a health check if you need to know whether definitions are loaded. ### Async applications @@ -99,6 +100,150 @@ context, use `client.bind(context, telemetry=False)`. Keep your secret key on the server, never in browser code. +## High performance flag targeting + +The client downloads flag definitions, including their targeting rules, when it +initializes. `get_flag()` and `get_flags()` then evaluate those rules locally against the +bound context. They make no network requests and never block on Reflag, so flag reads +are fast enough for hot code paths. + +Definitions are kept up to date in the background: + +- **Push (default).** The client listens for updates from Reflag over server-sent events + and refetches definitions as soon as a flag changes. +- **Polling.** Set `sync_mode="polling"` to refetch every `poll_interval` seconds + (default 60) instead, for example when long-lived streaming connections aren't + allowed. + +Refetches use ETags, so unchanged definitions aren't downloaded again, and they're spaced +at least `min_refresh_interval` seconds (default 1) apart. If a refresh fails, the client +keeps serving the last definitions it loaded. + +Telemetry is sent in the background too. Context updates and flag checks are queued in +memory, identical events within 60 seconds are deduplicated, and the queue is sent in +batches of up to `batch_size` events (default 100) at least every `batch_interval` +seconds (default 10). If more than `max_pending_events` (default 10,000) are waiting, new +events are dropped and counted in `client.dropped_events`. Closing the client sends any +remaining events, waiting at most `shutdown_timeout` seconds (default 5). Call +`client.flush()` (`await client.flush()` with `AsyncClient`) to send them sooner. + +```python +from reflag import Client + +client = Client( + sync_mode="polling", + poll_interval=30, + batch_size=500, + batch_interval=5, +) +``` + +## Fallback providers + +A fallback provider lets new processes start with saved flag definitions when Reflag is +unreachable, for example during an outage or a network problem at deploy time. + +Reflag stays the source of truth: + +1. At startup the client always fetches live definitions first. +2. Whenever it fetches new definitions, it saves a snapshot through the provider in the + background. Saving never delays flag reads. +3. Only if the first live fetch fails, after its retries, does the client load the saved + snapshot. `client.status` is then `"fallback"`. +4. The client keeps trying Reflag in the background. Once live definitions load, they + replace the fallback and `client.status` becomes `"ready"`. + +A running client never needs its provider to survive an outage: it keeps the last +definitions it loaded in memory. Fallback providers aren't used in offline mode. + +The first live fetch retries up to `fetch_retries` times (default 3), with each attempt +limited to `fetch_timeout` seconds (default 10). Lower these to start from the fallback +sooner when Reflag can't be reached. + +### Static fallback + +`StaticFallback` gives every context the same fixed values. Values can be Booleans or any +JSON value: + +```python +from reflag import Client, StaticFallback + +client = Client( + fallback_provider=StaticFallback( + {"new-dashboard": False, "dashboard-settings": {"theme": "light"}} + ), +) +``` + +Static values aren't targeted, and they're left out of +[bootstrap state](#bootstrapping-browser-clients) because they carry no visibility +information. + +### File fallback + +`FileFallback` saves the latest definitions to a JSON file in a directory and loads them +on startup. The directory is created with owner-only permissions if it doesn't exist. + +```python +from reflag import Client, FileFallback + +client = Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) +``` + +Each snapshot file is named after a hash of the secret key and API URL, so environments +don't overwrite each other's snapshots. Files are replaced atomically, so a reader never +sees a partially written snapshot. Use a directory on persistent storage, or the +snapshot is lost when the container or machine is replaced. Several processes can share a +directory; the last one to save wins, which is harmless because they save the same +definitions. + +### Custom providers + +To store snapshots elsewhere, such as Redis, S3 or your database, implement `load` and +`save`. `namespace` is a hash that identifies the environment; use it as the storage key. +Treat the snapshot as an opaque JSON object: store it as is and return it unchanged. + +```python +import json +from collections.abc import Mapping + +from redis import Redis + +from reflag import Client + + +class RedisFallback: + def __init__(self, redis: Redis) -> None: + self._redis = redis + + def load(self, namespace: str) -> Mapping[str, object] | None: + value = self._redis.get(f"reflag:flags-fallback:{namespace}") + return None if value is None else json.loads(value) + + def save(self, namespace: str, snapshot: Mapping[str, object]) -> None: + self._redis.set(f"reflag:flags-fallback:{namespace}", json.dumps(snapshot)) + + +client = Client(fallback_provider=RedisFallback(Redis.from_url("redis://localhost:6379"))) +``` + +Return `None` from `load` when there is no snapshot yet. If `load` or `save` raises, the +client logs a warning and continues without the fallback. Bound any I/O with a timeout: +`load` runs during startup, so a slow provider delays initialization. + +`AsyncClient` accepts the same synchronous providers, which it runs in a worker thread, +and also providers with `async def load` and `async def save`. + +### Testing fallback startup + +Run your application once with a working connection, so it saves a snapshot. Then +restart it with the same configuration, but with `HTTPS_PROXY=http://127.0.0.1:9` set +so that requests to Reflag fail. The client starts from the snapshot, and +`client.status` is `"fallback"`. + +Don't change `api_base_url` or `REFLAG_API_BASE_URL` to simulate an outage: the +namespace includes the API URL, so the client would look for a different snapshot. + ## Testing In offline mode the client needs no secret key, makes no network requests and sends no From f124e2f318dc31dc664c2ab3ce738f4552ff74af Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:56:13 +0000 Subject: [PATCH 2/7] docs: tighten flag read performance wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b972f98..e780bd2 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ Keep your secret key on the server, never in browser code. The client downloads flag definitions, including their targeting rules, when it initializes. `get_flag()` and `get_flags()` then evaluate those rules locally against the bound context. They make no network requests and never block on Reflag, so flag reads -are fast enough for hot code paths. +are fast even for hot code paths. Definitions are kept up to date in the background: From 52bb410990ff4cfc3276aef272cfd817b468c743 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:57:16 +0000 Subject: [PATCH 3/7] docs: shorten performance and fallback sections --- README.md | 115 ++++++++---------------------------------------------- 1 file changed, 17 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index e780bd2..72da0b1 100644 --- a/README.md +++ b/README.md @@ -102,68 +102,25 @@ Keep your secret key on the server, never in browser code. ## High performance flag targeting -The client downloads flag definitions, including their targeting rules, when it -initializes. `get_flag()` and `get_flags()` then evaluate those rules locally against the -bound context. They make no network requests and never block on Reflag, so flag reads -are fast even for hot code paths. - -Definitions are kept up to date in the background: - -- **Push (default).** The client listens for updates from Reflag over server-sent events - and refetches definitions as soon as a flag changes. -- **Polling.** Set `sync_mode="polling"` to refetch every `poll_interval` seconds - (default 60) instead, for example when long-lived streaming connections aren't - allowed. - -Refetches use ETags, so unchanged definitions aren't downloaded again, and they're spaced -at least `min_refresh_interval` seconds (default 1) apart. If a refresh fails, the client -keeps serving the last definitions it loaded. - -Telemetry is sent in the background too. Context updates and flag checks are queued in -memory, identical events within 60 seconds are deduplicated, and the queue is sent in -batches of up to `batch_size` events (default 100) at least every `batch_interval` -seconds (default 10). If more than `max_pending_events` (default 10,000) are waiting, new -events are dropped and counted in `client.dropped_events`. Closing the client sends any -remaining events, waiting at most `shutdown_timeout` seconds (default 5). Call -`client.flush()` (`await client.flush()` with `AsyncClient`) to send them sooner. +The client downloads flag definitions when it initializes. `get_flag()` and `get_flags()` +then evaluate flags locally against the bound context, so flag reads make no network +requests and are fast even for hot code paths. -```python -from reflag import Client - -client = Client( - sync_mode="polling", - poll_interval=30, - batch_size=500, - batch_interval=5, -) -``` +The client keeps definitions up to date in the background. Telemetry is batched and +deduplicated in the background too. Closing the client sends pending events; call +`flush()` to send them sooner. ## Fallback providers -A fallback provider lets new processes start with saved flag definitions when Reflag is -unreachable, for example during an outage or a network problem at deploy time. +A fallback provider saves the latest flag definitions to durable storage, so a new process +can still start if Reflag is unreachable during startup. -Reflag stays the source of truth: +Reflag remains the source of truth. The client always fetches live definitions first and +saves a snapshot through the provider after each update. It loads the saved snapshot only +if that first fetch fails, and `client.status` is then `"fallback"` until live definitions +load. Without a provider, a running client still keeps its last definitions in memory. -1. At startup the client always fetches live definitions first. -2. Whenever it fetches new definitions, it saves a snapshot through the provider in the - background. Saving never delays flag reads. -3. Only if the first live fetch fails, after its retries, does the client load the saved - snapshot. `client.status` is then `"fallback"`. -4. The client keeps trying Reflag in the background. Once live definitions load, they - replace the fallback and `client.status` becomes `"ready"`. - -A running client never needs its provider to survive an outage: it keeps the last -definitions it loaded in memory. Fallback providers aren't used in offline mode. - -The first live fetch retries up to `fetch_retries` times (default 3), with each attempt -limited to `fetch_timeout` seconds (default 10). Lower these to start from the fallback -sooner when Reflag can't be reached. - -### Static fallback - -`StaticFallback` gives every context the same fixed values. Values can be Booleans or any -JSON value: +Static fallbacks can contain Boolean or JSON values: ```python from reflag import Client, StaticFallback @@ -175,14 +132,7 @@ client = Client( ) ``` -Static values aren't targeted, and they're left out of -[bootstrap state](#bootstrapping-browser-clients) because they carry no visibility -information. - -### File fallback - -`FileFallback` saves the latest definitions to a JSON file in a directory and loads them -on startup. The directory is created with owner-only permissions if it doesn't exist. +File fallback: ```python from reflag import Client, FileFallback @@ -190,18 +140,9 @@ from reflag import Client, FileFallback client = Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) ``` -Each snapshot file is named after a hash of the secret key and API URL, so environments -don't overwrite each other's snapshots. Files are replaced atomically, so a reader never -sees a partially written snapshot. Use a directory on persistent storage, or the -snapshot is lost when the container or machine is replaced. Several processes can share a -directory; the last one to save wins, which is harmless because they save the same -definitions. - -### Custom providers - -To store snapshots elsewhere, such as Redis, S3 or your database, implement `load` and -`save`. `namespace` is a hash that identifies the environment; use it as the storage key. -Treat the snapshot as an opaque JSON object: store it as is and return it unchanged. +To store snapshots elsewhere, such as Redis or S3, implement `load` and `save`. Use +`namespace` as the storage key, and store the snapshot unchanged. `AsyncClient` also +accepts providers with `async` methods. ```python import json @@ -209,8 +150,6 @@ from collections.abc import Mapping from redis import Redis -from reflag import Client - class RedisFallback: def __init__(self, redis: Redis) -> None: @@ -222,28 +161,8 @@ class RedisFallback: def save(self, namespace: str, snapshot: Mapping[str, object]) -> None: self._redis.set(f"reflag:flags-fallback:{namespace}", json.dumps(snapshot)) - - -client = Client(fallback_provider=RedisFallback(Redis.from_url("redis://localhost:6379"))) ``` -Return `None` from `load` when there is no snapshot yet. If `load` or `save` raises, the -client logs a warning and continues without the fallback. Bound any I/O with a timeout: -`load` runs during startup, so a slow provider delays initialization. - -`AsyncClient` accepts the same synchronous providers, which it runs in a worker thread, -and also providers with `async def load` and `async def save`. - -### Testing fallback startup - -Run your application once with a working connection, so it saves a snapshot. Then -restart it with the same configuration, but with `HTTPS_PROXY=http://127.0.0.1:9` set -so that requests to Reflag fail. The client starts from the snapshot, and -`client.status` is `"fallback"`. - -Don't change `api_base_url` or `REFLAG_API_BASE_URL` to simulate an outage: the -namespace includes the API URL, so the client would look for a different snapshot. - ## Testing In offline mode the client needs no secret key, makes no network requests and sends no From 9cd94c2e553816f16fdf4be83123a0aa2423018e Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:24:18 +0000 Subject: [PATCH 4/7] docs: initialize clients in fallback examples --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 72da0b1..0bd1808 100644 --- a/README.md +++ b/README.md @@ -125,11 +125,12 @@ Static fallbacks can contain Boolean or JSON values: ```python from reflag import Client, StaticFallback -client = Client( +with Client( fallback_provider=StaticFallback( {"new-dashboard": False, "dashboard-settings": {"theme": "light"}} ), -) +) as client: + settings = client.get_flag("dashboard-settings", default={}) ``` File fallback: @@ -137,7 +138,8 @@ File fallback: ```python from reflag import Client, FileFallback -client = Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) +with Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) as client: + enabled = client.get_flag("new-dashboard") ``` To store snapshots elsewhere, such as Redis or S3, implement `load` and `save`. Use From f4d9cd85f6155a92512f2ad19525a16eae90790e Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:31:04 +0000 Subject: [PATCH 5/7] docs: document the file fallback single-writer requirement --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bd1808..d88965c 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,9 @@ with Client( settings = client.get_flag("dashboard-settings", default={}) ``` -File fallback: +For file fallback, use a private, persistent directory writable by the app. Allow only +one writer per snapshot. If workers would share a snapshot, give each writer its own +directory so a late save cannot overwrite newer definitions. ```python from reflag import Client, FileFallback From cbc834a342875638b3536cad631a6f20ac0e30d0 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:32:02 +0000 Subject: [PATCH 6/7] docs: recommend fallback options for multiple workers --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d88965c..fe402e7 100644 --- a/README.md +++ b/README.md @@ -133,9 +133,10 @@ with Client( settings = client.get_flag("dashboard-settings", default={}) ``` -For file fallback, use a private, persistent directory writable by the app. Allow only -one writer per snapshot. If workers would share a snapshot, give each writer its own -directory so a late save cannot overwrite newer definitions. +Use `FileFallback` when a single process writes the snapshot. Choose a private, +persistent directory writable by the app. For multiple workers, use `StaticFallback` +for fixed values or a shared provider that prevents older snapshots from replacing +newer ones. ```python from reflag import Client, FileFallback @@ -148,6 +149,9 @@ To store snapshots elsewhere, such as Redis or S3, implement `load` and `save`. `namespace` as the storage key, and store the snapshot unchanged. `AsyncClient` also accepts providers with `async` methods. +The Redis example below assumes one writer. To share it across workers, compare +`flagStateVersion` and write the snapshot in one atomic operation. + ```python import json from collections.abc import Mapping From 496556c26454c8401927bb93116ccadd5fb1b5b4 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:35:03 +0000 Subject: [PATCH 7/7] docs: defer shared fallback provider guidance --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index fe402e7..0bd1808 100644 --- a/README.md +++ b/README.md @@ -133,10 +133,7 @@ with Client( settings = client.get_flag("dashboard-settings", default={}) ``` -Use `FileFallback` when a single process writes the snapshot. Choose a private, -persistent directory writable by the app. For multiple workers, use `StaticFallback` -for fixed values or a shared provider that prevents older snapshots from replacing -newer ones. +File fallback: ```python from reflag import Client, FileFallback @@ -149,9 +146,6 @@ To store snapshots elsewhere, such as Redis or S3, implement `load` and `save`. `namespace` as the storage key, and store the snapshot unchanged. `AsyncClient` also accepts providers with `async` methods. -The Redis example below assumes one writer. To share it across workers, compare -`flagStateVersion` and write the snapshot in one atomic operation. - ```python import json from collections.abc import Mapping