Skip to main content

.NET Core Server SDK (Beta)

Installation

dotnet add package Statsig.Dotnet

Or add the package reference to your .csproj file:

<PackageReference Include="Statsig.Dotnet" Version="X.X.X" />

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.

using Statsig;

var statsig = new Statsig("server-secret-key");
await statsig.Initialize();

You can also provide custom options:

var options = new StatsigOptionsBuilder()
.SetEnvironment("production")
.SetSpecsSyncIntervalMs(10000)
.SetDisableAllLogging(false)
.Build();

var statsig = new Statsig("server-secret-key", options);
await statsig.Initialize();

For shared instance usage:

var sharedStatsig = Statsig.NewShared("server-secret-key", options);
await sharedStatsig.Initialize();

var statsig = Statsig.Shared();

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:

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.SetEmail("user@example.com")
.Build();

var gateValue = statsig.CheckGate(user, "new_feature_gate");
if (gateValue)
{
// Gate is on, enable new feature
}
else
{
// Gate is off
}

You can also disable exposure logging for this evaluation:

var options = new EvaluationOptions(disableExposureLogging: true);
var gateValue = statsig.CheckGate(user, "new_feature_gate", options);

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:

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.Build();

var config = statsig.GetDynamicConfig(user, "product_config");

var productName = config.Get<string>("product_name", "Default Product");
var price = config.Get<double>("price", 9.99);
var isEnabled = config.Get<bool>("enabled", false);
var features = config.Get<List<string>>("features", new List<string>());

Console.WriteLine($"Config Name: {config.Name}");
Console.WriteLine($"Group Name: {config.GroupName}");
Console.WriteLine($"Rule ID: {config.RuleID}");

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.

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.Build();

var experiment = statsig.GetExperiment(user, "button_color_test");

var buttonColor = experiment.Get<string>("color", "blue");
var fontSize = experiment.Get<int>("font_size", 14);
var showBorder = experiment.Get<bool>("show_border", true);

Console.WriteLine($"Experiment Name: {experiment.Name}");
Console.WriteLine($"Group Name: {experiment.GroupName}");
Console.WriteLine($"Rule ID: {experiment.RuleID}");
Console.WriteLine($"Button Color: {buttonColor}");

Parameter Stores

Parameter stores are not yet available for this sdk. Need it now? Let us know in Slack.

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:

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.Build();

statsig.LogEvent(user, "button_clicked");

statsig.LogEvent(user, "purchase_completed", 29.99);

statsig.LogEvent(user, "page_view", "homepage", new Dictionary<string, string>
{
["referrer"] = "google",
["campaign"] = "summer_sale"
});

statsig.LogEvent(user, "video_watched", 120, new Dictionary<string, string>
{
["video_id"] = "abc123",
["quality"] = "1080p"
});

