Repository navigation
feat: add process-shared feature payload cache with prefetch - #269
Open
vazarkevych wants to merge 6 commits into
Open
vazarkevych wants to merge 6 commits into
vazarkevych wants to merge 6 commits into
Conversation
…le-flight de-duplication Opt-in process-shared payload cache so repositories configured with the same (apiHost, clientKey) share one cached entry and collapse concurrent cold starts into a single network fetch. Ported from the internal shared-payload-cache branch, adapted to public main. - SharedPayloadCache + SharedFeatureCache coordinator: process-wide store keyed by (apiHost, clientKey) plus a decryption-key fingerprint, with a stale-while-revalidate read decision (FRESH served, STALE served and revalidated in background, EXPIRED/miss refetched). - SingleFlight: concurrent refreshes for the same key collapse to one in-flight fetch; the in-flight future always completes in a finally block so a leader Error cannot block followers forever. - Prefetch: GrowthBook.prefetchPayload / GBFeaturesRepository.prefetchPayload warm the shared cache before the first evaluation (serverless cold start). - 304 touches the shared entry timestamp so a confirmed-fresh payload is not reclassified stale and needlessly revalidated by other instances. - shutdown() releases the repository-owned HTTP client (dispatcher executor, pool, response cache); a caller-supplied client is left running. - FeatureRefreshScheduler exposes runNow/runInBackground, decoupling execution mode from RefreshMode; requestRefresh kept and deprecated for compatibility. Opt-in via builder.sharedCacheEnabled(true); defaults off, so per-instance behavior is unchanged. Honored only on the STALE_WHILE_REVALIDATE path. Backward compatible: existing positional constructors are unchanged; a new @builder constructor adds sharedCacheEnabled and a private terminal constructor assigns the final fields. No new third-party dependency. Adapted for public main: dropped the internal requestTimeout, initialPayload, and custom-header coupling absent here; the cache key omits custom headers; and the SSE-only on-disk cache clear is preserved (not cleared for polling repos). Tests are ported separately in a follow-up commit.
[Medium impact] The latest changes appear safe to merge and address the outstanding startup hang. Reviews (5) · Last reviewed commit: "fix: publish the shared payload before r..." · Reviewed by Greptile |
added 2 commits
October 16, 2026 11:32
…h scheduler Port the internal test suite for the shared payload cache, adapted to public main. 55 tests across six classes, green on JDK 17. - SingleFlightTest: de-duplication, leader-Error still completes the in-flight future, concurrent followers receive the leader result. - SharedPayloadCacheTest: FRESH/STALE/EXPIRED transitions, touch, LRU eviction, Settings validation (staleTtl <= maxAge, non-negative, maxEntries >= 1). - SharedFeatureCacheTest: deterministic read-decision matrix via an injected clock, plus key fingerprinting isolation. - GBFeaturesRepositorySharedCacheTest: one-fetch sharing across instances, concurrent de-duplication, prefetch warm-up, distinct-key isolation, stale-served-and-revalidated, expired-refetch, prefetch skipCache. - GBFeaturesRepositoryShutdownTest: a repository-owned client is released on shutdown; a caller-supplied client is left running. - FeatureRefreshSchedulerTest: inline vs background execution, mode pass-through, exception swallowing, null guards. Dropped three internal tests whose behaviors are absent from public main: different/identical custom request headers (no custom headers here) and follower-with-initialPayload adoption (no initialPayload bootstrap here); the underlying concurrent-collapse path stays covered by the de-dup test.
…d entries Address code-review findings on the shared payload cache: - triggerBackgroundSharedReload discarded the de-duplicated fetch result, so an instance whose background reload collapsed onto another leader kept serving stale flags until its next poll. It now adopts the returned payload when it did not perform the fetch, mirroring the cold-start path. - seedFromSharedPayload notified only the modern listener channel; onResponseJson with isFromCache=true skips onRefreshSuccess, so legacy FeatureRefreshCallback subscribers missed the payload on a cache hit or cold-start follower. It now notifies the legacy channel too. - fetchIntoSharedCache returned the shared payload unconditionally after a refresh, so a leader that fell back to its own disk cache on a failed fetch could hand an expired payload to followers past maxAge. It now returns a payload only when the entry is within maxAge (FRESH or STALE), else null so each follower uses its own fallback. This also fixes a staleTtl=0 interaction where a just-published payload would otherwise never be shared. - Removed redundant inline comments on requestFeatureRefresh in both repositories per the repository comment guide. New tests: backgroundReloadFollowerAdoptsRefreshedPayload and sharedCacheHitNotifiesLegacyCallback. Full :lib:test green on JDK 17.
Collaborator
Author
|
@greptile review |
Address review findings on GBFeaturesRepositorySharedCacheTest: - Remove Thread.sleep-based overlap. The server now holds its response on a latch, and tests release it only once both callers are provably inside the single-flight, awaited via SingleFlight.participantCount(). This makes the de-duplication and background-reload tests deterministic — a slow worker can no longer send an extra request and fail the count assertion. - tearDown no longer swallows shutdown failures: it tears down every repository, the server, and the server executor, then rethrows the first failure. - The HttpServer executor is kept in a field and shut down in tearDown so its worker threads do not accumulate across tests. SingleFlight gains a participantCount() (leaders plus waiting followers) and SharedFeatureCache a fetchParticipantCount() delegate, used only to gate the tests deterministically. WireMock is intentionally not used here: it cannot hold a response until N concurrent callers have arrived, which the single-flight gating requires; the loopback HttpServer follows the existing SSE/remote-eval test precedent. Full :lib:test is green on JDK 17.
Collaborator
Author
|
@greptile review |
…ache-prefetch # Conflicts: # lib/src/main/java/growthbook/sdk/java/repository/GBFeaturesRepository.java
Collaborator
Author
|
@greptile review |
…same-key init cannot deadlock A refresh callback that synchronously initialized another repository for the same key missed the shared cache and waited on the in-flight fetch that was invoking it. Publish the payload before applyPayload runs callbacks, and make SingleFlight re-entrant per thread so a skipCache call on the leader's thread runs directly instead of waiting on itself.
Collaborator
Author
|
@greptile review |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds an opt-in, process-shared feature payload cache so multiple
GBFeaturesRepositoryinstances configured with the same key share one cached payload and collapse concurrent cold
starts into a single network fetch.
SharedPayloadCache+SharedFeatureCachecoordinator) — a process-widestore keyed by
(apiHost, clientKey)plus a fingerprint of the decryption key, with astale-while-revalidate read decision: FRESH is served directly, STALE is served and revalidated in
the background, EXPIRED or a miss is refetched.
SingleFlight) — concurrent refreshes for the same key collapseto one in-flight fetch; followers receive the leader's payload instead of each hitting the network.
GrowthBook.prefetchPayload(PrefetchOptions)/GBFeaturesRepository.prefetchPayload)— warms the shared cache before the first evaluation (boot time / serverless cold start), so the
first real request is served from cache with no network round trip.
Enabled via
GBFeaturesRepository.builder().sharedCacheEnabled(true); off by default, soper-instance behavior is unchanged. Honored only on the
STALE_WHILE_REVALIDATEfeatures-GET path.Hardening
SingleFlightalways completes the in-flight future in afinallyblock, so a leader failing withan
Errorcannot leave followers blocked onget().SingleFlightis re-entrant per thread: a call for a key the current thread is already leading runsthe action directly instead of waiting on its own unfinished result.
that synchronously initializes another repository for the same key is served from the cache instead
of waiting on the fetch that is invoking it (previously a startup deadlock).
stale after
staleTtland needlessly revalidated by every other instance.shutdown()releases the repository-owned HTTP client (dispatcher executor, connection pool,response cache); a caller-supplied client is left running. The persisted feature cache is not
cleared, matching
main.RefreshMode.FORCE: the scheduler exposes explicitrunNow/runInBackground, and the stale background reload revalidates with normal ETag-awaresemantics instead of bypassing caches.
Public API (all additive)
GBFeaturesRepository.builder().sharedCacheEnabled(Boolean)— new builder field. The@Buildermoves to a new constructor that adds the flag; existing positional constructors are unchanged.
static void GBFeaturesRepository.prefetchPayload(PrefetchOptions)static void GBFeaturesRepository.configureSharedCache(Duration staleTtl, Duration maxAge, int maxEntries)static void GrowthBook.prefetchPayload(PrefetchOptions)public class PrefetchOptions(clientKey,apiHost,decryptionKey,skipCache)FeatureRefreshSchedulergainsrunNow/runInBackground;requestRefreshis kept and@Deprecated.SharedFeatureCache,SharedPayloadCacheandSingleFlightare package-private. No new third-partydependency.
Tests
SingleFlightTest,SharedPayloadCacheTest,SharedFeatureCacheTest,GBFeaturesRepositorySharedCacheTest,GBFeaturesRepositoryShutdownTest,FeatureRefreshSchedulerTest. Concurrency is gated with latches and single-flight participant counts —no
Thread.sleep. Cross-instance tests assert real request counts against a loopbackHttpServer../gradlew buildpasses on JDK 17.