Official documentation for Amplitude Experiment's server-side JVM SDK implementation. This SDK may be used in either Java or Kotlin server-side implementations.
This documentation has separate sections for remote and local evaluation:
Implements fetching variants for a user via remote evaluation.
Install the JVM Server SDK using Gradle.
1implementation "com.amplitude:experiment-jvm-server:<VERSION>"
1implementation("com.amplitude:experiment-jvm-server:<VERSION>")
Quick start
The SDK client should be initialized in your server on startup. The deployment key argument passed into the apiKey
parameter must live within the same project that you are sending analytics events to.
1fun initializeRemote(2 apiKey: String,3 config: RemoteEvaluationConfig = RemoteEvaluationConfig()4): RemoteEvaluationClient
1@Nonnull2public RemoteEvaluationClient initializeRemote(3 @Nonnull String apiKey,4 @Nonnull RemoteEvaluationConfig config5);
Parameter | Requirement | Description |
---|---|---|
apiKey |
required | The deployment key which authorizes fetch requests and determines which flags should be evaluated for the user. |
config |
optional | The client configuration used to customize SDK client behavior. |
1val experiment = Experiment.initializeRemote("<DEPLOYMENT_KEY>")
1RemoteEvaluationClient experiment = Experiment.initializeRemote("<DEPLOYMENT_KEY>");
The SDK client can be configured on initialization.
If you're using Amplitude's EU data center, configure the serverZone
option on initialization.
Name |
Description | Default Value |
---|---|---|
debug |
Set to true to enable debug logging. |
false |
serverZone |
The Amplitude data center to use. Either ServerZone.US or ServerZone.EU . |
ServerZone.US |
serverUrl |
The host to fetch flag configurations from. | https://api.lab.amplitude.com |
fetchTimeoutMillis |
The timeout for fetching variants in milliseconds. This timeout only applies to the initial request, not subsequent retries | 500 |
fetchRetries |
The number of retries to attempt if a request to fetch variants fails. | 1 |
fetchRetryBackoffMinMillis |
The minimum (initial) backoff after a request to fetch variants fails. This delay is scaled by the fetchRetryBackoffScalar |
0 |
fetchRetryBackoffMaxMillis |
The maximum backoff between retries. If the scaled backoff becomes greater than the max, the max is used for all subsequent requests | 10000 |
fetchRetryBackoffScalar |
Scales the minimum backoff exponentially. | 1 |
CohortSyncConfig
Name |
Description | Default Value |
---|---|---|
apiKey |
The analytics API key and NOT the experiment deployment key | required |
secretKey |
The analytics secret key | required |
maxCohortSize |
The maximum size of cohort that the SDK will download. Cohorts larger than this size won't download. | 2147483647 |
cohortPollingIntervalMillis |
The interval, in milliseconds, to poll Amplitude for cohort updates (60000 minimum). | 60000 |
cohortServerUrl |
The cohort server endpoint from which to fetch cohort data. For hitting the EU data center, set serverZone to ServerZone.EU . Setting this value will override serverZone defaults. |
https://cohort-v2.lab.amplitude.com |
Fetches variants for a user and returns the results. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.
1fun fetch(user: ExperimentUser): CompletableFuture<Map<String, Variant>>
1@Nonnull2public CompletableFuture<Map<String, Variant>> fetch(@Nonnull ExperimentUser user);
Parameter | Requirement | Description |
---|---|---|
user |
required | The user to remote fetch variants for. |
1val user = ExperimentUser.builder() 2 .userId("user@company.com") 3 .deviceId("abcdefg") 4 .userProperty("premium", true) 5 .build() 6val variants = try { 7 experiment.fetch(user).get() 8} catch (e: Exception) { 9 e.printStackTrace()10 return11}
1ExperimentUser user = ExperimentUser.builder() 2 .userId("user@company.com") 3 .deviceId("abcdefg") 4 .userProperty("premium", true) 5 .build(); 6Map<String, Variant> variants; 7try { 8 variants = experiment.fetch(user).get(); 9} catch (Exception e) {10 e.printStackTrace();11 return;12}
After fetching variants for a user, you may to access the variant for a specific flag.
1val variant = variants["<FLAG_KEY>"]2if (variant?.value == "on") {3 // Flag is on4} else {5 // Flag is off6}
1Variant variant = variants.get("<FLAG_KEY>");2if (Variant.valueEquals(variant, "on")) {3 // Flag is on4} else {5 // Flag is off6}
Implements evaluating variants for a user via local evaluation. If you plan on using local evaluation, you should understand the tradeoffs.
Install the JVM Server SDK using Maven or Gradle.
1implementation "com.amplitude:experiment-jvm-server:<VERSION>"
1implementation("com.amplitude:experiment-jvm-server:<VERSION>")
1// (1) Initialize the local evaluation client with a server deployment key. 2val experiment = Experiment.initializeLocal( 3 "<DEPLOYMENT_KEY>", 4 // (Recommended) Enable local evaluation cohort targeting. 5 LocalEvaluationConfig.builder() 6 .cohortSyncConfig(CohortSyncConfig("<API_KEY>", "<SECRET_KEY>")) 7 .build() 8) 9 10// (2) Start the local evaluation client.11experiment.start()12 13// (3) Evaluate a user.14val user = ExperimentUser.builder()15 .userId("user@company.com")16 .deviceId("abcdefg")17 .userProperty("premium", true)18 .build()19val variants = experiment.evaluate(user)
1// (1) Initialize the local evaluation client with a server deployment key. 2LocalEvaluationClient experiment = Experiment.initializeLocal("<DEPLOYMENT_KEY>", 3 // (Recommended) Enable local evaluation cohort targeting. 4 LocalEvaluationConfig.builder() 5 .cohortSyncConfig(new CohortSyncConfig("<API_KEY>", "<SECRET_KEY>")) 6 .build()); 7 8// (2) Start the local evaluation client. 9experiment.start();10 11// (3) Evaluate a user.12ExperimentUser user = ExperimentUser.builder()13 .userId("user@company.com")14 .deviceId("abcdefg")15 .userProperty("premium", true)16 .build();17Map<String, Variant> variants = experiment.evaluate(user);
Initializes a local evaluation client.
You must initialize the local evaluation client with a server deployment key to get access to local evaluation flag configs.
1fun initializeLocal(2 apiKey: String,3 config: LocalEvaluationConfig = LocalEvaluationConfig(),4): LocalEvaluationClient
1@Nonnull2public LocalEvaluationClient initializeLocal(3 @Nonnull String apiKey,4 @Nonnull LocalEvaluationConfig config5);
Parameter | Requirement | Description |
---|---|---|
apiKey |
required | The server deployment key which authorizes fetch requests and determines which flags should be evaluated for the user. |
config |
optional | The client configuration used to customize SDK client behavior. |
Use the streamUpdates
configuration to push flag config updates to the SDK (default false
), instead of polling every flagConfigPollingIntervalMillis
milliseconds. The time for SDK to receive the update after saving is generally under one second. It reverts to polling if streaming fails. Configure flagConfigPollingIntervalMillis
configuration to set the time flag configs take to update once modified (default 30s), as well for fallback.
You can configure the SDK client on initialization.
If you're using Amplitude's EU data center, configure the serverZone
option on initialization.
LocalEvaluationConfig
Name |
Description | Default Value |
---|---|---|
debug |
Set to true to enable debug logging. |
false |
serverZone |
The Amplitude data center to use. Either ServerZone.US or ServerZone.EU . |
ServerZone.US |
serverUrl |
The host to fetch flag configurations from. | https://api.lab.amplitude.com |
flagConfigPollingIntervalMillis |
The interval to poll for updated flag configs after calling Start() |
30000 |
flagConfigPollerRequestTimeoutMillis |
The timeout for the request made by the flag config poller | 10000 |
assignmentConfiguration |
Enable automatic assignment tracking for local evaluations. | null |
streamUpdates |
Enable streaming to replace polling for receiving flag config updates. Instead of polling every second, Amplitude servers push updates to SDK generally within one second. If the stream fails for any reason, it reverts to polling automatically and retry streaming after some interval. | false |
streamServerUrl |
The URL of the stream server. | https://stream.lab.amplitude.com |
streamFlagConnTimeoutMillis |
The timeout for establishing a valid flag config stream. This includes time for establishing a connection to stream server and time for receiving initial flag configs. | 1500 |
cohortSyncConfig |
Configuration to enable cohort downloading for local evaluation cohort targeting. | null |
AssignmentConfiguration
Name |
Description | Default Value |
---|---|---|
api_key |
The analytics API key and NOT the experiment deployment key | required |
cache_capacity |
The maximum number of assignments stored in the assignment cache | 65536 |
eventUploadThreshold |
setEventUploadThreshold() in the underlying Analytics SDK |
10 |
eventUploadPeriodMillis |
setEventUploadPeriodMillis() in the underlying Analytics SDK |
10000 |
useBatchMode |
useBatchMode() in the underlying Analytics SDK |
true |
CohortSyncConfig
Name |
Description | Default Value |
---|---|---|
apiKey |
The analytics API key and NOT the experiment deployment key | required |
secretKey |
The analytics secret key | required |
maxCohortSize |
The maximum size of cohort that the SDK will download. Cohorts larger than this size won't download. | 2147483647 |
cohortPollingIntervalMillis |
The interval, in milliseconds, to poll Amplitude for cohort updates (60000 minimum). | 60000 |
Start the local evaluation client, pre-fetching local evaluation mode flag configs for evaluation and starting the flag config poller at the configured interval.
1fun start()
1public void start();
You should wait for start()
to return before calling evaluate()
to ensure that flag configs are available for use in evaluation.
Shuts down the local evaluation client, stopping background processes for updating flag configs and cohorts.
1fun stop()
1public void stop();
Executes the evaluation logic using the flags pre-fetched on start()
. Evaluate must be given a user object argument and can optionally be passed an array of flag keys if only a specific subset of required flag variants are required.
Set assignmentConfiguration
to automatically track an assignment event to Amplitude when evaluate()
is called.
1fun evaluate(user: ExperimentUser, flagKeys: List<String> = listOf()): Map<String, Variant>
1@Nonnull2public Map<String, Variant> evaluate(@Nonnull experimentUser, @Nonnull List<String> flagKeys);
Parameter | Requirement | Description |
---|---|---|
user |
required | The user to evaluate. |
flagKeys |
optional | Specific flags or experiments to evaluate. If empty, all flags and experiments are evaluated. |
1// The user to evaluate 2val user = ExperimentUser.builder() 3 .userId("user@company.com") 4 .deviceId("abcdefg") 5 .userProperty("premium", true) 6 .build() 7 8// Evaluate all flag variants 9val allVariants = experiment.evaluate(user)10 11// Evaluate a specific subset of flag variants12val specificVariants = experiment.evaluate(user, listOf(13 "<FLAG_KEY_1>",14 "<FLAG_KEY_2>",15))16 17// Access a variant18val variant = allVariants["<FLAG_KEY>"]19if (variant?.value == "on") {20 // Flag is on21} else {22 // Flag is off23}
1// The user to evaluate 2ExperimentUser user = ExperimentUser.builder() 3 .userId("user@company.com") 4 .deviceId("abcdefg") 5 .userProperty("premium", true) 6 .build(); 7 8// Evaluate all flag variants 9Map<String, Variant> allVariants = experiment.evaluate(user);10 11// Evaluate a specific subset of flag variants12Map<String, Variant> specificVariants = experiment.evaluate(user,13 List.of("<FLAG_KEY_1>", "<FLAG_KEY_2>"));14 15// Access a variant16Variant variant = allVariants.get("<FLAG_KEY>");17if (Variant.valueEquals(variant, "on")) {18 // Flag is on19} else {20 // Flag is off21}
Since version 1.4.0
, the local evaluation SDK client supports downloading cohorts for local evaluation targeting. Configure the SDK using cohortSyncConfig
with the analytics apiKey
and secretKey
on initialization to enable this support.
1val experiment = Experiment.initializeLocal(2 "<DEPLOYMENT_KEY>",3 // (Recommended) Enable local evaluation cohort targeting.4 LocalEvaluationConfig.builder()5 .cohortSyncConfig(CohortSyncConfig("<API_KEY>", "<SECRET_KEY>"))6 .build()7)
1// (1) Initialize the local evaluation client with a server deployment key.2LocalEvaluationClient experiment = Experiment.initializeLocal("<DEPLOYMENT_KEY>",3 // (Recommended) Enable local evaluation cohort targeting.4 LocalEvaluationConfig.builder()5 .cohortSyncConfig(new CohortSyncConfig("<API_KEY>", "<SECRET_KEY>"))6 .build());
Thanks for your feedback!
June 4th, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.