Server SDKs

Ruby Server SDK

Evaluate configs and feature flags locally for any context with the Ruby server SDK, with updates delivered over server sent events to every process of your application, forked workers included

Introduction

The Ruby Server SDK is a server-side SDK that evaluates configs and their targeting rules. Upon initialization, it retrieves configs and targeting rules from ConfigDirector services. From that point on, it evaluates configs locally for any context, and receives updates via server sent events (SSE) when configs are updated on the dashboard or via the admin API.

The client is safe to share between threads. Each Ruby process holds its own client and its own connection to ConfigDirector: create the client the first time a process reads a config, share it for the lifetime of the process, and close it when the process exits. Evaluations read config state the client already holds in memory, so they make no network calls on the request path. Servers that fork their workers, such as Puma in cluster mode, are covered in Servers that fork their workers.

Installation

The SDK can be installed with Bundler. Its gem page is on RubyGems: https://rubygems.org/gems/configdirector-server-sdk

The minimum Ruby version supported is 3.3, on CRuby, the standard Ruby interpreter.

bundle add configdirector-server-sdk

The SDK depends only on gems of Ruby's standard library: logger, and net-http 0.10.0 or later, a newer release than Ruby ships. Your Gemfile.lock gains them, with net-protocol, timeout and uri.

Configure and initialize the client

  1. Create a client providing your server SDK key. You can retrieve a server SDK key for each environment under SDK keys in the dashboard's navigation panel. Creating the client makes no network call.
  2. Call init to connect and wait for the first values.
  3. Close the client when the process exits.

The example creates the client the first time a process reads a config, and returns that same client to every later read in the process:

lib/config_director_client_per_process.rb
require "configdirector"

# Creates the client the first time a process reads a config, and returns that client afterwards.
module ConfigDirectorClientPerProcess
  @lock = Mutex.new
  @client = nil

  def self.client
    @lock.synchronize { @client ||= created_and_initialized_client }
  end

  def self.created_and_initialized_client
    # IMPORTANT: Do not commit the server SDK key to your source code, it is a secret value.
    # Creating the client makes no network call.
    client = ConfigDirector.create_client(ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"))

    # Waits for the first values, up to the connection timeout. If none arrive in time, the client
    # keeps connecting in the background and reads return their in-code default value until they do.
    client.init

    # Reports what the process evaluated since the last report, and closes the connection.
    at_exit { client.close }
    client
  end

  private_class_method :created_and_initialized_client
end

Read through ConfigDirectorClientPerProcess.client wherever your application reads a config. The client is safe to share between threads, and each process creates its own, as Servers that fork their workers explains.

Server SDK keys are secret values. Do not commit them to your source code repository. Provide them at runtime via environment variables instead.

init waits for the first values, up to the connection timeout, and the client is ready once they arrive. It never raises because the connection failed, and every read returns its in-code default value until values arrive:

  • When no values arrive in time, it logs a warning and returns, and the client keeps connecting in the background.
  • When ConfigDirector refuses the connection, for example because it does not know the server SDK key, it logs an error, calls the connection_error handlers and returns at once. The client does not try again.
  • In polling mode, when the first request for values fails for another reason, it logs an error and returns at once, and the client asks again after the polling interval.

Calling init again waits again and never opens a second connection. On a closed client, init raises ConfigDirector::ConfigDirectorValidationError. ready? reports whether values have arrived.

The lock in the example matters on a threaded server such as Puma: without it, two first requests arriving together would each create and initialize a client. The at_exit handler closes the client when the process exits, which reports what the process evaluated since the last report; a process that exits without closing its client does not report its last reads.

Additional configuration options

ConfigDirector.create_client takes the server SDK key and the options below as keyword arguments. Only the key is required, and only outside offline mode. An option object cannot be changed once built, and with builds a copy with other values. An option the client cannot use, such as a blank server SDK key, an unknown connection mode, or a URL that is not an http or https URL, raises ConfigDirector::ConfigDirectorValidationError from create_client rather than returning a client that quietly never updates.

metadata

The metadata option allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"),
  metadata: ConfigDirector::Metadata.new(app_name: "YOUR-APP-NAME", app_version: "1.0.2")
)

A name or version that is not a String is read as its text, so app_version: 2 is "2".

logger and log_level

By default the SDK writes warnings and errors to standard error. The log_level option sets the lowest level it writes there, as Ruby's Logger takes it, such as :debug or Logger::INFO:

lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"), log_level: :debug)

To send the SDK's lines to your application's log, pass any object with the methods of Ruby's Logger (debug, info, warn and error) in the logger option, such as Rails.logger. The SDK calls each method with one String, and the logger's own level decides what is written, so log_level has no effect then:

lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"), logger: Rails.logger)

At the debug level the SDK logs each config it evaluates, such as [ConfigDirectorClient] Evaluated "new-checkout" to true (found-match).

connection

The connection option takes a ConfigDirector::ConnectionOptions with the following optional keyword arguments:

  • mode
    • The connection mode, one of "streaming", "polling" or "offline". It is recommended to use the default of streaming unless you have a specific need to use polling instead. In offline mode the client never connects to ConfigDirector and serves the values you give it; see Run without a connection.
    • Defaults to "streaming"
  • file
    • The path of a JSON file holding the values to serve in offline mode, as a String or a Pathname, resolved against the working directory of the process. Only one of file and values can be given, and only in offline mode. See Run without a connection.
  • values
    • The values to serve in offline mode, as a Hash keyed by config key. Only one of file and values can be given, and only in offline mode. See Run without a connection.
  • polling_interval
    • Only used in polling mode. How often the client asks ConfigDirector services for updates, in seconds. A value below the minimum of 60 seconds is raised to 60 seconds and a warning is logged. See Polling intervals.
    • Defaults to 300 seconds (5 minutes)
  • timeout
    • How long init waits for the first values, in seconds. If the timeout is reached, init returns but the client is still not ready and returns in-code default values. The client keeps trying to connect and retrieve config values in the background. In polling mode it is also how long each request for values may take. It has no effect in offline mode.
    • Defaults to 3 seconds
  • url
    • The base URL used to connect to ConfigDirector services
    • This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services. It has no effect in offline mode.
lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"),
  connection: ConfigDirector::ConnectionOptions.new(mode: "polling", polling_interval: 600, timeout: 5)
)

telemetry

Telemetry tuning. It is unlikely these settings need to be adjusted. However, in cases where your application has a large number of evaluations per second, you can adjust these settings to tune the memory footprint and frequency of telemetry requests.

Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features related to the configs being used.

Each evaluation the SDK reports says which variation was served and which percentage rollout and share served it. That is how ConfigDirector counts the contexts each variation of an experiment reached. Tracked events are sent with the same reports. The client sends its first report 5 seconds after init, then one every flush_interval, and close sends the last one.

The telemetry option takes a ConfigDirector::TelemetryOptions with the following optional keyword arguments:

  • event_queue_limit
    • The size limit of telemetry event queues. If the size limit is reached before the events are flushed to the network, older events are dropped.
    • ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than 50% of the total events, ConfigDirector issues an alert in the dashboard.
    • A number between 100 and 100,000. Defaults to 5,000.
  • flush_interval
    • How often events are flushed and sent over the network, in seconds.
    • Decrease this number if your application consistently captures a large number of events in short periods of time in order to reduce memory footprint from a large event queue.
    • Defaults to 30 seconds.
lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"),
  telemetry: ConfigDirector::TelemetryOptions.new(event_queue_limit: 10_000, flush_interval: 15)
)

Hooks

Hooks are events you can subscribe to in order to be notified of some key actions from the client. Subscribe with on, which takes the event name as a Symbol and a block, or any object that responds to call such as a lambda or method(:name), and returns a ConfigDirector::Subscription whose close removes the handler:

main.rb
subscription = client.on(:configs_updated) { |event| puts "Updated: #{event.keys.join(", ")}" }

subscription.close

Or give the handlers in the hooks option, a ConfigDirector::ClientHooks that takes one handler or an Array of handlers for each event. The client registers them before any handler registered with on, so they see the first values arrive:

lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  ENV.fetch("CONFIGDIRECTOR_SERVER_KEY"),
  hooks: ConfigDirector::ClientHooks.new(
    config_evaluated: ->(event) { puts "#{event.evaluation.key} evaluated to #{event.evaluation.value}" }
  )
)

The following hooks are available:

  • client_ready
    • Called with no argument when the client is initialized. When this event is emitted it means the client has received a payload from the ConfigDirector servers, or has loaded its offline values, and is ready to evaluate configs. It is emitted once, after the configs_updated handlers and the watches.
  • configs_updated: ConfigDirector::ConfigsUpdatedEvent
    • Called when a payload is received from the ConfigDirector servers with config data. It is emitted during initialization when an entire config payload is received, or when the offline values are loaded. After initialization, it is emitted when updates are pushed from the server (or discovered via polling if that connection mode is used).
    • keys - The config keys that were included in the payload from the server, in the order the server sent them, followed by the keys of configs whose targeting rules use a segment the payload included.
    • removed_keys - The keys of configs the payload removed. A config is removed when a full payload no longer includes it. Empty when nothing was removed.
  • config_evaluated: ConfigDirector::ConfigEvaluatedEvent
    • Called whenever a config is evaluated, before the read returns. This includes calls to get_value and evaluate, and evaluations delivered to watches.
    • evaluation - A ConfigDirector::ConfigEvaluation with the details of the evaluation:
      • key - The config key that was evaluated
      • value - The value the config evaluated to, of the class of the in-code default value. It can be the in-code default value provided to get_value or to the watch. For example, if the config was evaluated before the client was initialized.
      • value_id - The value ID, a stable hash of the value that you can send to a third party rather than the value. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves. It is nil when the evaluation fell back to the in-code default value. To report an experiment to an analytics tool, send the variation instead: the pages for Amplitude, Mixpanel, Google Analytics 4, Segment and PostHog name the event each one reads.
      • variation - The variation that was served, a ConfigDirector::Variation with its id and name. The id stays the same when the variation is renamed, and name is nil for a variation without one. It is nil when the config has no variations or the in-code default value is returned.
      • default_value? - Whether or not the evaluation fell back to the in-code default value.
      • reason - The reason for the evaluation resolution, as a String. In the case the config successfully evaluated based on server-provided targeting rules, or served an offline value, it is found-match. A context without an id that is served the default targeting rule value after skipping a percentage rollout reports rollout-skipped-no-identifier, with default_value? false; see Contexts without an id. If the evaluation had to fall back to the in-code default value, the reason says why the fallback was required:
        • client-not-ready - The evaluation happened before the client finished initialization, or after it was closed
        • config-state-missing - The requested config key was not present in the payload received from the server, usually because of an incorrect config key
        • invalid-number - The config was requested as a number but the value received from the server could not be read as that kind of number
        • invalid-boolean - The config was requested as a boolean but the value received from the server was neither true nor false
        • invalid-json - The config was requested with a Hash in-code default value but the value received from the server is not a JSON object, or with an Array but it is not a JSON array
        • type-mismatch - The config was requested as a String but it is a boolean or number config
        • value-missing - The config key was present in the payload received from the server, but it carried no value
      • context - The context that was provided to the evaluation, or nil when none was given or it was ignored for an invalid context kind
  • connection_error: ConfigDirector::ConnectionErrorEvent
    • Called when ConfigDirector refuses the connection, for example because it does not know the server SDK key, and the client will not try again. It is emitted at most once.
    • error - A ConfigDirector::ConfigDirectorConnectionError saying why, whose status is the HTTP status ConfigDirector answered with.

client_ready, configs_updated and connection_error handlers run on the thread that received the values: in streaming mode a background thread of the SDK, so one that blocks delays later updates; in polling mode the thread that called init for the first request and a background thread for every later one; in offline mode the thread that called init. config_evaluated handlers run on the thread that read the value, or on the thread that delivered the update when a watch fires. A handler can read from the client. A StandardError raised in a handler is logged at error level and ignored; the other handlers and the connection continue.

A handler registered twice runs twice. off(:configs_updated, handler) removes the first registration of handler, and off(:configs_updated) removes every handler of the event, hooks included. A block or a lambda is found only as the same object, while method(:name) finds a handler registered as method(:name).

Run without a connection

Set the connection mode to "offline" to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client needs no server SDK key, opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.

Give the values in a JSON file, with one value per config key, or inline:

lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  connection: ConfigDirector::ConnectionOptions.new(mode: "offline", file: "flags/new-checkout-on.json")
)
client.init
flags/new-checkout-on.json
{
  "new-checkout": true,
  "max-items": 20,
  "greeting": "hello",
  "theme": { "color": "blue" }
}
lib/config_director_client_per_process.rb
client = ConfigDirector.create_client(
  connection: ConfigDirector::ConnectionOptions.new(mode: "offline", values: { "new-checkout" => true, "max-items" => 20 })
)
client.init

The file path is resolved against the working directory of the process. The config type of each value in the file follows from the value itself: true or false (boolean), a whole number written without a decimal point or exponent (integer), any other number (float), a string, or an object or array (json). Inline values follow the same rule with Ruby classes, exactly as the test client reads them: true or false, an Integer, a Float, a String, or a Hash or an Array, which can hold nil. A key is a String or a Symbol, and a Symbol is read as its name. A value read with an in-code default value of another class returns the in-code default value, as it does against ConfigDirector.

init loads the values, and reads the file, each time it is called, and the client is ready when it returns. Each time, it calls the configs_updated handlers with every key the values hold, and every watch, as it does when values arrive from ConfigDirector; client_ready is called the first time only. Offline values never change on their own, so a watch is called again only when init is. polling_interval, timeout and url have no effect.

With mode: "offline" and neither file nor values, the client is ready once init returns and every config returns its in-code default value.

create_client raises ConfigDirector::ConfigDirectorValidationError when file and values are both given, either is given in streaming or polling mode, or an inline value is nil, a Symbol or of a class not listed above. init raises ConfigDirector::ConfigDirectorInitializationError when the file is missing, cannot be read, is not a JSON object or holds a value such as null. The client stays not ready, so a test run that starts from a misspelled path fails instead of passing on in-code default values. A later init that cannot load the file raises the same way and keeps serving the values loaded before.

If you come from LaunchDarkly, a file of values is what LaunchDarkly calls "flags from files", and offline mode with no values is its "offline mode".

Servers that fork their workers

Puma in cluster mode, Passenger's smart spawning and Unicorn with preload_app true load your application once and then fork their workers from that process. Since Puma 7, cluster mode loads the application before it forks by default. A Rails application as generated runs Puma in single mode, where nothing forks, until workers is set in config/puma.rb.

One connection per process

Each Ruby process that reads configs holds its own client and its own connection to ConfigDirector, so a server with four workers counts as four connections, and an application on 2 hosts with 4 workers each counts 8. Each connection counts toward your organization's service connection hours for as long as it is open.

A client initialized before the fork

A client that was initialized before the fork keeps working in each worker, with nothing for your application to call. At the fork, the worker serves at once the values the client held, then opens its own connection in the background and receives updates from then on. fork does not wait for that connection. The client's handlers and watches keep being called in the worker, and the worker reports what it evaluates. In streaming mode, the worker calls the configs_updated handlers with every key, and every watch, once shortly after the fork, even when nothing changed. The connection of the process that forked is not touched, and closing the client in a worker closes that worker's connection only.

A client that was never initialized, was closed, runs in offline mode, or whose server SDK key ConfigDirector refused does nothing at the fork. A process that Process.daemon starts keeps working the same way.

If a handler or a watch that runs in the background calls fork without a block, the forked process ends when the handler returns, with exit status 0 and after its at_exit handlers, as it would at the end of a fork block.

Create the client the first time it is used

Even though a client initialized at boot keeps working after the fork, create it the first time a process reads a config, as the setup code does, rather than while the application boots. A client created and initialized at boot, in a Rails initializer for example, also connects in every other process that loads the application:

  • the Puma master, which serves no request, so a host with four workers holds five connections;
  • bin/rails console and every Rake task, for as long as they run;
  • assets:precompile in an image build that has no server SDK key, where creating the client raises.

Created on first use, a client exists only in a process that reads a config, so only such a process connects. The first request in each worker waits for the first values, up to the connection timeout.

In a Rails application, put the setup code in lib/config_director_client_per_process.rb and load lib/ with autoload_lib_once, so that Rails does not reload the module when code changes in development. A reloaded module would forget its client and create a second one.

config/application.rb
module MyApp
  class Application < Rails::Application
    config.load_defaults 8.1
    config.autoload_lib_once(ignore: %w[assets tasks])
  end
end

Read through the module wherever a config is read:

app/controllers/checkout_controller.rb
class CheckoutController < ApplicationController
  def show
    client = ConfigDirectorClientPerProcess.client
    context = ConfigDirector::Context.new(id: params[:user_id])
    render json: { "new-checkout" => client.get_value("new-checkout", false, context) }
  end
end

With workers 4 in config/puma.rb, each of the four workers creates its own client on its first request, and the master creates none. To have each worker wait for its first values before it serves a request instead, call the same method from Puma's before_worker_boot hook, which runs in each worker after the fork:

config/puma.rb
workers 4

before_worker_boot do
  ConfigDirectorClientPerProcess.client
end

Applications that fork for each job

Resque, by default, forks a new process for each job. Most other job servers, such as Sidekiq, run many jobs in one long-lived process, which needs nothing beyond the setup above.

Initialize the client in the Resque worker before it forks, so that each job starts with the values the worker had at the fork:

config/initializers/resque.rb
Resque.before_first_fork do
  ConfigDirectorClientPerProcess.client
end

