Java Core Server SDK
Statsig Server Core
Statsig Server Core is currently in beta - we encourage you to try it out and give us feedback in the Statsig Slack.
Statsig Server Core is a performance-focused rewrite of Statsig server SDKs with a shared core Rust library, that we're rolling out as an option for each Server Environment we currently support with SDKs.
Server Core brings Rust's natural speed and performance optimizations to each language, as we develop them in one, shared library. Initial benchmarking suggests Server Core can evaluate 5-10x as fast as existing SDKs. Beside evaluation performance improvement, we introduced new compression mechanism, which should reduce outbound (egress) network payload significantly.
Server Core does not currently resolve User Agents or Countries. Expect this addition in the near future.
Server Core also introduces many new features, for example,
- Param Stores, including bootstrap with param stores,
- SDK Observability Interface
- Streaming Config Specs and etc.
Server Core is currently available for Java, Node, and Python. Need another language? Let us know in the Statsig Slack and we'll prioritize it.
Installation
Installing the Java SDK
To ensure the Statsig Java SDK works correctly on your machine, you'll need to install the core library and the correct OS/architecture-specific dependency.
Our system will automatically detect your OS and architecture, then log the appropriate dependency for you to include in your build.gradle
. Here's how the process works:
Step 1: Install the Core Library
You should always include the core library in your build.gradle
file, regardless of your system:
dependencies {
implementation 'com.statsig:javacore:X.X.X' // Replace X.X.X with the latest version
}
Step 2: Detect Your OS and Architecture
We will automatically detect your:
- Operating System (OS): Whether you are using macOS, Linux, or Windows.
- System Architecture: Whether your system runs on ARM (e.g., Apple Silicon M1/M2) or x86 (Intel/AMD).
To help you install the correct architecture-specific dependency, we use a logging mechanism to print the exact command you need to add to your build.gradle
file.
After completing Step 1, simply run the following code:
import com.statsig.*;
// All StatsigOptions are optional, feel free to adjust them as needed
StatsigOptions options = new StatsigOptions.Builder()
.setSpecsSyncIntervalMs(10)
.setEventLoggingFlushIntervalMs(10)
.build();
Statsig statsig = new Statsig("your-secret-key", options);
You should get an output similar to the example below. The exact command may vary depending on your OS and architecture:
For Linux with arm64 architecture, add the following to build.gradle:
implementation 'com.statsig:javacore:<version>:amazonlinux2023-arm64'
For Linux with x86_64 architecture, add the following to build.gradle:
implementation 'com.statsig:javacore:<version>:amazonlinux2023-x86_64'
Step 3. Putting It All Together:
- Up-to-Date Versions: Make sure you always replace
<version>
with the latest SDK version. - Latest Version can be found here: https://central.sonatype.com/artifact/com.statsig/javacore/overview
Here’s an example of what your build.gradle
might look like:
dependencies {
implementation 'com.statsig:javacore:X.X.X' // Core SDK
implementation 'com.statsig:javacore:<version>:amazonlinux2023-arm64' // OS and architecture-specific dependency
}
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.
Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.
options
that allows you to pass in a StatsigOptions to customize the SDK.Initialize the SDK
After installation, you will need to initialize the SDK with customized Configuration using a Server Secret Key from the statsig console.
import com.statsig.*;
// All StatsigOptions are optional, feel free to adjust them as needed
StatsigOptions options = new StatsigOptions.Builder()
.setSpecsSyncIntervalMs(10000)
.setEventLoggingFlushIntervalMs(10000)
.setOutputLoggerLevel(OutputLogger.LogLevel.INFO)
.build();
Statsig myStasigServer = new Statsig(SECRET_KEY, options);
statsig.initialize().get();
initialize
will perform a network request. After initialize
completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.Working with the SDK
Checking a Feature Flag/Gate
Now that your SDK is initialized, let's fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;
) by default.
From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:
boolean isFeatureOn = statsig.checkGate(user, "example_gate");
Reading a Dynamic Config
Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:
Difference between Experiment & DynamicConfig class
In this SDK, we now have two classes: Experiment and DynamicConfig, both of which help you manage feature flags and configurations for your users. These classes are similar to the ones in the Kotlin SDK, but are tailored for use in Java.
While both Experiment
and DynamicConfig
classes share similar functionalities (i.e., retrieving configuration values), their underlying structures and intended use cases differ slightly:
Config/Experiment Usage
DynamicConfig config = statsig.getDynamicConfig(user, "awesome_product_details");
Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.
Layer layer = statsig.getLayer(user, "layer_name");
Experiment experiment = statsig.getExperiment(user, "sample_exp")
Logging an Event
Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:
StatsigUser user = new StatsigUser("user123");
String eventName = "purchase";
String value = "100";
Map<String, String> metadata = new HashMap<>();
metadata.put("item_id", "12345");
metadata.put("category", "electronics");
statsig.logEvent(user, eventName, value, metadata);
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Retrieving Feature Gate Metadata
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:
FeatureGate gate = statsig.getFeatureGate(user, "exmaple_gate");
Statsig User
When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. The userID
field is required because it's needed to provide a consistent experience for a given user (click here to understand further why it's important to always provide a userID).
Besides userID
, we also have email
, ip
, userAgent
, country
, locale
and appVersion
as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom
field and be able to create targeting based on them.
Note that while typing is lenient on the StatsigUser
object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.
Usage in Java Core
StatsigUser user = new StatsigUser.Builder()
.setUserID("user_id")
.setCustomIDs(Map.of("external_id", "abc123"))
.setEmail("user@example.com")
.setIp("192.168.0.1")
.setLocale("en-US")
.setAppVersion("1.0.0")
.setUserAgent("Mozilla/5.0")
.setCountry("USA")
.setPrivateAttributes(Map.of("is_beta_user", "true"))
.setCustom(Map.of("subscription", "premium"))
.build();
Private Attributes
Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes
, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes
will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.
For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" }
to privateAttributes
on the user and that's it!
Statsig Options
StatsigOptions Class
The statsig.initialize()
method takes an optional parameter options
to customize the Statsig client. Below is the structure of the StatsigOptions
class, including available parameters and their descriptions:
Parameters
-
specs_url
:Optional[str]
Custom URL for fetching feature specifications. -
specs_sync_interval_ms
:Optional[int]
How often the SDK updates specifications from Statsig servers (in milliseconds). -
init_timeout_ms
:Optional[int]
Sets the maximum timeout for initialization requests (in milliseconds). -
log_event_url
:Optional[str]
Custom URL for logging events. -
disable_all_logging
:Optional[bool]
Whentrue
, disables all event logging. -
event_logging_flush_interval_ms
:Optional[int]
How often events are flushed to Statsig servers (in milliseconds). -
event_logging_max_queue_size
:Optional[int]
Maximum number of events to queue before forcing a flush. -
enable_id_lists
:Optional[bool]
Enable/disable ID list functionality. -
id_lists_url
:Optional[str]
Custom URL for fetching ID lists. -
id_lists_sync_interval_ms
:Optional[int]
How often the SDK updates ID lists from Statsig servers (in milliseconds). -
fallback_to_statsig_api
:Optional[bool]
Whether to fallback to the Statsig API if custom endpoints fail. -
environment
:Optional[str]
Environment parameter for evaluation. -
output_log_level
:Optional[str]
Controls the verbosity of SDK logs.
Example Usage
from statsig import StatsigOptions
# Initialize StatsigOptions with custom parameters
options = StatsigOptions()
options.environment = "development"
options.init_timeout_ms = 3000
options.disable_all_logging = False
# Pass the options object into statsig.initialize()
statsig.initialize("secret-key", options)
Shutting Statsig Down
Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.
To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:
// Method signature
public CompletableFuture<Void> shutdown()
// example usage
try {
statsig.shutdown().get();
System.out.println("Statsig instance have been successfully shutdown.");
} catch (InterruptedException | ExecutionException e) {
System.err.println(e.getMessage());
}
// Method signature
public CompletableFuture<Void> flushEvents()
// example usage
try {
statsig.flushEvents().get();
System.out.println("All events have been successfully flushed.");
} catch (InterruptedException | ExecutionException e) {
System.err.println("Failed to flush events: " + e.getMessage());
}
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Supported OS and Architecture Combinations
OS/Architecture Identifier | Description | Dependency |
---|---|---|
java-core | Platform-independent Java core, ALWAYS ADD THIS | implementation 'com.statsig:javacore:X.X.X' |
macos-arm64 | macOS (Apple Silicon/ARM64) | implementation 'com.statsig:javacore:X.X.X:macos-arm64' |
macos-x86_64 | macOS (Intel/x86_64 or AMD64) | implementation 'com.statsig:javacore:X.X.X:macos-x86_64' |
windows-arm64 | Windows (ARM64) | implementation 'com.statsig:javacore:X.X.X:windows-arm64' |
windows-i686 | Windows (Intel/i686, 32-bit architecture) | implementation 'com.statsig:javacore:X.X.X:windows-i686' |
windows-x86_64 | Windows (Intel/AMD 64-bit architecture, x86_64) | implementation 'com.statsig:javacore:X.X.X:windows-x86_64' |
amazonlinux2-arm64 | Amazon Linux 2 (ARM64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2-arm64' |
amazonlinux2-x86_64 | Amazon Linux 2 (Intel/AMD 64-bit, x86_64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2-x86_64' |
amazonlinux2023-arm64 | Amazon Linux 2023 (ARM64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2023-arm64' |
amazonlinux2023-x86_64 | Amazon Linux 2023 (Intel/AMD 64-bit, x86_64) | implementation 'com.statsig:javacore:X.X.X:amazonlinux2023-arm64' |
Reference
FeatureGate Class Structure:
class FeatureGate {
String name; // gate name
boolean value; // evluation boolean result
String ruleID; // rule id for this gate
EvaluationDetails evaluationDetails; // evluation details
String rawJson; // in case you might intersted in a raw Json string of
// this feature gate
}
Experiment Class Structure:
class Experiment {
String name; // Name of the experiment
String ruleID; // ID of the rule used in the experiment
Map<String, JsonElement> value; // Configuration values specific to the experiment
String groupName; // The group name the user falls into within the experiment
EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated
String rawJson; // Raw JSON representation of the experiment
}
DynamicConfig Class Structure:
class Experiment {
String name; // Name of the experiment
String ruleID; // ID of the rule used in the experiment
Map<String, JsonElement> value; // Configuration values specific to the experiment
EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated
String rawJson; // Raw JSON representation of the experiment
}
Methods for both Experiment and DynamicConfig
public String getString(String key, String fallbackValue)
public boolean getBoolean(String key, Boolean fallbackValue)
public double getDouble(String key, double fallbackValue)
public int getInt(String key, int fallbackValue)
public long getLong(String key, long fallbackValue)
public Object[] getArray(String key, Object[] fallbackValue)
public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)
Layer
Layer {
String name; // layer name
String ruleID; // rule id for this rule
String groupName;
Map<String, JsonElement> value;
String allocatedExperimentName;
EvaluationDetails evaluationDetails;
String rawJson; // raw JSON string representation of Layer Object
}
Layer Methods
/**
* Retrieves a string value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* String value = layer.getString("feature_name", "default_value");
*/
public String getString(String key, String fallbackValue)
/**
* Retrieves a boolean value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Boolean isEnabled = layer.getBoolean("is_enabled", false);
*/
public boolean getBoolean(String key, Boolean fallbackValue)
/**
* Retrieves a double value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* double ratio = layer.getDouble("conversion_ratio", 1.0);
*/
public double getDouble(String key, double fallbackValue)
/**
* Retrieves an integer value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* int maxAttempts = layer.getInt("max_attempts", 3);
*/
public int getInt(String key, int fallbackValue)
/**
* Retrieves a long value from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* long timestamp = layer.getLong("start_timestamp", 1627389483L);
*/
public long getLong(String key, long fallbackValue)
/**
* Retrieves an array of objects from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Object[] items = layer.getArray("item_list", new Object[] {});
*/
public Object[] getArray(String key, Object[] fallbackValue)
/**
* Retrieves a Map object from the layer based on the specified key.
* If the key is not found, the fallback value is returned.
*
* @example
* Map<String, Object> items = layer.getMap("item_list", new Object[] {});
*/
public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue)