Skip to main content

Rust Server SDK

Installation

To use the SDK, add statsig as a dependency in your Cargo.toml. The latest version can be found at crates.io/crates/statsig.

[dependencies]
statsig = "X.Y.Z" # <- update version

Initialize the SDK

After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.

info

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.

There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
use statsig::{Statsig};

Statsig::initialize("secret-key").await;

// or with StatsigOptions

use statsig::{Statsig, StatsigOptions};

let env = HashMap::from([("tier".to_string(), "staging".to_string())]);
let opts = StatsigOptions {
environment: Some(env),
..StatsigOptions::default()
};

Statsig::initialize_with_options("secret-key", opts).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::with_user_id("a-user".to_string());

if Statsig::check_gate(&user, "a_gate").ok().unwrap_or(false) {
// 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:

let config = Statsig::get_config(&user, "a_config").ok().unwrap();
let item_name = config.get("product_name", "Awesome Product v1".to_string());
let price = config.get("price", 10.0);
let should_discount = config.get("discount", false);

// or just get the whole value object backing this config if you prefer

let value = config.value;

Getting an 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.

// Values via get_layer

let layer = Statsig::get_layer(&user, "user_promo_experiments").ok().unwrap();
let title = layer.get("title", "Welcome to Statsig!".to_string());
let discount = layer.get("discount", 0.1);

// or, via getExperiment

let title_exp = Statsig::get_config(&user, "new_user_promo_title").ok().unwrap();
let price_exp = Statsig::get_config(&user, "new_user_promo_price").ok().unwrap();

let title = title_exp.get("title", "Welcome to Statsig!".to_string());
let discount = price_exp.get("discount", 0.1);

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:

let event = StatsigEvent {
event_name: "add_to_cart".into(),
value: Some(json!("SKU_12345")),
metadata: Some( HashMap::from([
("price".into(), "9.99".into()),
("item_name".into(), "diet_coke_48_pack".into())
]))
};

Statsig::log_event(&user, event);

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

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.

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

You can specify optional parameters with options when initializing.

  • environment | Option<HashMap<String, String>>

    • a HashMap you can use to set environment variables that apply to all of your users in the same session and will be used for targeting purposes.
    • The most common usage is to set the "tier" (string), and have feature gates pass/fail for specific environments. e.g.
    let environment = Some(HashMap::from([("tier".to_string(), "staging".to_string())]));
    StatsigOptions{environment, ..StatsigOptions::default()};
  • api_override String, default "https://statsigapi.net/v1"

    • The base url to use for network requests from the SDK
  • rulesets_sync_interval_ms: u32, default 10_000

    • The interval to poll for changes to your gate and config definition changes
  • logger_flush_interval_ms: u32, default 60_000

    • The default interval to flush logs to Statsig servers
  • logger_max_queue_size: u32, default 500, can be set lower but anything over 1000 will be dropped on the server

    • The maximum number of events to batch before flushing logs to the server

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();

FAQ

How do I run experiments for logged out users?

See the guide on device level experiments

Reference

StatsigUser

#[derive(Clone, Deserialize, Serialize)]
pub struct StatsigUser {
pub user_id: Option<String>,
pub email: Option<String>,
pub ip: Option<String>,
pub user_agent: Option<String>,
pub country: Option<String>,
pub locale: Option<String>,
pub app_version: Option<String>,
pub custom: Option<HashMap<String, Value>>,
pub private_attributes: Option<HashMap<String, Value>>,
pub custom_ids: Option<HashMap<String, String>>,

StatsigOptions

pub struct StatsigOptions {
pub environment: Option<HashMap<String, String>>,
pub api_override: String,
pub rulesets_sync_interval_ms: u32,
pub logger_max_queue_size: u32,
pub logger_flush_interval_ms: u32,
}