A job that reads its configs and ends within a few milliseconds then opens no connection. A job that runs longer opens its own connection and downloads every value, so a worker that runs 10 such jobs a second opens 10 connections a second.

A job reports what it evaluated only when it closes the client or runs for 5 seconds. Resque ends each job's process with exit!, which skips the at_exit handler of the setup code, so close the client in the job's after_perform hook, and in its on_failure hook, which Resque calls instead when the job raises:

app/jobs/send_invoice.rb
class SendInvoice
  @queue = :invoices

  def self.perform(invoice_id)
    client = ConfigDirectorClientPerProcess.client
    # ...
  end

  def self.after_perform_close_the_configdirector_client(*)
    ConfigDirectorClientPerProcess.client.close
  end

  def self.on_failure_close_the_configdirector_client(*)
    ConfigDirectorClientPerProcess.client.close
  end
end

Closing sends the job's report before its process ends, so each job waits for one request to ConfigDirector, up to 5 seconds. With FORK_PER_JOB=false, Resque runs every job in the worker's own process, which must not close its client: leave the hooks out then.

Retrieve config values

Retrieve config values with get_value, and subscribe to updates with watch. The first argument is the config key, the second is the in-code default value, which is returned if the config is not available or cannot be read as its class, and the third is the context targeting rules are evaluated for. The class of the in-code default value decides how the config is read:

main.rb
client = ConfigDirectorClientPerProcess.client
user = ConfigDirector::Context.new(id: "user-id")

# Retrieve config values
retries = client.get_value("max-retries", 3, user)
theme = client.get_value("theme", "light", user)
new_checkout = client.get_value("new-checkout", false, user)

# A JSON config is read as a Hash, and so is its in-code default value
limits = client.get_value("rate-limits", { "per_minute" => 60 }, user)

# Watch for config updates
subscription = client.watch("new-checkout", false, user) do |enabled|
  puts "new-checkout is now #{enabled}"
end

# Close the subscription when the watch is no longer needed
subscription.close

The class of the in-code default value decides how a config is read, not how the config was declared in the dashboard, so the in-code default value should always be the safe choice:

  • true or false reads a boolean. Only true and false read as a boolean, in any letter case. A config holding 1 yields the in-code default value.
  • A String reads the text of any config that is not a boolean, integer or float config, as the server spelled it, with no parsing, so a JSON config gives its JSON. A boolean or number config read with a String gives the in-code default value instead.
  • An Integer reads a whole number. A whole number the server wrote as 26.0 or 2.6e1 still reads as 26. Any other number yields the in-code default value.
  • A Float reads any finite number.
  • A Hash reads a JSON object and an Array reads a JSON array, with String keys. The in-code default value is returned as it is, never merged with the config's members.

nil, a Symbol or any other class of in-code default value raises ConfigDirector::ConfigDirectorValidationError, and so does a context that is not a ConfigDirector::Context.

get_value never raises when a config is missing or its value will not read as the class of the in-code default value; it returns your in-code default value instead. Which of those happened is reported by evaluate and through config_evaluated.

Evaluate config values with a context

Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

get_value takes a ConfigDirector::Context as its third argument, which is what targeting rules are evaluated against. The same key can therefore resolve differently per user. Leave it out when there is no user to evaluate for.

The context is the last argument of get_value. Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

main.rb
user = ConfigDirector::Context.new(
  id: "12345",
  name: "Example User",
  traits: { "region" => "North America" } # Any arbitrary traits which can be referenced in targeting rules
)

client.get_value("my-boolean-config-key", false, user)

It is also the third argument of watch:

main.rb
subscription = client.watch("new-checkout", false, user) do |enabled|
  puts "new-checkout is now #{enabled}"
end

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with kind:

main.rb
tenant = ConfigDirector::Context.new(
  id: "acme",
  kind: "tenant",
  name: "Acme Inc.",
  traits: { "plan" => "enterprise" }
)

client.get_value("my-boolean-config-key", false, tenant)

Leaving kind out means user. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given.

ConfigDirector::Context.new takes the following keyword arguments, all optional:

  • id
    • The context's identifier, a String, or an Integer such as the ID of a database record, which is read as its digits. With the context kind, it decides the context's bucket in a percentage rollout, so changing it can move the context into a different bucket. A context without one skips percentage rollouts; see Contexts without an id.
  • kind
    • The context kind, such as "tenant". Contexts of different kinds are separate contexts even when they share an identifier, and a percentage rollout can place them in different shares.
  • name
    • The context's display name, a String.
  • traits
    • A Hash of arbitrary traits which can be referenced in targeting rules, keyed by the name the rule references. A trait is a String, a number, true, false, nil, or an Array or Hash of them. A Symbol key or value is read as its text, so { plan: :pro } is the trait "plan" with the value "pro". Give a date as ISO 8601 text, such as user.created_at.iso8601, so date conditions can compare it.
  • anonymous
    • true keeps the context out of the dashboard: it is evaluated but never persisted, and telemetry reports neither the context nor its ID. Read it with anonymous?.

