Experiment Ruby SDK

Official documentation for Amplitude Experiment's server-side Ruby SDK implementation.

This documentation is split into two sections for remote and local evaluation:

Remote evaluation

Implements fetching variants for a user via remote evaluation.

Install

Ruby version compatibility

The Ruby Server SDK works with Ruby 2.0+.

Install the Ruby Server SDK with bundler or gem directly.

1gem 'amplitude-experiment'

1gem install amplitude-experiment

Quick start

  1. Initialize the experiment client
  2. Fetch variants for the user
  3. Access a flag's variant
1require 'amplitude-experiment'
2 
3# (1) Initialize the experiment client
4experiment = AmplitudeExperiment.initialize_remote('<DEPLOYMENT_KEY>', AmplitudeExperiment::RemoteEvaluationConfig.new)
5 
6# (2) Fetch variants for a user
7user = AmplitudeExperiment::User.new(
8 user_id: 'user@company.com',
9 device_id: 'abcdefg',
10 user_properties: {
11 'premium' => true
12 }
13)
14variants = experiment.fetch(user)
15 
16# (3) Access a flag's variant
17variant = variants['YOUR-FLAG-KEY']
18unless variant.nil?
19 if variant.value == 'on'
20 # Flag is on
21 else
22 # Flag is off
23 end
24end

Initialize

The SDK client should be initialized in your server on startup. The deployment key argument passed into the apiKey parameter must live within the same project that you are sending analytics events to.

1initialize_remote(apiKey, config = nil) : Client
Parameter Requirement Description
apiKey required The deployment key which authorizes fetch requests and determines which flags should be evaluated for the user.
config optional The client configuration used to customize SDK client behavior.

Timeout and retry configuration

Configure the timeout and retry options to best fit your performance requirements.

1experiment = AmplitudeExperiment.initialize_remote('<DEPLOYMENT_KEY>', AmplitudeExperiment::RemoteEvaluationConfig.new)

Configuration

You can configure the SDK client on initialization.

EU data center

If you're using Amplitude's EU data center, configure the server_zone option on initialization.

Name
Description Default Value
debug Enable additional debug logging. false
server_zone The Amplitude data center to use. Either ServerZone::US or ServerZone::EU ServerZone::US
server_url The host to fetch variants from. https://api.lab.amplitude.com
fetch_timeout_millis The timeout for fetching variants in milliseconds. This timeout only applies to the initial request, not subsequent retries 10000
fetch_retries The number of retries to attempt if a request to fetch variants fails. 0
fetch_retry_backoff_min_millis The minimum (initial) backoff after a request to fetch variants fails. This delay is scaled by the fetchRetryBackoffScalar 500
fetch_retry_backoff_max_millis The maximum backoff between retries. If the scaled backoff becomes greater than the max, the max is used for all subsequent requests 10000
fetch_retry_backoff_scalar Scales the minimum backoff exponentially. 1.5
fetch_retry_timeout_millis The request timeout for retrying variant fetches. 10000

Fetch

Fetches variants for a user and returns the results. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.

1fetch(user: AmplitudeExperiment::User) : Variants
Parameter Requirement Description
user required The user to remote fetch variants for.
1user = AmplitudeExperiment::User.new(
2 user_id: 'user@company.com',
3 device_id: 'abcdefg',
4 user_properties: {
5 'premium' => true
6 }
7)
8variants = experiment.fetch(user)

After fetching variants for a user, you may to access the variant for a specific flag.

1variant = variants['YOUR-FLAG-KEY']
2unless variant.nil?
3 if variant.value == 'on'
4 # Flag is on
5 else
6 # Flag is off
7 end
8end

Fetch async

The fetch method is synchronous. To fetch asynchronously, you can use fetch_async method

1fetch_async(user: AmplitudeExperiment::User, &callback)
Parameter Requirement Description
user required The user to remote fetch variants for.
callback optional The callback to handle the variants. Callback takes two arguments: User object and returned Variants.
1experiment.fetch_async(user) do |_, variants|
2 variant = variants['sdk-ci-test']
3 unless variant.nil?
4 if variant.value == 'on'
5 # Flag is on
6 else
7 # Flag is off
8 end
9 end
10end

Local evaluation

Implements evaluating variants for a user via local evaluation. If you plan on using local evaluation, you should understand the tradeoffs.

Install

Install the Ruby Server SDK's local evaluation.

Warning Operating system and architecture support

The local evaluation package currently only supports the following OS' and architectures (OS/ARCH):

Supported

  • darwin/amd64
  • darwin/arm64
  • linux/amd64
  • linux/arm64

Alpine linux is not supported at this time.

If you need another OS/Arch supported, please submit an issue on github or email experiment@amplitude.com.

Install the Ruby Server SDK with bundler or gem directly.

Ruby version compaitibility

The Ruby Server SDK works with Ruby 2.0+.

1gem 'amplitude-experiment'

1gem install amplitude-experiment

Quick start

  1. Initialize the experiment client
  2. Start the local evaluation client
  3. Evaluate a user
1require 'amplitude-experiment'
2 
3# (1) Initialize the local evaluation client with a server deployment key.
4experiment = AmplitudeExperiment.initialize_local('DEPLOYMENT_KEY',
5 # (Recommended) Enable local evaluation cohort targeting.
6 AmplitudeExperiment::LocalEvaluationConfig.new(
7 cohort_sync_config: AmplitudeExperiment::CohortSyncConfig.new(
8 api_key: 'API_KEY',
9 secret_key: 'SECRET_KEY'
10 )
11 )
12)
13 
14# (2) Start the local evaluation
15experiment.start
16 
17# (3) Evaluate a user
18user = AmplitudeExperiment::User.new(
19 user_id: 'user@company.com',
20 device_id: 'abcdefg',
21 user_properties: {
22 'premium' => true
23 }
24)
25variants = experiment.evaluate(user)
26variant = variants['YOUR-FLAG-KEY']
27unless variant.nil?
28 if variant.value == 'on'
29 # Flag is on
30 else
31 # Flag is off
32 end
33end

Initialize

Initializes a local evaluation client.

Server deployment key

You must initialize the local evaluation client with a server deployment key to get access to local evaluation flag configs.

1AmplitudeExperiment.initialize_local(api_key)
Parameter Requirement Description
apiKey required The server deployment key which authorizes fetch requests and determines which flags should be evaluated for the user.
config optional The client configuration used to customize SDK client behavior.

Flag polling interval

Use the flag_config_polling_interval_millis configuration to determine the time flag configs take to update once modified (default 30s).

Configuration

You can configure the SDK client on initialization.

EU data center

If you're using Amplitude's EU data center, configure the server_zone option on initialization.

LocalEvaluationConfig

Name
Description Default Value
server_zone The Amplitude data center to use. Either ServerZone::US or ServerZone::EU ServerZone::US
server_url The host to fetch flag configurations from. https://api.lab.amplitude.com
bootstrap Bootstrap the client with a map of flag key to flag configuration {}
flag_config_polling_interval_millis The interval to poll for updated flag configs after calling start 30000
debug Set to true to enable debug logging. false
assignment_config Configuration for automatically tracking assignment events after an evaluation. nil
cohort_sync_config Configuration to enable cohort downloading for local evaluation cohort targeting. nil

AssignmentConfig

Name
Description Default Value
api_key The analytics API key and NOT the experiment deployment key required
cache_capacity The maximum number of assignments stored in the assignment cache 65536
flush_queue_size Events wait in the buffer and are sent in a batch. The buffer is flushed when the number of events reaches flush_queue_size. 200
flush_interval_millis Events wait in the buffer and are sent in a batch. The buffer is flushed every flush_interval_millis milliseconds. 10 seconds
flush_max_retries The number of times the client retries an event when the request returns an error. 12
logger The logger instance used by Amplitude client. Default Ruby logger
min_id_length The minimum length of user_id and device_id. 5
callback Client level callback function. Takes three parameters:
1. event: a Event instance
2. code: a integer of HTTP response code
3. message: a string message.
nil
server_zone The server zone of the projects. Supports EU and US. For EU data residency, Change to EU. US
server_url The API endpoint URL that events are sent to. Automatically selected by server_zone and use_batch. If this field is set with a string value instead of nil, then server_zone and use_batch are ignored and the string value is used. https://api2.amplitude.com/2/httpapi
use_batch Whether to use batch API. By default, the SDK will use the default serverUrl. False
storage_provider Used to create storage instance to hold events in the storage buffer. Events in storage buffer are waiting to be sent. InMemoryStorageProvider
opt_out Opt out option. If set to True, client doesn't process and send events. False

