Installation
Gradle
To install in a Gradle project, add Jitpack to your repositories, and then add the dependency with the latest version to your project’s dependencies.Maven
To install in a Maven project, add Jitpack to your repositories:Usage
There are two main approaches to using the GrowthBook Java SDK:- Enhanced Client (Recommended) - For better performance with multi-context support
- Traditional per-request approach - Create a new context and SDK instance per request
Enhanced Client (Recommended)
Available starting in version 0.9.0 For improved performance and better resource management, especially in web applications, use the enhanced client pattern. This approach allows you to reuse a single client instance across multiple requests while providing different user contexts for each evaluation while calling the feature methods likeisOn().
This GrowthBookClient instance is decoupled from the GBContext, creates a singleton featureRepository based on your refreshStrategy and uses the latest features at the time of
evaluation, all managed internally.
Basic Enhanced Client Usage
Configuring the client with Options
TheOptions builder configures the GrowthBookClient. apiHost and clientKey are required. apiHost must use http or https; a host without a scheme is treated as https.
Configuration validation
GrowthBookClient.initialize() validates Options before it fetches features. OptionsValidator.validate(options) throws InvalidOptionsException (an IllegalArgumentException) and lists every problem on getViolations(). initialize() catches that exception, logs it, and returns false.
Checks include:
apiHostis present and useshttporhttps(a host without a scheme is treated ashttps)clientKeyis presentswrTtlSecondsis greater than0when setbackgroundFetchIntervalis not negative when setremoteEvalCacheTtlSecondsis greater than0when set- Cache settings do not conflict (
CacheMode.CUSTOMwithout acacheManager, or acacheManagerwhile caching is disabled) - Remote evaluation constraints, listed under Remote Evaluation
Using the Enhanced Client with Different User Contexts
Thread Safety Note
While the enhanced client is designed for concurrent use, full concurrency support is still being refined. For high-concurrency applications, consider:- Using connection pooling for database-backed sticky bucket services
- Implementing proper synchronization for custom tracking callbacks
- Testing thoroughly under expected load conditions
Traditional Usage
For new projects, we recommend using the Enhanced Client instead for better performance. There are 2 steps to initializing the traditional GrowthBook SDK:- Create a GrowthBook context
GBContextwith the features JSON and the user attributes - Create the
GrowthBookSDK class with the context
GrowthBook context
The GrowthBook contextGBContext can be created either by implementing the builder class, available at GBContext.builder(), or by using the GBContext constructor.
Using the GBContext builder
The builder is the easiest to use way to construct aGBContext, allowing you to provide as many or few arguments as you’d like. All fields mentioned above are available via the builder.
HttpClient recommendationThe above example uses
java.net.http.HttpClient which, depending on your web framework, may not be the best option, in which case it is recommended to use a networking library more suitable for your implementation.Using the GBContext constructor
You can also useGBContext constructor if you prefer, which will require you to pass all arguments explicitly.
Features
The features JSON is equivalent to thefeatures property that is returned from the SDK Connection endpoint.
- You can read more about features here
- You can see an example features JSON here
Attributes
Attributes are a JSON string. You can specify attributes about the current user and request. Here’s an example:Context#attributesJson or GrowthBook#setAttributes. This will completely overwrite the attributes object with whatever you pass in. Also, be aware that changing attributes may change the assigned feature values. This can be disorienting to users if not handled carefully.
Secure Attributes
When secure attribute hashing is enabled, all targeting conditions in the SDK payload referencing attributes with datatypesecureString or secureString[] will be anonymized via SHA-256 hashing. This allows you to safely target users based on sensitive attributes. You must enable this feature in your SDK Connection for it to take effect.
If your SDK Connection has secure attribute hashing enabled, you will need to manually hash any secureString or secureString[] attributes that you pass into the GrowthBook SDK.
To hash an attribute, use a cryptographic library with SHA-256 support, and compute the SHA-256 hashed value of your attribute plus your organization’s secure attribute salt.
Using Features
Every feature has a “value” which is assigned to a user. This value can be any JSON data type. If a feature doesn’t exist, the value will benull.
There are 4 main methods for evaluating features.
GrowthBookClient methods take a UserContext. On that client, getFeatureValue and evalFeature also take a Class<T>, such as String.class. GrowthBook.evalFeature takes a Class<T> as well. The primitive GrowthBook.getFeatureValue overloads still infer the type from defaultValue.
isOn() / isOff()
These methods return a boolean for truthy and falsy values. Only the following values are considered to be “falsy”:nullfalse""0
isOn() will return true and isOff() will return false. If the value is “falsy”, then the opposite values will be returned.
getFeatureValue(featureKey, defaultValue)
This method has a variety of overloads to help with casting values to primitive and complex types. In short, the type of thedefaultValue argument will determine the return type of the function.
See the Java Docs for more information.
See the unit tests for example implementations including type casting for all above-mentioned methods.
evalFeature(String)
TheevalFeature method returns a FeatureResult<T> object with more info about why the feature was assigned to the user. The T type corresponds to the value type of the feature. In the above example, T is Float.
FeatureResult<T> has the following getters. getValue() returns the raw evaluated value as Object, so cast it yourself, or use getFeatureValue when you only need the typed value.
As expected in Kotlin, you can access these getters using property accessors.
Typed feature access
Available starting in version 0.11.0FeatureKey carries both the feature identifier and its value type. Declare keys once with TypedKey, then pass them to GrowthBookClient or GrowthBook instead of raw strings.
getFeature returns the raw evaluated value. It does not deserialize that value into the key’s type. Use getFeatureValue(FeatureKey, defaultValue, UserContext) on GrowthBookClient, or getFeatureValue(FeatureKey, defaultValue) on GrowthBook, when you need a deserialized object. TypedKey also provides ofDouble and ofFloat. The matching client methods are getDoubleFeature and getFloatFeature.
Inline Experiments
Instead of declaring all features up-front in the context and referencing them by IDs in your code, you can also just run an experiment directly. This is done with thegrowthbook.run(Experiment<T>) method.
The Experiment builder takes ArrayList values for variations and weights, and a Gson JsonObject for conditionJson.
Inline experiment return value ExperimentResult
AnExperimentResult<T> is returned where T is the generic value type for the experiment.
There’s also a number of methods available.
As expected in Kotlin, you can access these getters using property accessors.
Tracking feature usage and experiment impressions
This section covers how to track and monitor feature usage and experiment impressions in your application. There are several types of callbacks and events you can subscribe to:- Tracking Callback - Called when a user is included in an experiment
- Feature Usage Callback - Called every time a feature is evaluated
- Experiment Run Callback - Called when an inline experiment is run with
run()(regardless of inclusion)
Tracking Callback
Any time an experiment is run to determine the value of a feature, we may call this callback so you can record the assigned value in your event tracking or analytics system of choice. The tracking callback is only called when the user is in the experiment. If they are not in the experiment, this will not be called.Feature Usage Callback
Any time a feature is evaluated (regardless of experiment participation), this callback is called with the feature key and result.Experiment Run Callback
You can subscribe to inline experiment runs using theExperimentRunCallback. This callback is called regardless of whether the user is included in the experiment.
Subscriptions fire from run() only, not from feature evaluation such as isOn() or evalFeature(). They fire the first time an experiment key is run, and again only when inExperiment or the variation changes for that key on the same instance. On a shared GrowthBookClient, that state is kept per experiment key across all users, not per user.
Multiple Callback Subscriptions
You can subscribe to multiple experiment run callbacks.onRun is a generic method, so implement the callback with a class or an anonymous class. A Java lambda cannot implement it.
Working with Encrypted features
As of version 0.3.0, the Java SDK supports decrypting encrypted features. You can learn more about SDK Connection Endpoint Encryption. The main difference is you create aGBContext by passing an encryption key (.encryptionKey() when using the builder) and using the encrypted payload as the features JSON (.featuresJson() for the builder).
Fetching, Caching, and Refreshing features with GBFeaturesRepository
As of version 0.4.0, the Java SDK provides an optionalGBFeaturesRepository class which will manage networking for you in the following ways:
- Fetching features from the SDK endpoint when
initialize()is called - Decrypting encrypted features when provided with a decryption key, e.g.
.builder().decryptionKey(clientKey)(encryptionKeyon this builder is deprecated) - Caching features (in-memory)
- Refreshing features
RecommendationThis class should be implemented as a singleton class as it includes caching and refreshing functionality.
GBFeaturesRepository class with your own class to make it easier to work with dependency injection frameworks. Each of these instances should be singletons.
Fetching the features
You will need to create a singleton instance of theGBFeaturesRepository class either by implementing its .builder() or by using its constructor.
Then, you would call myGbFeaturesRepositoryInstance.initialize() in order to make the initial (blocking) request to fetch the features. Then, you would call myGbFeaturesRepositoryInstance.getFeaturesJson() and provided that to the GBContext initialization.
Caching and refreshing behavior
There are 3 refresh strategies available, selected withFeatureRefreshStrategy on the Options or GBFeaturesRepository builder.
Stale While Revalidate
This is the default strategy but can be explicitly stated by passingFeatureRefreshStrategy.STALE_WHILE_REVALIDATE as the refresh strategy option to the GBFeaturesRepository builder or constructor.
The GBFeaturesRepository will automatically refresh the features when the features become stale. Features are considered stale every 60 seconds. This amount is configurable with the swrTtlSeconds option, which also sets the interval of the background poll that drives the refresh.
When you fetch features and they are considered stale, the stale features are returned from the getFeaturesJson() method and a network call to refresh the features is enqueued asynchronously. When that request succeeds, the features are updated with the newest features, and the next call to getFeaturesJson() will return the refreshed features.
The repository sends If-None-Match and keeps the current payload when the server responds 304 Not Modified.
swrTtlSeconds has no effect under the SERVER_SENT_EVENTS refresh strategy, where updates are pushed as they happen.
Server-Sent Events
This is a new strategy that can be enabled by passingFeatureRefreshStrategy.SERVER_SENT_EVENTS as the refresh strategy option to the GBFeaturesRepository builder or constructor.
If you’re using GrowthBook Cloud , this is ready for you to use. If you are self-hosting, you will need to set up the GrowthBook Proxy to enable it.
Remote Eval strategy
FeatureRefreshStrategy.REMOTE_EVAL_STRATEGY is a repository refresh mode. On initialize(), GBFeaturesRepository calls fetchForRemoteEval with the configured RequestBodyForRemoteEval.
That strategy is separate from Options.remoteEval(true), which is the client remote evaluation path described in Remote Evaluation. Setting only REMOTE_EVAL_STRATEGY does not set remoteEval. When remoteEval(true) is set, GrowthBookClient.initialize() does not create a features repository for evaluation, so this strategy does not apply.
Caching feature payloads
The SDK can persist the fetched feature payload so a restart does not require a fresh network call before features are available. Configure this withcacheMode (CacheMode):
AUTO and FILE use cacheDirectory when it is set. Otherwise AUTO tries the growthbook.cache.dir system property, then the platform cache directory, then java.io.tmpdir, so it usually writes to disk.
isCacheDisabled(true) turns persistence off. CacheMode.CUSTOM requires a cacheManager. Supplying a cacheManager while caching is disabled fails configuration validation.
Caffeine cache adapter
The optionalgrowthbook-cache-caffeine module is a Caffeine-backed GbCacheManager. It depends on com.github.ben-manes.caffeine:caffeine:2.9.3. Published on JitPack as com.github.growthbook.growthbook-sdk-java:growthbook-cache-caffeine:0.11.0. That module already depends on lib.
CaffeineGbCacheManager.builder() returns CaffeineCacheOptions.Builder. buildManager() returns the cache manager. maximumSize defaults to 1000. maximumWeight(long) bounds the cache by UTF-8 payload bytes and takes precedence over maximumSize. recordStats(true) turns on the counters reported by stats(); without it they stay at 0.
JCache adapter
The optionalgrowthbook-cache-jcache module wraps a JSR-107 cache. Published on JitPack as com.github.growthbook.growthbook-sdk-java:growthbook-cache-jcache:0.11.0. It depends on javax.cache:cache-api:1.1.1 and on lib. It does not include a cache provider. Put a JSR-107 provider such as Ehcache or Hazelcast on the runtime classpath.
JCacheGbCacheManager.builder() returns JCacheCacheOptions.Builder. cacheManager is required. cacheName defaults to growthbook-features. Eviction and expiry are configured on the provider, not on this adapter.
Customizing refresh timing and retries
You can set a minimum interval between non-forced background refreshes and a bounded exponential retry policy for feature fetches. WhenretryPolicy is omitted, the repository uses FeatureFetchRetryPolicy’s default: 5 total attempts, with retry waits of 1s, 2s, 4s, and 8s. The default maximum delay is 16 seconds. Network errors, 408, 429, and 5xx responses are retried. Retries run on the calling thread, so a failing initialize() can block for about 15 seconds with the default policy. The same maxAttempts limits consecutive Server-Sent Events reconnect attempts.
Forcing a refresh
GrowthBookClient.refreshFeatures() honors the configured background fetch interval. refreshFeatures(RefreshMode.FORCE) always performs a network request and bypasses cache freshness checks. Current features stay available for evaluation while the refresh runs.
refreshFeature() is deprecated and calls refreshFeatures(), except when remote evaluation is enabled. In that case it clears the remote evaluation cache.
Sticky Bucketing
By default, GrowthBook does not persist assigned experiment variations for a user. It relies on deterministic hashing so the same user attributes always map to the same experiment variation. That is not always enough. If you change targeting conditions in the middle of an experiment, users may stop being shown a variation even if they were previously bucketed into it. Sticky Bucketing keeps users on the same experiment variant when user attributes, login status, or experiment parameters change. See the Sticky Bucketing docs. Provide aStickyBucketService. The SDK includes InMemoryStickyBucketServiceImpl. Implement the interface yourself for a database or other store.
The SDK chooses which attributes to look up. GrowthBookClient requests assignments for every primitive user attribute. GrowthBook uses each experiment’s hashAttribute and fallbackAttribute. The stickyBucketIdentifierAttributes option is accepted but not used for this in 0.11.0.
A StickyAssignmentsDocument has three fields:
attributeName: the attribute used to identify the user, such asidorcookie_idattributeValue: the value of that attribute, such as123assignments: persisted experiment assignments, for example{"exp1__0":"control"}
attributeName and attributeValue together are the primary key.
Implementing a custom StickyBucketService
ImplementStickyBucketService to persist assignments. getAssignments, saveAssignments, and getAllAssignments are the interface methods. The map returned by getAllAssignments must be keyed by attributeName + "||" + attributeValue, because the SDK looks documents up by that key. InMemoryStickyBucketServiceImpl uses the same format.
stickyBucketService when remoteEval is enabled. Remote evaluation rejects that combination. See Remote Evaluation.
Remote Evaluation
TheremoteEval option is available starting in version 0.11.0. refreshForRemoteEval and FeatureRefreshStrategy.REMOTE_EVAL_STRATEGY were available earlier.
Remote Evaluation evaluates feature flags on a private server. Targeting rules and unused variations stay off the client. On a trusted server it is usually unnecessary, because the SDK can evaluate the full payload locally. It is mainly useful for Android and other clients you don’t control. Enable it in the SDK Connection settings. Cloud customers need a self-hosted GrowthBook Proxy or another remote evaluation backend. Read the remote evaluation guide.
On GrowthBookClient, set remoteEval(true). initialize() prepares the remote evaluation client and returns false when setup fails. Later evaluations call the remote API for the current user attributes and cache the response. If that request fails, the SDK logs a warning and evaluates against an empty feature set, so features return their fallback values. preloadRemoteEval(UserContext) warms that cache and returns false when remote evaluation is off or the request fails.
apiHost cannot be growthbook.io or a subdomain of it. OptionsValidator also rejects remote evaluation when:
decryptionKeyis setstickyBucketServiceis setrefreshStrategyis explicitlyFeatureRefreshStrategy.STALE_WHILE_REVALIDATE
refreshStrategy unset, as in the example above. remoteEval(true) does not change that field. The validator reads getRefreshStrategy(), which is null until you set it, and null is allowed. getRefreshingStrategy() still reports STALE_WHILE_REVALIDATE when the field is unset, but remote evaluation does not use that default. Setting the strategy explicitly to STALE_WHILE_REVALIDATE is what makes initialize() return false.
Sticky bucketing for this mode belongs on the remote evaluation backend. The client must not be given a StickyBucketService.
refreshForRemoteEval(RequestBodyForRemoteEval) sends an explicit payload. RequestBodyForRemoteEval accepts attributes (JsonObject), forcedFeatures, forcedVariations, and url.
refreshStrategy(FeatureRefreshStrategy.SERVER_SENT_EVENTS), the client listens for feature updates and clears the remote evaluation cache when they arrive.
GBContext.builder().remoteEval(true) is the same flag for a traditional GrowthBook instance. It also requires apiHost and clientKey. With an invalid configuration, new GrowthBook(context) throws InvalidOptionsException instead of returning a failure value.
Custom Fields
Available starting in version 0.11.0 Experiments can carry custom metadata configured in GrowthBook.Experiment exposes:
getCustomField(String fieldId)returns the raw value (Object), ornullif it is absentgetCustomField(String fieldId, Class<FieldType> fieldType)casts or deserializes the value with GsonhasCustomField(String fieldId)returns whether the field is present
FeatureRule stores the same metadata on getCustomFields(), which returns Map<String, Object>. It does not have the getCustomField(String) helpers that Experiment does.
Diagnostics
Available starting in version 0.11.0GrowthBookClient.getDiagnostics() returns a Diagnostics snapshot. toJson() serializes it. getHealth().getState() is a DiagnosticsHealthState: READY, NOT_READY, DEGRADED, ERROR, or SHUTDOWN. getHealth().getIssues() lists DiagnosticsIssue values, each with getCode(), getSeverity(), and getMessage().
The snapshot also includes SDK, config, client, feature, refresh, cache, streaming, and remote evaluation sections through getSdk(), getConfig(), getClient(), getFeatures(), getRefresh(), getCache(), getStreaming(), and getRemoteEval().
Overriding Feature Values
The Java SDK allows you to override feature values and experiments using the URL.Force Experiment Variations
You can force an experiment variation by passing the experiment key and variation index as query parameters in the URL you set on theGBContext. For example, if you add ?my-experiment-id=2 to the URL, users will be forced into the variation at index 2 in the variations list when evaluating the experiment with key my-experiment-id.
Force Feature Values via the URL
You can force a value for a feature by passing the key, prefixed bygb~, and the URI-encoded value in the URL’s query parameters. You must also set allowUrlOverrides to true when building your GBContext in order to enable this feature as it is not enabled by default.
dark_mode:truebanner_text:"Hello, everyone! I hope you are all doing well!"donut_price:3.33
Supported types
The value passed in the URL is cast at runtime based on the generic type argument passed in when evaluating the feature. This means that when you call
<ValueType>getFeatureValue(), what you pass into the URL must successfully cast as ValueType otherwise the value in the URL will be ignored.
All keys must be prefixed with gb~.
Using with Proguard and R8
Many Android projects use code-shrinking and obfuscation tools like Proguard and R8 in production. If you are experiencing unexpected feature evaluation results with your release Android builds that do not occur in your debug builds, it’s most likely related to this. You will need to add the following to yourproguard-rules.pro file to ensure that all of the GrowthBook SDK classes are kept so that your features are evaluated properly in projects that use Proguard and R8:

