On this page

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.

bash
gem 'amplitude-experiment'

Quick start

  1. Initialize the experiment client
  2. Fetch variants for the user
  3. Access a flag's variant
ruby
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.

ruby
initialize_remote(apiKey, config = nil) : Client

Timeout and retry configuration

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

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

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.

ruby
fetch_v2(user: AmplitudeExperiment::User, fetch_options: AmplitudeExperiment::FetchOptions = nil) : Variants

FetchOptions

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

ruby
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

ruby
fetch_async_v2(user: AmplitudeExperiment::User, fetch_options: AmplitudeExperiment::FetchOptions = nil, &callback)
ruby
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+.

bash
gem 'amplitude-experiment'

Quick start

  1. Initialize the experiment client
  2. Start the local evaluation client
  3. Evaluate a user
ruby
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.

ruby
AmplitudeExperiment.initialize_local(api_key)

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

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
  • flush_interval_millis
    • Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every flush_interval_millis milliseconds.
    • Default Value: 10 seconds
  • 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_id and device_id.
    • Default Value: 5
  • callback
    • Description:
      • Client level callback function. Takes three parameters:
        1. event: a Event instance
        1. code: a integer of HTTP response code
        1. message: a string message.
    • Default Value: nil
  • server_zone
    • Description: The server zone of the projects. Supports EU and US. For EU data residency, Change to EU.
    • Default Value: US
  • server_url
    • Description: The API endpoint URL where Experiment sends events. Automatically selected by server_zone and use_batch. If you set this field to a string value instead of nil, the SDK ignores server_zone and use_batch and uses the string value.
    • Default Value: https://api2.amplitude.com/2/httpapi
  • use_batch
    • Description: Whether to use batch API. By default, the SDK uses the default serverUrl.
    • Default Value: False
  • 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

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
  • flush_interval_millis
    • Description: Events wait in the buffer, and Experiment sends them in a batch. The buffer is flushed every flush_interval_millis milliseconds.
    • Default Value: 10 seconds
  • 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_id and device_id.
    • Default Value: 5
  • callback
    • Description:
      • Client level callback function. Takes three parameters:
        1. event: a Event instance
        1. code: a integer of HTTP response code
        1. message: a string message.
    • Default Value: nil
  • server_zone
    • Description: The server zone of the projects. Supports EU and US. For EU data residency, Change to EU.
    • Default Value: US
  • server_url
    • Description: The API endpoint URL where Experiment sends events. Automatically selected by server_zone and use_batch. If you set this field to a string value instead of nil, the SDK ignores server_zone and use_batch and uses the string value.
    • Default Value: https://api2.amplitude.com/2/httpapi
  • use_batch
    • Description: Whether to use batch API. By default, the SDK uses the default serverUrl.
    • Default Value: False
  • 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

CohortSyncConfig

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.

ruby
start

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

ruby
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().

ruby
evaluate_v2(user: AmplitudeExperiment::User, flag_keys: Array[String] = [], options: AmplitudeExperiment::EvaluateOptions = nil) : Hash[String, Variant]
ruby
# 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

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.

ruby
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:

ruby
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

ruby
# 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:

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

ruby
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?