The LogEvent method supports multiple overloads:

  • LogEvent(user, eventName)
  • LogEvent(user, eventName, stringValue, metadata)
  • LogEvent(user, eventName, intValue, metadata)
  • LogEvent(user, eventName, doubleValue, 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:

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.Build();

var gate = statsig.GetFeatureGate(user, "new_feature_gate");

Console.WriteLine($"Gate Name: {gate.Name}");
Console.WriteLine($"Gate Value: {gate.Value}");
Console.WriteLine($"Rule ID: {gate.RuleID}");
Console.WriteLine($"ID Type: {gate.IDType}");

if (gate.EvaluationDetails != null)
{
Console.WriteLine($"Config Sync Time: {gate.EvaluationDetails.ConfigSyncTime}");
Console.WriteLine($"Init Time: {gate.EvaluationDetails.InitTime}");
Console.WriteLine($"Reason: {gate.EvaluationDetails.Reason}");
}

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

note

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

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

StatsigOptions can be configured using the StatsigOptionsBuilder pattern:

var options = new StatsigOptionsBuilder()
.SetSpecsURL("https://custom-api.statsig.com/v1/download_config_specs")
.SetLogEventURL("https://custom-api.statsig.com/v1/rgstr")
.SetEnvironment("production")
.SetSpecsSyncIntervalMs(30000)
.SetEventLoggingMaxQueueSize(1000)
.SetWaitForCountryLookupInit(true)
.SetWaitForUserAgentInit(true)
.SetDisableCountryLookup(false)
.SetDisableUserAgentParsing(false)
.SetDisableAllLogging(false)
.SetEnableIDLists(true)
.SetIDListsURL("https://custom-api.statsig.com/v1/get_id_lists")
.SetIDListsSyncIntervalMs(60000)
.SetGlobalCustomFields(new Dictionary<string, object>
{
["app_version"] = "1.2.3",
["build_number"] = "456"
})
.Build();

var statsig = new Statsig("server-secret-key", options);

Available Options

  • SetSpecsURL(string): Override the default specs download endpoint
  • SetLogEventURL(string): Override the default event logging endpoint
  • SetEnvironment(string): Set the environment tier (e.g., "production", "staging")
  • SetSpecsSyncIntervalMs(int): How often to sync configuration specs (default: 10000ms)
  • SetEventLoggingMaxQueueSize(int): Maximum events to queue before flushing
  • SetWaitForCountryLookupInit(bool): Wait for country lookup initialization
  • SetWaitForUserAgentInit(bool): Wait for user agent parsing initialization
  • SetDisableCountryLookup(bool): Disable automatic country detection
  • SetDisableUserAgentParsing(bool): Disable user agent parsing
  • SetDisableAllLogging(bool): Disable all event logging
  • SetEnableIDLists(bool): Enable ID list targeting
  • SetIDListsURL(string): Override the default ID lists endpoint
  • SetIDListsSyncIntervalMs(int): How often to sync ID lists (default: 60000ms)
  • SetGlobalCustomFields(Dictionary<string, object>): Global custom fields for all events

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:

await statsig.FlushEvents();

await statsig.Shutdown();

statsig.Dispose();

For shared instances:

var statsig = Statsig.Shared();
await statsig.FlushEvents();
await statsig.Shutdown();

Statsig.RemoveSharedInstance();

Methods

  • FlushEvents(): Immediately flush any pending events to Statsig servers
  • Shutdown(): Gracefully shutdown the SDK, flushing events and cleaning up resources
  • Dispose(): Release native resources (implements IDisposable)

It's recommended to call FlushEvents() before Shutdown() to ensure all events are sent, and always call Dispose() or use using statements to properly clean up resources.

Client SDK Bootstrapping | SSR v1.0.0+

The .NET Core server SDK supports generating the initializeValues needed to initialize a Statsig Client SDK, letting you pair your client-side initialize() calls with other requests to your server, effectively enabling zero-latency client SDK startup.

var user = new StatsigUserBuilder()
.SetUserID("user_123")
.Build();

var initResponse = statsig.GetClientInitializeResponse(user);

var options = new ClientInitResponseOptions
{
HashAlgorithm = "sha256",
ClientSDKKey = "client-sdk-key",
IncludeLocalOverrides = false
};

var customInitResponse = statsig.GetClientInitializeResponse(user, options);

The GetClientInitializeResponse method returns a JSON string containing the initialization data needed by client-side SDKs. This enables server-side rendering and reduces client initialization time.

ClientInitResponseOptions

  • HashAlgorithm: Hash algorithm for response integrity (default: "djb2")
  • ClientSDKKey: Client SDK key to include in response
  • IncludeLocalOverrides: Whether to include local overrides in the response (default: false)

Working with IP or UserAgent Values

The server SDK will not automatically use the ip, or userAgent for gate evaluation as Statsig servers would, since we don't have access to the request headers. If you'd like to use the attributes we derive from these properties, like Browser Name/Version, OS Name/Version & Country, you must manually set the ip and userAgent fields on the user object when calling GetClientInitializeResponse.

Working with IDs

To ensure that the server SDK evaluates each config accurately, they need access to all user attributes that the client SDK leverages. We recommend passing all of these attributes to the server SDK - using tools like Cookies if needed to ensure they're attached on first requests. If the user objects on the client and server aren't identical, modern SDKs will throw an InvalidBootstrap warning.

Client SDKs also auto-generate a StableID, and its important to manage the lifecycle of this ID to be sure that it is consistent on client and server side. Managing this with a cookie is often easiest, see Keeping StableID Consistent. If StableID differs between Client and Server, you'll see a BootstrapStableIDMismatch warning, and checks with this warning won't contribute to your experiment analyses.

getClientInitializeResponse and the legacy JS SDK

If you are migrating from the legacy JS Client, you will need to make some updates to how your server SDK generates values. The default hashing algorithm was changed from sha256 to djb2 for performance and size reasons.

See the Bootstrapping Migration Docs for more.

Local Overrides v1.0.0+

To override the return value of a gate/config/experiment/layer locally, we expose a set of override APIs. Coupling this with StatsigOptions.disable_network can be helpful when writing unit tests.

statsig.OverrideGate("test_gate", true);

statsig.OverrideDynamicConfig("test_config", new Dictionary<string, object>
{
["color"] = "red",
["size"] = 42,
["enabled"] = true
});

statsig.OverrideExperiment("test_experiment", new Dictionary<string, object>
{
["variant"] = "treatment",
["multiplier"] = 1.5
});

statsig.OverrideExperimentByGroupName("test_experiment", "treatment_group");

statsig.OverrideLayer("test_layer", new Dictionary<string, object>
{
["theme"] = "dark",
["font_size"] = 16
});

You can also specify a user ID for targeted overrides:

statsig.OverrideGate("test_gate", true, "user_123");

statsig.OverrideDynamicConfig("test_config", new Dictionary<string, object>
{
["special_feature"] = true
}, "user_123");

Local overrides are useful for:

  • Testing specific configurations during development
  • QA testing with known values
  • Debugging feature flag behavior
  • Integration testing with predictable results

Note: Overrides persist for the lifetime of the Statsig instance and affect all evaluations unless a specific user ID is provided.

note
  1. These only apply locally - they do not update definitions in the Statsig console or elsewhere.
  2. The local override API is not designed to be a full mock. They are only a convenient way to override the value of the gate/config/etc.

Manual Exposures

warning

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.

To check a gate without an exposure being logged, call the following.

Later, if you would like to expose this gate, you can call the following.

Performance Benefits

The .NET Core SDK leverages Statsig's high-performance Rust evaluation engine through FFI bindings, providing:

  • Sub-millisecond evaluation times for feature gates and experiments
  • Memory-efficient configuration caching and user context handling
  • Concurrent evaluation support for high-throughput applications
  • Optimized network communication with automatic retry logic and compression

FFI Architecture

The SDK uses Foreign Function Interface (FFI) to communicate with the Rust core:

  • Native Rust evaluation engine handles all rule processing
  • .NET wrapper provides familiar C# APIs and type safety
  • Automatic memory management between .NET and Rust boundaries
  • Thread-safe operations across the FFI boundary

Async/Await Support

All network operations are fully async:

await statsig.Initialize();
await statsig.FlushEvents();
await statsig.Shutdown();

Evaluation methods are synchronous for optimal performance:

var result = statsig.CheckGate(user, "gate_name");

Thread Safety

The Statsig instance is thread-safe and can be used concurrently across multiple threads. Consider using the shared instance pattern for application-wide usage:

var sharedStatsig = Statsig.NewShared("server-secret-key");
await sharedStatsig.Initialize();

var statsig = Statsig.Shared();

Error Handling

The SDK handles network errors gracefully:

  • Automatic retries with exponential backoff
  • Fallback to cached configurations during network issues
  • Default values returned when evaluations fail
  • Comprehensive logging for debugging

Requirements

  • .NET 8.0 or later
  • Windows, macOS, or Linux (x64 and ARM64 supported)
  • Network access to Statsig APIs (configurable endpoints)