Rust Server SDK
Installation
To use the SDK, add the Statsig Rust package to your Cargo.toml file:
[dependencies]
statsig-rust = "X.Y.Z" # Replace with the latest version
Or, you can use the cargo command:
cargo add statsig-rust
You can find the latest version and documentation at crates.io/crates/statsig-rust.
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.use statsig_rust::{Statsig, StatsigOptions};
use std::sync::Arc;
// Simple initialization
let statsig = Statsig::new("server-secret-key", None);
statsig.initialize().await?;
// Or with StatsigOptions
let mut options = StatsigOptions::default();
options.environment = Some("development".to_string());
let statsig = Statsig::new("server-secret-key", Some(Arc::new(options)));
statsig.initialize().await?;
// Don't forget to shutdown when done
statsig.shutdown().await?;
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:
let user = StatsigUser::new("a-user");
if statsig.check_gate(&user, "a_gate") {
// Gate is on, enable new feature
} else {
// Gate is off
}
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:
use statsig_rust::{Statsig, StatsigUser, DynamicConfigEvaluationOptions};
use std::sync::Arc;
// Get a dynamic config for a specific user
let user = StatsigUser::with_user_id("my_user".to_string());
let config = statsig.get_dynamic_config(&user, "a_config");
// Access config values with type-safe getters and fallback values
let product_name = config.get_string("product_name", "Awesome Product v1"); // returns String
let price = config.get_double("price", 10.0); // returns f64
let should_discount = config.get_boolean("discount", false); // returns bool
let quantity = config.get_int("quantity", 1); // returns i64
// Advanced Usage:
// You can disable exposure logging for this specific check
let mut options = DynamicConfigEvaluationOptions::default();
options.disable_exposure_logging = Some(true);
let config = statsig.get_dynamic_config_with_options(&user, "a_config", &options);
// The config object also provides metadata about the evaluation
println!("{}", config.rule_id); // The ID of the rule that served this config
println!("{}", config.id_type); // The type of the evaluation (experiment, config, etc)
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.
use statsig_rust::{Statsig, StatsigUser};
// Values via get_layer
let user = StatsigUser::with_user_id("my_user".to_string());
let layer = statsig.get_layer(&user, "user_promo_experiments");
let title = layer.get_string("title", "Welcome to Statsig!");
let discount = layer.get_double("discount", 0.1);
// Via get_experiment
let title_exp = statsig.get_experiment(&user, "new_user_promo_title");
let price_exp = statsig.get_experiment(&user, "new_user_promo_price");
let title = title_exp.get_string("title", "Welcome to Statsig!");
let discount = price_exp.get_double("discount", 0.1);
Parameter Stores
Sometimes - you don't know exactly what kind of Statsig config (Gate/Experiment/Layer/Dynamic Config) you want behind a particular value – you might want on-the-fly control of that, outside of your deployment cycle.Parameter Stores enable this by letting you define a "Parameter" that can be static, or changed into a gate, experiment, etc. in the Statsig console. Parameter Stores are optional – but parameterizing your application can prove very useful, even allowing non-technical Statsig users to turn parameters into experiments.
let param_store = statsig.get_parameter_store("my_parameters");
let param_store_value = param_store.get(&user, "my_parameter_value", false); //false is fallback value
println!("param_store_value: {}", param_store_value);
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:
use statsig_rust::{Statsig, StatsigUser};
use std::collections::HashMap;
use crate::evaluation::dynamic_value::DynamicValue;
// Create a user
let user = StatsigUser::with_user_id("user_id".to_string());
// Create metadata hashmap
let mut metadata = HashMap::new();
metadata.insert("price".to_string(), "9.99".into());
metadata.insert("item_name".to_string(), "diet_coke_48_pack".into());
// Log the event
statsig.log_event(
&user,
"add_to_cart",
Some("SKU_12345".into()), // value as DynamicValue
Some(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:
use statsig_rust::{Statsig, StatsigUser};
// Create a user
let user = StatsigUser::with_user_id("user_id".to_string());
// Get a feature gate
let gate = statsig.get_feature_gate(&user, "example_gate");
// Access gate properties
println!("{}", gate.rule_id);
println!("{}", gate.value); // Boolean value of the gate
Manual Exposures
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Manual exposures give you the option to query your gates/experiments without triggering an exposure, and optionally, manually log the exposure after the fact.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
boolean result = statsig.checkGate(aUser, 'a_gate_name', new CheckGateOptions(true));
Later, if you would like to expose this gate, you can call the following.
statsig.manuallyLogGateExposure(aUser, 'a_gate_name');
To get a dynamic config without an exposure being logged, call the following.
DynamicConfig config = statsig.getDynamicConfig(aUser, 'a_dynamic_config_name', new CheckGateOptions(true));
Later, if you would like to expose the dynamic config, you can call the following.
statsig.manuallyLogDynamicConfigExposure(aUser, 'a_dynamic_config_name');
To get an experiment without an exposure being logged, call the following.
Experiment experiment = statsig.getExperiment(aUser, 'an_experiment_name', new CheckGateOptions(true));
Later, if you would like to expose the experiment, you can call the following.
statsig.manuallyLogExperimentExposure(aUser, 'an_experiment_name');
To get a layer parameter without an exposure being logged, call the following.
Layer layer = statsig.getLayer(aUser, 'a_layer_name', new CheckGateOptions(true));
const paramValue = layer.get('a_param_name', 'fallback_value');
Later, if you would like to expose the layer parameter, you can call the following.
statsig.manuallyLogLayerParamExposure(aUser, 'a_layer_name', 'a_param_name');
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. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)
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.
Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.
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.
use statsig_rust::StatsigUser;
// Create a user with just a user ID
let user = StatsigUser::with_user_id("user-123".to_string());
// Or create a user with custom IDs
use std::collections::HashMap;
let mut custom_ids = HashMap::new();
custom_ids.insert("employee_id".to_string(), "emp-456".to_string());
let user_with_custom_ids = StatsigUser::with_custom_ids(custom_ids);
// Or, use StatsigUserBuilder
use statsig_rust::{Statsig, statsig_user::StatsigUserBuilder};
// Create a user with several properties
let user = StatsigUserBuilder::new_with_user_id("user-123".to_string())
.email(Some("user@example.com".to_string()))
.ip(Some("192.168.1.1".to_string()))
.user_agent(Some("Mozilla/5.0...".to_string()))
.country(Some("US".to_string()))
.locale(Some("en-US".to_string()))
.app_version(Some("1.0.0".to_string()))
.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 Struct in Rust
The Statsig::new() method takes an optional parameter options to customize the Statsig client. Here's the accurate structure of the StatsigOptions struct based on the source code:
Parameters
-
data_store
: Option<Arc<dyn DataStoreTrait>> External data store for Statsig values. -
disable_all_logging
: Option<bool> When true, disables all event logging. -
disable_network
: Option<bool> Whentrue
, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called "localMode". -
enable_id_lists
: Option<bool> Enable/disable ID list functionality. -
disable_user_agent_parsing
Optional[bool]
Default false. If set to true, the SDK will NOT attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation. -
wait_for_user_agent_init
Optional[bool]
Default: falseWhen set to true, the SDK will wait until user agent parsing data is fully loaded during initialization. This may slow down by ~1 second startup but ensures that parsing of the user’s userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations.
-
disable_user_country_lookup
Optional[bool]
Default false. If set to true, the SDK will NOT attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation. -
wait_for_country_lookup_init
Optional[bool]
Default: falseWhen set to true, the SDK will wait for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down by ~1 second startup but ensures that IP-to-country parsing is ready at evaluation time
-
environment
: Option<String> Environment parameter for evaluation. -
event_logging_adapter
: Option<Arc<dyn EventLoggingAdapter>> Custom adapter for event logging. -
event_logging_flush_interval_ms
: Option<u32> How often events are flushed to Statsig servers (in milliseconds). -
event_logging_max_queue_size
: Option<u32> Maximum number of events to queue before forcing a flush. -
fallback_to_statsig_api
: Option<bool> Whether to fallback to the Statsig API if custom endpoints fail. -
id_lists_adapter
: Option<Arc<dyn IdListsAdapter>> Custom adapter for ID lists. -
id_lists_sync_interval_ms
: Option<u32> How often the SDK updates ID lists from Statsig servers (in milliseconds). -
id_lists_url
: Option<String> Custom URL for fetching ID lists. -
init_timeout_ms
: Option<u64> Sets the maximum timeout for initialization requests (in milliseconds). -
log_event_url
: Option<String> Custom URL for logging events. -
observability_client
: Option<Weak<dyn ObservabilityClient>> Client for collecting observability data. -
output_log_level
: Option<LogLevel> Controls the verbosity of SDK logs. -
override_adapter
: Option<Arc<dyn OverrideAdapter>> Custom adapter for overrides. -
spec_adapters_config
: Option<Vec<SpecAdapterConfig>> Configuration for specification adapters. -
specs_adapter
: Option<Arc<dyn SpecsAdapter>> Custom adapter for specifications. -
specs_sync_interval_ms
: Option<u32> How often the SDK updates specifications from Statsig servers (in milliseconds). -
specs_url
: Option<String> Custom URL for fetching feature specifications. -
service_name
: Option<String> Name of the service using Statsig. -
global_custom_fields
: Option<HashMap<String, DynamicValue>> Global custom fields to include with all evaluations.
Example Usage
use statsig_rust::{Statsig, StatsigOptions};
use std::sync::Arc;
// Initialize StatsigOptions with custom parameters
let mut options = StatsigOptions::default();
options.environment = Some("development".to_string());
options.init_timeout_ms = Some(3000);
options.disable_all_logging = Some(false);
options.enable_id_lists = Some(true);
options.output_log_level = Some(LogLevel::Info); // LogLevel enum, not a string
// Pass the options object into Statsig::new()
let statsig = Statsig::new("server-secret-key", Some(Arc::new(options)));
statsig.initialize().await?;
// Or, use the builder pattern for a more fluent interface
let options = StatsigOptions::builder()
.environment(Some("development".to_string()))
.init_timeout_ms(Some(3000))
.disable_all_logging(Some(false))
.enable_id_lists(Some(true))
.specs_sync_interval_ms(Some(30000))
.build();
// Pass the options object into Statsig::new()
let statsig = Statsig::new("server-secret-key", Some(Arc::new(options)));
statsig.initialize().await?;
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:
statsig.shutdown().await?;
Alternatively, you can manually flush events without shutting down:
// Manually flush events to the server
statsig.flush_events().await;
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments