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 using 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.
gem 'amplitude-experiment'
Quick start
require 'amplitude-experiment'
# (1) Initialize the experiment client
experiment = AmplitudeExperiment.initialize_remote('<DEPLOYMENT_KEY>', AmplitudeExperiment::RemoteEvaluationConfig.new)
# (2) Fetch variants for a user
user = AmplitudeExperiment::User.new(
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium' => true
}
)
variants = experiment.fetch_v2(user)
# (3) Access a flag's variant
variant = variants['YOUR-FLAG-KEY']
unless variant.nil?
if variant.value == 'on'
# Flag is on
else
# Flag is off
end
end
Initialize
Initialize the SDK client in your server on startup. The deployment key argument you pass to the apiKey parameter must live within the same project that you are sending analytics events to.
initialize_remote(apiKey, config = nil) : Client
| Parameter | Requirement | Description |
|---|---|---|
apiKey | required | The deployment key that authorizes fetch requests and determines which flags to evaluate 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.
experiment = 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 | When true, sets the logger level to DEBUG. | false |
logger | Custom Logger instance for SDK logging. | Default Logger with ERROR level |
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. The SDK scales this delay by the fetchRetryBackoffScalar | 500 |
fetch_retry_backoff_max_millis | The maximum backoff between retries. If the scaled backoff becomes greater than the max, the SDK uses the max 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. The function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.
fetch_v2(user: AmplitudeExperiment::User, fetch_options: AmplitudeExperiment::FetchOptions = nil) : Variants
FetchOptions
| Name | Description | Default Value |
|---|---|---|
tracks_exposure | To track or not track an exposure event for this fetch request. If nil, uses the server's default behavior (doesn't track exposure). | nil |
tracks_assignment | To track or not track an assignment event for this fetch request. If nil, uses the server's default behavior (does track assignment). | nil |
user = AmplitudeExperiment::User.new(
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium' => true
}
)
variants = experiment.fetch_v2(user)
After fetching variants for a user, you may to access the variant for a specific flag.
variant = variants['YOUR-FLAG-KEY']
unless variant.nil?
if variant.value == 'on'
# Flag is on
else
# Flag is off
end
end
Fetch async
The fetch method is synchronous. To fetch asynchronously, you can use fetch_async method
fetch_async_v2(user: AmplitudeExperiment::User, fetch_options: AmplitudeExperiment::FetchOptions = nil, &callback)
experiment.fetch_async_v2(user) do |_, variants|
variant = variants['sdk-ci-test']
unless variant.nil?
if variant.value == 'on'
# Flag is on
else
# Flag is off
end
end
end
Local evaluation
Implements evaluating variants for a user using local evaluation. If you plan to use local evaluation, understand the tradeoffs.
Install
Install the Ruby Server SDK's local evaluation.
The local evaluation package supports the following OS' and architectures (OS/ARCH):
Supported
- darwin/amd64
- darwin/arm64
- linux/amd64
- linux/arm64
The local evaluation package doesn't support Alpine Linux at this time.
If you need another OS/Arch supported, 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+.
gem 'amplitude-experiment'
Quick start
require 'amplitude-experiment'
# (1) Initialize the local evaluation client with a server deployment key.
experiment = AmplitudeExperiment.initialize_local('DEPLOYMENT_KEY',
# (Recommended) Enable local evaluation cohort targeting.
AmplitudeExperiment::LocalEvaluationConfig.new(
cohort_sync_config: AmplitudeExperiment::CohortSyncConfig.new(
api_key: 'API_KEY',
secret_key: 'SECRET_KEY'
)
)
)
# (2) Start the local evaluation
experiment.start
# (3) Evaluate a user
user = AmplitudeExperiment::User.new(
user_id: 'user@company.com',
device_id: 'abcdefg',
user_properties: {
'premium' => true
}
)
variants = experiment.evaluate_v2(user)
variant = variants['YOUR-FLAG-KEY']
unless variant.nil?
if variant.value == 'on'
# Flag is on
else
# Flag is off
end
end
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.
AmplitudeExperiment.initialize_local(api_key)
| Parameter | Requirement | Description |
|---|---|---|
apiKey | required | The server deployment key that authorizes fetch requests and determines which flags to evaluate 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 after modification (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 | When true, sets the logger level to DEBUG. | false |
logger | Custom Logger instance for SDK logging. | Default Logger with ERROR level |
assignment_config | Deprecated. Configuration for automatically tracking assignment events after an evaluation. | nil |
exposure_config | Configuration for tracking exposure events after an evaluation. | nil |
cohort_sync_config | Configuration to enable cohort downloading for local evaluation cohort targeting. | nil |
AssignmentConfig
api_key- Description: The analytics API key and NOT the experiment deployment key
- Default Value: required
cache_capacity- Description: The maximum number of assignments stored in the assignment cache
- Default Value:
65536
flush_queue_size- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed when the number of events reaches
flush_queue_size. - Default Value:
200
- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed when the number of events reaches
flush_interval_millis- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every
flush_interval_millismilliseconds. - Default Value:
10 seconds
- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every
flush_max_retries- Description: The number of times the client retries an event when the request returns an error.
- Default Value:
12
logger- Description: The logger instance used by Amplitude client.
- Default Value: Default Ruby logger
min_id_length- Description: The minimum length of
user_idanddevice_id. - Default Value:
5
- Description: The minimum length of
callback- Description:
- Client level callback function. Takes three parameters:
- event: a Event instance
- code: a integer of HTTP response code
- message: a string message.
- Default Value:
nil
- Description:
server_zone- Description: The server zone of the projects. Supports
EUandUS. For EU data residency, Change toEU. - Default Value:
US
- Description: The server zone of the projects. Supports
server_url- Description: The API endpoint URL where Experiment sends events. Automatically selected by
server_zoneanduse_batch. If you set this field to a string value instead ofnil, the SDK ignoresserver_zoneanduse_batchand uses the string value. - Default Value:
https://api2.amplitude.com/2/httpapi
- Description: The API endpoint URL where Experiment sends events. Automatically selected by
use_batch- Description: Whether to use batch API. By default, the SDK uses the default
serverUrl. - Default Value:
False
- Description: Whether to use batch API. By default, the SDK uses the default
storage_provider- Description: Used to create storage instance to hold events in the storage buffer. Events in storage buffer are waiting to be sent.
- Default Value:
InMemoryStorageProvider
opt_out- Description: Opt out option. If set to
True, client doesn't process and send events. - Default Value:
False
- Description: Opt out option. If set to
ExposureConfig
api_key- Description: The analytics API key and NOT the experiment deployment key
- Default Value: required
cache_capacity- Description: The maximum number of exposures stored in the exposure cache
- Default Value:
65536
flush_queue_size- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed when the number of events reaches
flush_queue_size. - Default Value:
200
- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed when the number of events reaches
flush_interval_millis- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every
flush_interval_millismilliseconds. - Default Value:
10 seconds
- Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every
flush_max_retries- Description: The number of times the client retries an event when the request returns an error.
- Default Value:
12
logger- Description: The logger instance used by Amplitude client.
- Default Value: Default Ruby logger
min_id_length- Description: The minimum length of
user_idanddevice_id. - Default Value:
5
- Description: The minimum length of
callback- Description:
- Client level callback function. Takes three parameters:
- event: a Event instance
- code: a integer of HTTP response code
- message: a string message.
- Default Value:
nil
- Description:
server_zone- Description: The server zone of the projects. Supports
EUandUS. For EU data residency, Change toEU. - Default Value:
US
- Description: The server zone of the projects. Supports
server_url- Description: The API endpoint URL where Experiment sends events. Automatically selected by
server_zoneanduse_batch. If you set this field to a string value instead ofnil, the SDK ignoresserver_zoneanduse_batchand uses the string value. - Default Value:
https://api2.amplitude.com/2/httpapi
- Description: The API endpoint URL where Experiment sends events. Automatically selected by
use_batch- Description: Whether to use batch API. By default, the SDK uses the default
serverUrl. - Default Value:
False
- Description: Whether to use batch API. By default, the SDK uses the default
storage_provider- Description: Used to create storage instance to hold events in the storage buffer. Events in storage buffer are waiting to be sent.
- Default Value:
InMemoryStorageProvider
opt_out- Description: Opt out option. If set to
True, client doesn't process and send events. - Default Value:
False
- Description: Opt out option. If set to
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 downloads. The SDK doesn't download cohorts larger than this size. | 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 overrides 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.
start
You should await the result of start to ensure that flag configs are ready to be used before calling evaluate()
experiment.start
Evaluate
Executes the evaluation logic using the flags pre-fetched on start. You must give evaluate a user object argument. You can optionally pass an array of flag keys if you require only a specific subset of flag variants.
Exposure tracking
Set exposure_config to enable exposure tracking. Then, set tracks_exposure to true in EvaluateOptions when calling evaluate_v2().
evaluate_v2(user: AmplitudeExperiment::User, flag_keys: Array[String] = [], options: AmplitudeExperiment::EvaluateOptions = nil) : Hash[String, Variant]
# The user to evaluate
user = AmplitudeExperiment::User.new(user_id: 'test-user')
# Evaluate all flag variants
all_variants = experiment.evaluate_v2(user)
# Evaluate a specific subset of flag variants
specific_variants = experiment.evaluate_v2(user, ["<FLAG_KEY_1>", "<FLAG_KEY_2>"])
# Access a variant
variant = all_variants["<FLAG_KEY>"]
if variant.value == 'on':
# Flag is on
else:
# Flag is off
end
EvaluateOptions
| Name | Description | Default Value |
|---|---|---|
tracks_exposure | If true, the SDK tracks an exposure event for the evaluated variants. | false |
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.
experiment = AmplitudeExperiment.initialize_local('DEPLOYMENT_KEY',
# (Recommended) Enable local evaluation cohort targeting.
AmplitudeExperiment::LocalEvaluationConfig.new(
cohort_sync_config: AmplitudeExperiment::CohortSyncConfig.new(
api_key: 'API_KEY',
secret_key: 'SECRET_KEY'
)
)
)
Custom logging
Provide your own Logger instance to control logging behavior.
Custom logger
Pass a custom Logger instance to RemoteEvaluationConfig or LocalEvaluationConfig:
require 'logger'
require 'amplitude-experiment'
# Create a custom logger
custom_logger = Logger.new('experiment.log')
custom_logger.level = Logger::WARN
custom_logger.formatter = proc do |severity, datetime, progname, msg|
"#{datetime}: #{severity} - #{msg}\n"
end
# Remote evaluation with custom logger
remote_config = AmplitudeExperiment::RemoteEvaluationConfig.new(
logger: custom_logger
)
experiment = AmplitudeExperiment.initialize_remote('DEPLOYMENT_KEY', remote_config)
# Provide Local evaluation with your Rails logger
local_config = AmplitudeExperiment::LocalEvaluationConfig.new(
logger: Rails.logger
)
experiment = AmplitudeExperiment.initialize_local('DEPLOYMENT_KEY', local_config)
Debug flag with default logger
# Without custom logger, debug=false uses ERROR level
config = AmplitudeExperiment::RemoteEvaluationConfig.new(
debug: false
)
# Default logger level is ERROR
# Without custom logger, debug=true uses DEBUG level
config = AmplitudeExperiment::RemoteEvaluationConfig.new(
debug: true
)
# Default logger level is DEBUG
When you provide a custom logger, the SDK ignores the debug flag and your logger keeps its configured level:
custom_logger = Logger.new($stdout)
custom_logger.level = Logger::WARN
# Custom logger maintains its WARN level regardless of debug flag
config = AmplitudeExperiment::RemoteEvaluationConfig.new(
logger: custom_logger,
debug: true
)
# Logger level stays WARN (debug flag is ignored)
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.
require 'amplitude-experiment'
require 'securerandom'
# Get the cookie name for the Amplitude API key
# Use new_format: true for Browser SDK 2.0 cookies
amp_cookie_name = AmplitudeExperiment::AmplitudeCookie.cookie_name('amplitude-api-key')
# For Browser SDK 2.0: AmplitudeExperiment::AmplitudeCookie.cookie_name('amplitude-api-key', new_format: true)
device_id = nil
# Try to get device ID from existing cookie
unless cookies[amp_cookie_name].nil?
device_id = AmplitudeExperiment::AmplitudeCookie.parse(cookies[amp_cookie_name]).device_id
# For Browser SDK 2.0: AmplitudeExperiment::AmplitudeCookie.parse(cookies[amp_cookie_name], new_format: true).device_id
end
# If no device ID found, generate a new one and set the cookie
if device_id.nil?
device_id = SecureRandom.uuid
amp_cookie_value = AmplitudeExperiment::AmplitudeCookie.generate(device_id)
# For Browser SDK 2.0: AmplitudeExperiment::AmplitudeCookie.generate(device_id, new_format: true)
cookies[amp_cookie_name] = {
value: amp_cookie_value,
domain: '.your-domain.com', # this should be the same domain used by the Amplitude JS SDK
httponly: false,
secure: false
}
end
Was this helpful?