Skip to main content

Rust Server SDK

Getting Started

The following will outline how to get up and running with Statsig for Rust.

Create an Account

To work with the SDK, you will need a Statsig account. If you don't yet have an account, you can sign up for a free one here. You could skip this for now, but you will need an SDK key and some gates/experiments to use with the SDK in just a minute.


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

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.


Do NOT embed your Server Secret Key in client side applications, or expose it in any external facing documents. However, if you accidentally exposed it, you can create a new one in 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};


// or with StatsigOptions

use statsig::{Statsig, StatsigOptions};

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

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

Retrieving Feature Gate Metadata

In certain scenarios, it's beneficial to access detailed information about a feature gate, such as its current state for a specific user or additional contextual data. This can be accomplished effortlessly through the Get Feature Gate API. By providing the necessary user details and the name of the feature gate you're interested in, you can fetch this metadata to inform your application's behavior or for analytical purposes.

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.

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 "", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "" } 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 ""

    • 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:



How do I run experiments for logged out users?

See the guide on device level experiments



#[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>>,


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,