Context.new raises ConfigDirector::ConfigDirectorValidationError when id is neither a String nor an Integer, name is not a String, traits is not a Hash or is nested deeper than 100 levels, or anonymous is neither true nor false. It never fails because of the kind. A context cannot be changed once built, two contexts built with the same values are equal, and with builds a copy with other values.

Contexts without an id

A percentage rollout places each context in a share by its id, so a context without an id skips percentage rollouts: a rollout does not apply to it, and the targeting rules after the rollout are tried, as they are after a conditional rule the context does not match. The default targeting rule value is served when none of them applies. A rule that serves a single value still applies to it. To keep an anonymous visitor in a rollout, give the context a stable id, such as a session ID.

Watch for updates

watch takes the config key, the in-code default value, which also decides how each update is read, and an optional context, and calls its block with the newly evaluated value. It returns a ConfigDirector::Subscription whose close removes the watch:

main.rb
subscription = client.watch(
  "new-checkout",
  false,
  ConfigDirector::Context.new(id: "user-id", name: "Example User", traits: { "region" => "North America" })
) do |enabled|
  puts "new-checkout is now #{enabled}"
end

subscription.close

A watch fires whenever an update carries its key or a segment the config's targeting rules use, whether or not the value changed. It is not called when it is registered, so a watch registered before init is called for the first values, and one registered afterwards only sees later updates. When a full payload no longer includes the watched config, the block is called with the in-code default value, so it always agrees with what get_value would return. Blocks run on the thread that received the update, after the configs_updated handlers, so one that blocks delays later updates. A StandardError a block raises is logged and ignored.

unwatch("new-checkout", on_change) removes the first watch on the key whose block is the same Proc, such as one given to watch as &on_change, and unwatch("new-checkout") removes every watch on the key.

Track events

track reports to ConfigDirector that something happened in your application, such as a completed checkout. ConfigDirector shows tracked events on the Live feed and counts them for each variation of a running experiment; see Tracked events.

track takes the name of the event and an optional context the event happened for. The event's value and details are optional keyword arguments:

main.rb
client.track(
  "checkout-completed",
  ConfigDirector::Context.new(id: "user-id"),
  value: 49.9,
  details: { plan: "pro", seats: 3, tags: %w[beta internal], address: { city: "Lisbon" } }
)

client.track("export-finished", ConfigDirector::Context.new(id: "acme", kind: "tenant"))

client.track("nightly-sync-finished")
  • The name is a String, or a Symbol, which is read as its name.
  • value is a number the event measures, such as an amount of money, a count or a duration: an Integer or a finite Float. Any other number, such as a BigDecimal or a Rational, is left out, so convert it with to_f.
  • details is a Hash describing the event, with String or Symbol keys. Its values are Strings, numbers, true, false, nil, Symbols, which are sent as their names, Times, or nested Hashes and Arrays of them. A Time, Rails' ActiveSupport::TimeWithZone included, is sent as ISO 8601 text in UTC, such as 2026-11-15T10:30:00.000Z. A Date, a DateTime or a value of any other class leaves the details out, and a Float that is not finite is sent as null.

An event counts for an experiment only when it is tracked for a context with an id, the same one the experiment's config was evaluated for, so pass the context you evaluate with when you track the outcome of an experiment. Without a context, or for a context without an id, the event is still reported and counts for no experiment. For a context marked anonymous, the event is reported without the id, so it counts for no experiment either. A context with an invalid context kind is ignored as it is in an evaluation: the SDK logs an error and reports the event without a context. A context that is not a ConfigDirector::Context drops the event, with a warning.

track returns nil and never raises. The event is sent with the SDK's next telemetry report, every 30 seconds unless you changed flush_interval. In offline mode and after close, track does nothing. The SDK applies these limits, and logs one warning for each of them per telemetry report:

LimitBeyond it
An event name of 1 to 150 charactersThe event is not reported.
1,000 tracked events in one telemetry reportFurther events are not reported until that report is sent.
Details of up to 20 top-level keys and 1 KB as JSON, nested up to 100 levels, holding only the values aboveThe details are left out and the event is still reported.
A value that is an Integer or a finite FloatThe value is left out and the event is still reported.

ConfigDirector applies limits of its own to the events it stores; see Limits.

Other useful client features

The client provides additional methods. Reads and close cannot be called from a signal handler, such as a block given to Signal.trap: Ruby raises ThreadError there.

evaluate

Evaluates a config the way get_value does, with the same three arguments, and returns the ConfigDirector::ConfigEvaluation behind it — the value, whether it is the in-code default value, the reason, the value_id, the variation, and the context — instead of the value alone. It is the same object the config_evaluated hook reports, so use it where the reason matters at the point of the read, such as when reporting an evaluation to another system; get_value is enough everywhere else. Like every read, it reaches config_evaluated and is counted in telemetry.

main.rb
evaluation = client.evaluate("my-config-key", false, ConfigDirector::Context.new(id: "user-id"))
puts "No config with this key reached the SDK." if evaluation.reason == "config-state-missing"

ready?

Returns whether the client has received config state and is ready to evaluate configs. It is initially false and becomes true once the first config state arrives. Until it does, every read returns its in-code default value.

closed?

Returns whether the client has been closed. A closed client cannot be reopened.

get_all_configs

Returns what every config serves to a context, as a Hash of config keys to ConfigDirector::ConfigState, for example to hand the values to a page you render on the server. It takes two optional keyword arguments: context:, the context to evaluate for, and config_keys:, to get only those keys. It returns an empty Hash until the client is ready, and these reads reach no config_evaluated handler and are not counted in telemetry.

main.rb
configs = client.get_all_configs(context: ConfigDirector::Context.new(id: "user-id"), config_keys: ["new-checkout"])

Each ConfigState carries the config's id, key and type, the value served as text, its value_id and its variation. When a percentage rollout served the value, it also carries the rollout's rule_id and share_id.

unwatch_all

Removes every watch on every config. Handlers registered with on and the hooks option stay.

close

Closes the connection to ConfigDirector services, reports what the client evaluated and tracked since its last report, and removes every handler, hook and watch. It waits up to 5 seconds for ConfigDirector to answer the report, and up to 5 more when a report was already being sent. After close the client is not ready, every read returns its in-code default value and get_all_configs returns an empty Hash. Calling close more than once is harmless.

Only close when the process exits and will no longer make use of the client.

Never create a client inside a request. Each one waits in init for its first values, opens its own connection to ConfigDirector, and keeps it open until it is closed.

Test your code

Use the SDK's testing entry point, configdirector/testing, to test the code that reads your configs and flags. It creates a test client: the SDK's real client over an in-memory connection that your test controls. Only the connection to ConfigDirector and the telemetry are replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and no network connection is opened, no telemetry is sent, and no thread is started. It ships in the gem, so there is nothing else to install.

spec/checkout_service_spec.rb
require "configdirector/testing"

RSpec.describe CheckoutService do
  it "shows the new checkout while the flag is on" do
    test_client = ConfigDirector::Testing.create_test_client({ "new-checkout" => true, "max-items" => 20 })
    service = CheckoutService.new(test_client.client)
    test_client.client.init

    expect(service.new_checkout_enabled?("user-123")).to be(true)

    test_client.set_value("new-checkout", false)
    expect(service.new_checkout_enabled?("user-123")).to be(false)

    test_client.client.close
  end
end

test_client.client is a ConfigDirector::ConfigDirectorClient, so it goes anywhere your code accepts one. It starts not ready, like a production client, because the code under test usually owns the call to init; unless initialization is held or set to fail, init serves the stored values at once. The test client has no close of its own: close its client when the test ends.

Clients created on first use

The setup code creates its client the first time a process reads a config, so a test can put the test client in place before that. Make ConfigDirector.create_client return the test client's client, and forget the module's client after each example, so the next example creates its own:

spec/support/test_client_in_place_of_the_application_client.rb
RSpec.shared_context "with a test client" do
  let(:test_client) { ConfigDirector::Testing.create_test_client({ "new-checkout" => true }) }

  before { allow(ConfigDirector).to receive(:create_client).and_return(test_client.client) }

  after do
    test_client.client.close
    ConfigDirectorClientPerProcess.instance_variable_set(:@client, nil)
  end
end

The first read of an example then goes through ConfigDirectorClientPerProcess as it does in production: it creates the client, which is the test client's, and calls init, which serves the stored values at once.

Values

create_test_client, set_value and replace_values take Ruby values, and the config type follows from the class of each value: true or false is a boolean config, an Integer an integer config, a Float a float config, a String a string config, and a Hash or an Array a JSON config, which can hold nil. A key is a String or a Symbol, and a Symbol is read as its name. A String is always a string config, so JSON text meant as a JSON config is given as JSON.parse(text). Every value is served as an unconditional config, so every context receives the same value; a test that needs different values per context is written as one test per value. A value the SDK cannot serve, such as nil, a Symbol or a Float that is not finite, raises ConfigDirector::ConfigDirectorValidationError, and so does a blank key or a key of another class. Nothing changes then.

Reads behave as they do in production: set_value("new-checkout", true) read with a String in-code default value returns that in-code default value with the type-mismatch reason, set_value("max-items", 2.5) read with an Integer returns it with the invalid-number reason, and set_value("banner-text", "") returns it with the value-missing reason. evaluate and config_evaluated handlers report the reason. A Hash keeps its order.

Controls

ControlEffect
set_value(key, value)Stores the value and, while the client is connected, delivers an update carrying only key. Reads, the watches of key and the configs_updated handlers see it before the call returns.
remove_value(key)Removes the value and delivers a full update without it. Reads return the in-code default value with the config-state-missing reason, the watches of key receive the in-code default value, and configs_updated handlers find key in removed_keys.
replace_values(values)Replaces every stored value, cancels a hold or a failure that no init has used yet, and delivers a full update. Use it to reset a test client shared between tests.
hold_initializationThe next init waits until another thread calls complete_initialization or fail_initialization, or until the timeout. init blocks, so a test calls it on another thread.
complete_initializationDelivers the stored values to the held init, on the calling thread, so the client is ready when the call returns. The held init returns once the handlers and watches of those values have run. Called before init while a hold is set, it cancels the hold.
fail_initializationFails the held init the way a refused server SDK key does: the client is not ready, an error is logged and the connection_error handlers receive a ConfigDirectorConnectionError with the status 401, on the calling thread, and then the held init returns. Called while no init is held, it makes the next init fail, which then returns at once.
tracked_eventsThe events the code under test tracked with track, in call order, each as a ConfigDirector::Testing::TrackedEvent with its name, context, value and details. An event whose name the SDK would not report is not recorded, and a value or details the SDK would leave out are nil in the record. The details are recorded as the SDK sends them, so their keys are Strings and a Time is its ISO 8601 text in UTC. The limit of 1,000 events per telemetry report does not apply to the record, and nothing is recorded once the client is closed. It is the same Array on every call, so test_client.tracked_events.clear empties it.

The init after a failed one serves the stored values, the ones set in the meantime included.

spec/checkout_service_spec.rb
it "shows the old checkout when ConfigDirector refuses the key" do
  test_client = ConfigDirector::Testing.create_test_client({ "new-checkout" => true }, timeout: 0.5)
  service = CheckoutService.new(test_client.client)
  test_client.fail_initialization

  test_client.client.init

  expect(test_client.client.ready?).to be(false)
  expect(service.new_checkout_enabled?("user-123")).to be(false)
  test_client.client.close
end

Options

create_test_client(values, timeout: nil, logger: nil) takes timeout, in seconds, which bounds how long a held init waits and defaults to the SDK's production timeout of 3 seconds; and logger, any object with the methods of Ruby's Logger, as ConfigDirector.create_client takes it. Without a logger the SDK writes warnings and errors to standard error.

What to expect

  • The first values are delivered while init runs, so watches registered before init run before it returns, and the configs_updated handlers run before the client_ready handlers.
  • Watches and handlers run on the thread that calls set_value, remove_value, replace_values, complete_initialization or init, never on a thread of the SDK, so an assertion can follow the call directly. A change made from inside a handler or a watch is delivered right after the one being handled.
  • A held init that reaches the timeout logs the SDK's timeout warning, and a client that was not ready stays not ready until the next init. A client that was ready keeps serving its values through a later held or failed init, and completing such an init calls no client_ready handler.
  • Each failed init calls the connection_error handlers, where a client connected to ConfigDirector calls them at most once.
  • Watches run for every update that carries their key, whether or not the value changed, as in production. remove_value and replace_values deliver a full update, so they also run the watches of every key left.
  • A StandardError a watch or a handler raises is logged and does not reach the caller, as in production. An exception that is not a StandardError, such as a failed RSpec expectation, reaches the call that delivered the change.
  • After close, ready? is false, every read returns its in-code default value, get_all_configs returns an empty Hash, init raises ConfigDirectorValidationError, every handler and watch has been removed, and the closed client takes none of the values the test client's controls store.