Setup the SDK
1
Install the SDK
To use the SDK, add the Statsig Rust package to your Cargo.toml file:Or, you can use the cargo command:You can find the latest version and documentation at crates.io/crates/statsig-rust.
2
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.There is also an optional parameter named
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
options that allows you to pass in a StatsigOptions to customize the SDK.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 (thinkreturn 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:
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 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:Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but often recommend the use of layers, which make parameters reusable and let you run mutually exclusive experiments.Parameter Stores
Sometimes you don’t know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments.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: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:Using Shared Instance
In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose:Statsig::new_shared(sdk_key, options): Creates a new shared instance of Statsig that can be accessed globallyStatsig::shared(): Returns the shared instanceStatsig::has_shared_instance(): Checks if a shared instance exists (useful when you aren’t sure if the shared instance is ready yet)Statsig::remove_shared(): Removes the shared instance (useful when you want to switch to a new shared instance)
has_shared_instance() and remove_shared() are helpful in specific scenarios but aren’t required in most use cases where the shared instance is set up near the top of your application.Also note that only one shared instance can exist at a time. Attempting to create a second shared instance will result in an error.Manual Exposures
By default, the SDK will automatically log an exposure event when you check a gate, get a config, get an experiment, or get a layer. However, there are times when you may want to log an exposure event manually. For example, if you’re using a gate to control access to a feature, but you don’t want to log an exposure until the user actually uses the feature, you can use manual exposures. All of the main SDK functions (check_gate, get_dynamic_config, get_experiment, get_layer) accept an options parameter with a disable_exposure_logging field. When this is set to true, the SDK will not automatically log an exposure event. You can then manually log the exposure at a later time using the corresponding manual exposure logging method:
- Feature Gates
- Dynamic Configs
- Experiments
- Layers
Statsig User
TheStatsigUser object represents a user in Statsig. You must provide a userID or at least one of the customIDs to identify the 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.
Private Attributes
Private attributes are user attributes that are used for evaluation but are not forwarded to any integrations. They are useful for PII or sensitive data that you don’t want to send to third-party services.Statsig Options
You can pass in an optional parameteroptions in addition to sdkKey during initialization to customize the Statsig client. Here are the available options that you can configure.
StatsigOptions
StatsigOptions
External data store for Statsig values.
When true, disables all event logging.
When
true, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called “localMode”.Enable/disable ID list functionality. Required to be
true when using segments with more than 1000 IDs. See ID List segments for more details.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.
When 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.
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.
When 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 parameter for evaluation.
Custom adapter for event logging.
How often events are flushed to Statsig servers (in milliseconds).
Maximum number of events to queue before forcing a flush.
Maximum number of batches of events to hold in buffer to retry.
Whether to fallback to the Statsig API if custom endpoints fail.
Custom adapter for ID lists.
How often the SDK updates ID lists from Statsig servers (in milliseconds).
Custom URL for fetching ID lists.
Sets the maximum timeout for initialization requests (in milliseconds).
Custom URL for logging events.
Client for collecting observability data.
Controls the verbosity of SDK logs.
Custom adapter for overrides.
Configuration for specification adapters.
Custom adapter for specifications.
How often the SDK updates specifications from Statsig servers (in milliseconds).
Custom URL for fetching feature specifications.
Global custom fields to include with all evaluations.
Configuration for connecting through a proxy server. The
ProxyConfig struct has the following properties:proxy_host: Option<String> - Specifies the proxy server hostproxy_port: Option<u16> - Specifies the proxy server portproxy_auth: Option<String> - For proxy authentication (format:"username:password")proxy_protocol: Option<String> - Specifies the protocol (e.g.,"http","https")
Example Usage
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 callshutdown() before your app/server shuts down:
SDK Event Subscriptions
The Statsig SDK provides an event subscription system that allows you to listen for evaluation events in real-time. This feature is useful for debugging, analytics, custom logging, and integrating with external systems.Supported Events
The SDK supports subscribing to the following evaluation events:gate_evaluated- Fired when a feature gate is evaluated for a userdynamic_config_evaluated- Fired when a dynamic config is retrieved for a userexperiment_evaluated- Fired when an experiment is evaluated for a userlayer_evaluated- Fired when a layer is evaluated for a user"*"- Subscribe to all evaluation events
SDK Event Data
Each event includes relevant context about the evaluation:- Gate Evaluated Events include:
gate_name,value(boolean),rule_id,reason - Dynamic Config Events include: the full
dynamic_configobject with values and metadata - Experiment Events include: the full
experimentobject with variant assignment and parameters - Layer Events include: the full
layerobject with allocated experiment and parameters
Use Cases
Event subscriptions are particularly useful for:- Debugging: Monitor which features are being evaluated and their results
- Analytics: Track feature usage patterns and user segments
- Custom Logging: Send evaluation data to your own logging systems
- Integration: Forward events to external analytics or monitoring tools
- Testing: Verify that features are being evaluated as expected
Best Practices
- Clean up subscriptions: Always unsubscribe when you no longer need to listen for events to prevent memory leaks
- Handle event data carefully: Event objects may contain sensitive user information depending on your configuration
- Use specific event types: Subscribe to specific events rather than ”*” when possible for better performance
- Avoid heavy processing: Keep event handlers lightweight to avoid impacting SDK performance
Local Overrides
Local Overrides are a way to override the values of gates, configs, experiments, and layers for testing purposes. This is useful for local development or testing scenarios where you want to force a specific value without having to change the configuration in the Statsig console.Persistent Storage
The Persistent Storage interface allows you to implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups even when the user returns later. This is particularly useful for client-side A/B testing where you want to ensure users always see the same variant.Data Store
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.Custom Output Logger
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.Observability Client
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.Fields Needed Methods (Enterprise Only)
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our slack channel if you want this enabled.
Description
These methods return an array of strings representing the user fields that are referenced in the targeting rules or conditions of the specified feature. This can be useful for understanding which user properties influence a particular feature’s behavior.Field Mapping
The fields returned by these methods correspond to the following user properties:FAQ
How do I run experiments for logged out users?
How do I run experiments for logged out users?
See the guide on device level experiments
Reference
Fields Needed Methods (Enterprise Only)
This is available for Enterprise contracts. Please reach out to our support team, your sales contact, or via our slack channel if you want this enabled.