# Legacy Rust Server SDK

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

- **Package:** `statsig` ([crates](https://crates.io/crates/statsig))
- **Latest version:** 1.4.0
- **Repository:** [rust-sdk](https://github.com/statsig-io/rust-sdk)

> **Warning:**
>
> Support for the Legacy Rust SDK ends April 30, 2026. Migrate to the
>
> [new Rust SDK](https://docs.statsig.com/server-core/rust-core)
>
> soon.

## Setup the SDK

1. **Install the SDK**

   To use the SDK, add `statsig` as a dependency in your `Cargo.toml`. You can find the latest version at [crates.io/crates/statsig](https://crates.io/crates/statsig).

   ```toml
   [dependencies]
   statsig = "X.Y.Z" # <- update version
   ```
2. **Initialize the SDK**

   After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys).

   > **Warning:**
   >
   > Don't 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.

   ```rust
   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` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls.

## Working with the SDK

## Checking a Feature Flag/Gate

After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default.

All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user:

```rust
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 work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters.

```rust
let config = Statsig::get_config(&user, "a_config").ok().unwrap();
let value = config.get_string("a_key", "default_value");
```

## Getting a Layer/Experiment

Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse.

```rust
let layer = Statsig::get_layer(&user, "a_layer").ok().unwrap();
let param_value = layer.get_string("a_parameter", "default_value");

// or via get_experiment
let experiment = Statsig::get_experiment(&user, "an_experiment").ok().unwrap();
let exp_value = experiment.get_string("a_parameter", "default_value");
```

## Logging an Event

To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object:

```rust
let event = StatsigEvent::new("event_name".to_string());
Statsig::log_event(&user, event);
```

For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events).

## Statsig User

When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail.

In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them.

Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array.

### Private Attributes

To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers.

For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user.

## Shutdown

To gracefully shutdown the SDK and flush all events:

```rust
Statsig::shutdown().await;
```
