Elixir Core Server SDK
Statsig Server Core
Statsig Server Core is currently in beta - we encourage you to try it out and give us feedback in the Statsig Slack.
Statsig Server Core is a performance-focused rewrite of Statsig server SDKs with a shared core Rust library, that we're rolling out as an option for each Server Environment we currently support with SDKs.
Server Core brings Rust's natural speed and performance optimizations to each language, as we develop them in one, shared library. Initial benchmarking suggests Server Core can evaluate 5-10x as fast as existing SDKs. Alongside evaluation performance improvement, we introduced new compression mechanism, which should reduce outbound (egress) network payload significantly.
Server Core does not currently resolve User Agents or Countries. Expect this addition in the near future.
Server Core also introduces many new features, for example,
- Param Stores, including bootstrap with param stores,
- SDK Observability Interface
- Streaming Config Specs and etc.
Server Core is currently available for Java, Node, and Python. Need another language? Let us know in the Statsig Slack and we'll prioritize it.
Installation
To use the SDK, add the following to your mix.exs:
{:statsig_elixir, "~> 0.0.6-beta.7"},
SDK is written using rustler_precompiled, which will download precompiled binary by default. But there is also an option to build Rust code within your project by
# set the environment variable
FORCE_STATSIG_NATIVE_BUILD="true"
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 expose it, you can create a new one in the Statsig console.
options
that allows you to pass in a StatsigOptions to customize the SDK.Statsig.ex is using GenServer to manage the actual implementation of statsig instance (which is written in Rust). Which requires you add Statsig into your Supervision Tree.
# Initializing, with StatsigOptions
sdk_key = "secret-key******" # your secret key
statsig_options = %StatsigOptions{enable_id_lists: true}
# Add to your supervision tree
statsig_spec = %{id: Statsig, start: {Statsig, :start_link, [sdk_key, statsig_options]}}
children = [
// Other Apps
statsig_spec
]
res = Supervisor.start_link(children, opts)
# Or directly initialize the GenServer
{:ok,_} = Statsig.start_link(sdk_key, statsig_options)
Statsig.initialize()
# Don't forget to shutdown when done
Statsig.shutdown()
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:
user = %StatsigUser{
user_id: "test_user_123"
}
{:ok, check_gate} = Statsig.check_gate("test_public", user)
# check_gate will be a boolean
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:
# Get a dynamic config for a specific user
user = %StatsigUser{
user_id: "test_user_123"
}
{:ok, config} = Statsig.get_config("a_config", user)
# Access the values in the dynamic config:
param_value = DynamicConfig.get_param_value(config, "header_text")
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.
# Values via get_layer
user = %StatsigUser{
user_id: "test_user_123"
}
{:ok, layer} = Statsig.get_layer("user_promo_experiments", user)
{:ok, title_string_value} = Layer.get(layer, "title", "Welcome to Statsig!")
{:ok, discount_float_value} = Layer.get(layer, "discount", 0.1)
# Via get_experiment
{:ok, experiment} = Statsig.get_experiment("user_promo_experiment", user)
title_exp = Experiment.get_param_value(experiment, "new_user_promo_title")
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:
result = Statsig.log_event(user, "test_event", 1, %{"metadata_1" => "value"})
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:
{:ok, feature_gate} = Statsig.get_feature_gate(user, "example_gate")
# access the value, or the name off of the feature_gate 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
StatsigOptions Class
Parameters
-
environment:
: The environment you're operating in (e.g., Production) -
output_log_level:
: The type of logs you'd like exposed. (e.g., Debug) -
init_timeout_ms:
: How long it should take for initialization to time out. -
event_logging_flush_interval_ms:
: How often events should flush to the Statsig servers. -
event_logging_max_queue_size:
: How many events should be buffered before flushing to the Statsig servers. -
log_event_url:
: The URL events should be logged to -
specs_sync_interval_ms:
: How often specs should sync from the Statsig servers -
specs_url:
: The URL Statsig should download specs from -
enable_id_lists:
: If ID list download should be enabled -
id_lists_url:
: The URL ID lists should be downloaded from -
id_lists_sync_interval_ms:
: How often ID lists should be synced.
Example Usage
# Initialize StatsigOptions with custom parameters
statsig_options = %StatsigOptions{
enable_id_lists: true
}
# Pass the options object into statsig.initialize()
{:ok, _} = Statsig.start_link(sdk_key, statsig_options)
Statsig.initialize()
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