CohortSyncConfig

Name
Description Default Value
api_key The analytics API key and NOT the experiment deployment key required
secret_key The analytics secret key required
max_cohort_size The maximum size of cohort that the SDK will download. Cohorts larger than this size will not be downloaded. 2147483647
cohort_polling_interval_millis The interval, in milliseconds, to poll Amplitude for cohort updates (60000 minimum). 60000
cohort_server_url The cohort server endpoint from which to fetch cohort data. For hitting the EU data center, set server_zone to EU. Setting this value will override server_zone defaults. https://cohort-v2.lab.amplitude.com

Start

Start the local evaluation client, pre-fetching local evaluation mode flag configs for evaluation and starting the flag config poller at the configured interval.

1start

You should await the result of start to ensure that flag configs are ready to be used before calling evaluate()

1experiment.start

Evaluate

Executes the evaluation logic using the flags pre-fetched on start. You must give evaluate a user object argument, and can you can optionally pass it an array of flag keys if only a specific subset of required flag variants are required.

Automatic assignment tracking

Set assignment_config to automatically track an assignment event to Amplitude when evaluate() is called.

1evaluate(user, flag_keys)
Parameter Requirement Description
user required The user to evaluate.
flag_keys optional Specific flags or experiments to evaluate. If nil, or empty, all flags and experiments are evaluated.
1# The user to evaluate
2user = AmplitudeExperiment::User.new(user_id: 'test-user')
3# Evaluate all flag variants
4all_variants = experiment.evaluate(user)
5# Evaluate a specific subset of flag variants
6specific_variants = experiment.evaluate(user, ["<FLAG_KEY_1>", "<FLAG_KEY_2>"])
7# Access a variant
8variant = all_variants["<FLAG_KEY>"]
9if variant.value == 'on':
10 # Flag is on
11else:
12 # Flag is off
13end

Local evaluation cohort targeting

Since version 1.5.0, the local evaluation SDK client supports downloading cohorts for local evaluation targeting. You must configure the cohort_sync_config option with the analytics api_key and secret_key on initialization to enable this support.

1experiment = AmplitudeExperiment.initialize_local('DEPLOYMENT_KEY',
2 # (Recommended) Enable local evaluation cohort targeting.
3 AmplitudeExperiment::LocalEvaluationConfig.new(
4 cohort_sync_config: AmplitudeExperiment::CohortSyncConfig.new(
5 api_key: 'API_KEY',
6 secret_key: 'SECRET_KEY'
7 )
8 )
9)

Access Amplitude cookies

If you're using the Amplitude Analytics SDK on the client-side, the Ruby server SDK provides an AmplitudeCookie class with convenience functions for parsing and interacting with the Amplitude identity cookie. This is useful for ensuring that the Device ID on the server matches the Device ID set on the client, especially if the client hasn't yet generated a Device ID.

1require 'amplitude-experiment'
2 
3# grab amp device id if present
4amp_cookie_name = AmplitudeExperiment::AmplitudeCookie.cookie_name('amplitude-api-key')
5device_id = nil
6unless cookies[amp_cookie_name].nil?
7 device_id = AmplitudeExperiment::AmplitudeCookie.parse(cookies[amp_cookie_name]).device_id
8end
9 
10if device_id.nil?
11 # deviceId doesn't exist, set the Amplitude Cookie
12 device_id = SecureRandom.uuid
13 amp_cookie_value = AmplitudeExperiment::AmplitudeCookie.generate(device_id)
14 cookies[amp_cookie_name] = {
15 value: amp_cookie_value,
16 domain: '.your-domain.com', # this should be the same domain used by the Amplitude JS SDK
17 httponly: false,
18 secure: false
19 }
20end
Was this page helpful?

Thanks for your feedback!

June 4th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.