Skip to content

feat: add process-shared feature payload cache with prefetch - #269

Open
vazarkevych wants to merge 6 commits into
mainfrom
feat/shared-payload-cache-prefetch
Open

vazarkevych wants to merge 6 commits into
mainfrom
feat/shared-payload-cache-prefetch

Conversation

@vazarkevych

@vazarkevych vazarkevych commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds an opt-in, process-shared feature payload cache so multiple GBFeaturesRepository
instances configured with the same key share one cached payload and collapse concurrent cold
starts into a single network fetch.

  • Shared payload cache (SharedPayloadCache + SharedFeatureCache coordinator) — a process-wide
    store keyed by (apiHost, clientKey) plus a fingerprint of the decryption key, with a
    stale-while-revalidate read decision: FRESH is served directly, STALE is served and revalidated in
    the background, EXPIRED or a miss is refetched.
  • Single-flight de-duplication (SingleFlight) — concurrent refreshes for the same key collapse
    to one in-flight fetch; followers receive the leader's payload instead of each hitting the network.
  • Prefetch (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, so
per-instance behavior is unchanged. Honored only on the STALE_WHILE_REVALIDATE features-GET path.

Hardening

  • SingleFlight always completes the in-flight future in a finally block, so a leader failing with
    an Error cannot leave followers blocked on get().
  • SingleFlight is re-entrant per thread: a call for a key the current thread is already leading runs
    the action directly instead of waiting on its own unfinished result.
  • A fetched payload is published to the shared cache before refresh callbacks run, so a callback
    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).
  • HTTP 304 refreshes the shared entry's timestamp, so a confirmed-fresh payload is not reclassified
    stale after staleTtl and 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.
  • Background execution is decoupled from RefreshMode.FORCE: the scheduler exposes explicit
    runNow / runInBackground, and the stale background reload revalidates with normal ETag-aware
    semantics instead of bypassing caches.

Public API (all additive)

  • GBFeaturesRepository.builder().sharedCacheEnabled(Boolean) — new builder field. The @Builder
    moves 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)
  • New public class PrefetchOptions (clientKey, apiHost, decryptionKey, skipCache)
  • FeatureRefreshScheduler gains runNow / runInBackground; requestRefresh is kept and
    @Deprecated.

SharedFeatureCache, SharedPayloadCache and SingleFlight are package-private. No new third-party
dependency.

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 loopback HttpServer.

./gradlew build passes on JDK 17.

…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.
@vazarkevych vazarkevych changed the title feat: add process-shared feature payload cache with prefetch and sing… feat: add process-shared feature payload cache with prefetch Oct 16, 2026
@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[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

Volodymyr Nazarkevych 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.
@vazarkevych

Copy link
Copy Markdown
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.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

@andywhite37 andywhite37 added effort:large Substantial review and testing, often across APIs, components, or environments. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:low Can wait because impact or urgency is limited. risk:medium Changes behavior with a bounded impact that needs focused validation. labels Oct 19, 2026
…ache-prefetch

# Conflicts:
#	lib/src/main/java/growthbook/sdk/java/repository/GBFeaturesRepository.java
@vazarkevych

Copy link
Copy Markdown
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.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

This branch has not been deployed

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

Labels

effort:large Substantial review and testing, often across APIs, components, or environments. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:low Can wait because impact or urgency is limited. risk:medium Changes behavior with a bounded impact that needs focused validation.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants