Skip to content
NanoFlags
Start free

SDKs

Ruby SDK

The nanoflags gem evaluates flags locally and synchronously against a signed, in-memory configuration. Background threads keep it current, and the client is thread-safe and fork-safe. A variation call never performs I/O and never raises.

Install

Gemfile
gem "nanoflags"
gem "nanoflags-openfeature"   # optional: OpenFeature provider
  • Published on RubyGems as nanoflags 0.2.0 and nanoflags-openfeature 0.2.0. Ruby 3.1 or newer.
  • No runtime dependencies: Net::HTTP, sockets, OpenSSL (Ed25519) and JSON from the standard library. The WebSocket client for live updates is a small built-in RFC 6455 implementation.
  • The engine is a native port of the NanoFlags engine, tested against the shared fixtures generated from the reference engine (21,998 evaluation cases), so it gives the same results as every other SDK.
  • Apache-2.0. Source in nanoflags-sdk/ruby.

Quickstart

Copy a server key (nf_srv_…) from Settings → SDK keys in the dashboard and keep it in an environment variable. Pass on_error: to the constructor, so it is registered before the first load starts, then wait for readiness.

app.rb
require "nanoflags"

FLAGS = NanoFlags::Client.new(
  ENV.fetch("NANOFLAGS_SDK_KEY"),   # nf_srv_… (server view) or nf_pub_… (client-exposed flags only)
  service: "checkout-api",          # shown in "which revision is each service running"
  on_error: ->(e) { warn "nanoflags #{e.code}: #{e.message}" }
)
FLAGS.wait_until_ready(5)           # never raises; true once a configuration is in use

user = { key: current_user.id.to_s, plan: current_user.plan, country: "DE" }
if FLAGS.bool_variation("new-checkout", false, user)
  # …
end
  • Create one client per process and share it between threads. The base URL defaults to the hosted edge, https://edge.nanoflags.io.
  • The context is a Hash of JSON-like attributes (String or Symbol keys; Time and Date become ISO 8601 strings). key is the stable identity used for percentage rollouts.
  • The logger: you pass receives the client's diagnostics at debug level, and last_error always holds the latest error.

Typed variations and details

ruby
enabled = FLAGS.bool_variation("new-checkout", false, user)
accent  = FLAGS.string_variation("accent", "blue", user)
limit   = FLAGS.number_variation("rate-limit", 100, user)        # Integer for whole numbers, else Float
layout  = FLAGS.json_variation("layout", { "cols" => 3 }, user)  # Hash with String keys
every   = FLAGS.all_flags(user)                                  # no telemetry

d = FLAGS.bool_variation_detail("new-checkout", false, user)
d.value     # => true
d.reason    # => "rule_match"
d.rule_id   # => "beta"
d.revision  # => 57
d.trace     # the same steps the dashboard shows
FieldMeaning
valueThe value served (your default in the fallback cases).
reason"rule_match", "default" (no rule matched), "off" (flag disabled), "flag_not_found", "error" (wrong type or malformed configuration)
rule_index · rule_idThe matching rule (zero-based index), or nil.
in_rollout · bucketFor percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99).
revisionThe configuration revision the result came from.
traceA list of NanoFlags::Engine::TraceStep explaining the decision step by step.
error · json · type_nameWhy reason is "error"; the raw value as JSON text and its type name.

Each variation takes the flag key, the default and an optional context. You get your default when no configuration has loaded yet, when the flag is unknown, or when it serves a value of another type. A disabled flag is not a fallback case: it returns the flag's configured off value. evaluate(key, default, context) returns the engine result without a type check.

Live updates and listeners

The client keeps one WebSocket to the edge's /v1/live open (subprotocol nanoflags.v1, the key in the Authorization header, never in the URL), the same protocol as the JavaScript, Python, Go and Java SDKs. The edge sends the current bundle on connect and every new revision as it is published. Each pushed bundle is verified exactly like a fetched one before it is swapped in atomically, so an evaluation always sees one revision in full; a push that does not verify changes nothing and triggers a regular request instead.

ruby
off = FLAGS.on_change { |e| puts "now on r#{e.revision} (was r#{e.previous_revision}) via #{e.transport}" }
FLAGS.on(:status) { |status| puts "nanoflags status: #{status}" }   # "not-ready", "ready" or "stale"

off.call   # unsubscribe
FieldMeaning
revision · previous_revisionThe new revision and the one it replaced (nil for the first).
checksumChecksum of the new configuration.
source:network, :store or :bootstrap
transport:live (pushed over the WebSocket), :stream (fetched after an event-stream notice) or :poll
latency_msFor pushed revisions that carry their commit time: milliseconds from the database commit to this event; otherwise nil.
  • Listeners run on the client's background threads: keep them short. An exception in a listener is logged and never breaks the client. on(:change | :error | :status), on_change and on_error return an unsubscribe lambda.
  • A text ping every 30 s or so detects dead connections, and sockets are replaced after about 50 minutes. Reconnects back off 1 s, 2 s, 4 s and so on, up to 5 minutes. While the socket is healthy, polling only runs every live_poll_interval (300 s) as a safety net. live: false skips the socket.
  • Close code 4004 means the environment of the key was deleted: the last configuration stays in use, status becomes "stale", on_error receives :environment_deleted and the client stops reconnecting.
  • Fallback. While no socket can be opened (a proxy that refuses upgrades, for example), the client keeps the event stream GET /v1/stream open: each revision event makes it fetch /v1/bundle with If-None-Match, verify the bundle and swap it in. Polling every poll_interval (30 s; 0 disables it) catches anything both miss. After failures it retries after 1 s, 2 s, 4 s and so on, up to the poll interval; stream reconnects back off up to 30 s. streaming: false uses polling only.

Readiness and status

ruby
unless FLAGS.wait_until_ready(5)
  Rails.logger.warn("flags not loaded yet (#{FLAGS.last_error&.message}); variations return their defaults")
end

FLAGS.status        # "not-ready" | "ready" | "stale"
FLAGS.revision      # revision in use, or nil
FLAGS.transport     # :live | :stream | :poll
FLAGS.initialized?  # true once a configuration is in use
  • wait_until_ready(timeout) blocks until a configuration is in use or the first load attempt failed, for at most timeout seconds (nil: no limit). It never raises.
  • "ready": the configuration is known to be current. "stale": a configuration is in use but is not known to be current. "not-ready": nothing is loaded and every variation returns its default.
  • Don't block a request on readiness. Wait once at boot, with a short timeout, and let your defaults cover the rest.

Puma, Unicorn and fork safety

The client is fork-safe (Puma, Unicorn, Passenger, Resque, Sidekiq Swarm). A forked worker keeps the configuration it inherited, so it can evaluate immediately, and on its first call restarts its own background threads and opens its own live socket; the parent's connection is never touched. Events queued before the fork are sent by the parent only, and cached test sessions are inherited.

config/puma.rb
preload_app!

on_worker_boot { NanoFlags::Client.after_fork }   # start each worker's threads right away
  • NanoFlags::Client.after_fork restarts the background threads of every client in the forked child now. It is optional: without it, a client notices the fork on its first call and restarts then.
  • With preload_app!, creating the client in the master is fine. If the master should not open any connection, pass start: false there and call FLAGS.start in on_worker_boot instead: a client created with start: false only starts when start is called.
  • Unicorn: call NanoFlags::Client.after_fork from after_fork in config/unicorn.rb.

Rails and Sidekiq

config/initializers/nanoflags.rb
Rails.application.config.after_initialize do
  NANOFLAGS = NanoFlags::Client.new(
    Rails.application.credentials.nanoflags_sdk_key,
    service: "web",
    cache_path: Rails.root.join("tmp/nanoflags.json"),   # optional: start from the last good bundle
    logger: Rails.logger
  )
end

Sidekiq and other threaded workers use the same process-wide client from every job; evaluations are lock-free reads of the current bundle. Call close on shutdown only if you need the final telemetry flush synchronously: an at_exit hook does it too.

Test sessions

A shared test session, created in the dashboard (Scenarios → Shared test session), pins a configuration snapshot and a synthetic context to a token (nf_ts_…). A service that receives the token in the x-nanoflags-session header evaluates against that snapshot, with the context session.context.merge(your_context), for that request only. Sampled events from a session carry its id. Shared test sessions are part of the Scale plan.

config/application.rb
# any Rack app: use NanoFlags::SessionMiddleware, FLAGS
config.middleware.use NanoFlags::SessionMiddleware, FLAGS   # reads x-nanoflags-session, resolves it once per request
ruby
# a controller
flags = request.env["nanoflags.flags"]            # or NanoFlags.flags_for(FLAGS) where there is no request
flags.bool_variation("checkout-v2", false, { key: current_user.id })   # session-scoped while the session is active
flags.active?                                    # false when unknown, expired, revoked or not permitted here

# downstream calls join the session ({} outside one, always safe to merge)
Faraday.get(PRICING_URL, nil, NanoFlags.session_headers)

# jobs: pass the token along and resolve it in the worker
PriceJob.perform_async(order.id, NanoFlags.current_session)
NanoFlags.with_session(token) { NanoFlags.flags_for(FLAGS).bool_variation("checkout-v2", false, { key: user_id }) }

# or directly
s = FLAGS.session(request.headers["x-nanoflags-session"], service: "checkout-api")
s.id; s.expires_at; s.revision
  • FLAGS.session(token, service:) asks the edge once per token and service (GET /v1/session, the token in X-NanoFlags-Session, service in X-NanoFlags-Service, default: the client's service) and caches the answer until the session expires. Unknown tokens are remembered for 15 s, failed lookups for 3 s (:session errors). Concurrent requests with the same new token wait for one lookup.
  • It never raises. An unknown, expired, revoked or not permitted token falls back to the normal configuration: the evaluator behaves exactly like the client, so one code path serves normal traffic and tests. When a session expires mid-flight, active? turns false and evaluations continue on the published configuration.
  • The current session lives in fiber storage (Fiber[], inherited by threads and fibers started inside it on Ruby 3.2+; fiber-local on 3.1). Nothing is stored on the client. The middleware's session ends when call returns.
  • A session changes which snapshot and context an evaluation uses. It grants no data access and must not be used for authorization. Client keys only receive client-exposed flags, in sessions too. Session bundles are not signed; verification does not apply to them. A revoked session keeps working in a process that cached it until it expires.
APIDescription
session(token, service: nil)Returns a NanoFlags::SessionEvaluator: the typed variations and their details, evaluate, active?, id, expires_at, revision.
NanoFlags::SessionMiddlewareRack middleware: sets env["nanoflags.flags"] and runs the rest of the request inside the session.
NanoFlags.with_session(token) { … }Runs the block with token as the current session. An absent or malformed token runs it outside any session.
NanoFlags.flags_for(client)The current request's evaluator, resolved once per request and client; outside a session it behaves like the client.
NanoFlags.current_session · NanoFlags.session_headersThe current token (or nil); { "x-nanoflags-session" => token } inside a session, else {}.
NanoFlags::SESSION_HEADER"x-nanoflags-session"

Last good config and bootstrap

Once loaded, the last good configuration stays in use through network failures, rejected bundles and edge errors (status becomes "stale").

ruby
FLAGS = NanoFlags::Client.new(sdk_key, cache_path: "tmp/flags.json")                  # keep the last good bundle
FLAGS = NanoFlags::Client.new(sdk_key, store: NanoFlags::Store::Cache.new(Rails.cache))  # share it through an ActiveSupport cache
FLAGS = NanoFlags::Client.new(sdk_key, bootstrap: File.read("flags-bootstrap.json"))    # serve a bundle you ship until the edge answers
  • cache_path writes atomically with mode 0600 and restores the bundle on start as "stale" until the edge confirms it. A restored copy is verified again and ignored if it does not verify.
  • store: takes any object with get and set(text). bootstrap: takes a Hash or JSON text.
  • The cache holds flag rules, never the SDK key.

Signature verification

Every bundle is checked (Ed25519 over the canonical string, by key id) before it can replace the current one. With the hosted edge this is on by default with the production keys embedded in the gem (NanoFlags::OFFICIAL_SIGNING_KEYS), and unsigned bundles are refused. The raw signed bytes are hashed exactly as served.

ruby
# Self-hosted or proxied edge: pin your keys and require signatures
FLAGS = NanoFlags::Client.new(
  sdk_key,
  base_url: "https://flags.internal.example",
  verify: { public_keys: [{ "kty" => "OKP", "crv" => "Ed25519", "x" => "…", "kid" => "k1" }], require: true }
)
  • A bundle that fails verification is not used: the previous one stays, and on_error receives code :signature.
  • A bundle naming an unknown key id (a key rotation) loads GET /v1/keys once, at most once a minute. verify: true (or fetch_keys: true) uses the edge's /v1/keys for a self-hosted edge; verify: false turns verification off.
  • Bundles signed for another environment than the first accepted one are refused.
  • Bundles for a newer evaluation engine than NanoFlags::Engine::VERSION are refused (code :engine) and the current configuration stays in use: upgrade the gem. The canonical string is described in Signatures.

Telemetry and redaction

A sampled 10 % of evaluations are sent every 10 s, plus a service report every 60 s. By default, context values never leave the process: only the names (and value types) of the attributes the flag's rules use, for example {"plan" => "string"}.

ruby
FLAGS = NanoFlags::Client.new(
  sdk_key,
  events: { sample_rate: 0.05, redact: ->(ctx) { { plan: ctx[:plan] } } }   # what leaves the process
)

QUIET = NanoFlags::Client.new(sdk_key, events: false)   # no telemetry at all

redact receives a copy of the context you passed and returns the Hash that is sent instead of the default. flush sends queued events now.

OpenFeature provider

Gemfile
gem "nanoflags-openfeature"
ruby
require "nanoflags/openfeature"

nanoflags = NanoFlags::Client.new(ENV.fetch("NANOFLAGS_SDK_KEY"), service: "checkout-api")
OpenFeature::SDK.configure do |config|
  config.set_provider_and_wait(NanoFlags::OpenFeature::Provider.new(nanoflags, ready_timeout: 10))
end

client = OpenFeature::SDK.build_client
ctx = OpenFeature::SDK::EvaluationContext.new(targeting_key: current_user.id.to_s, plan: current_user.plan)
client.fetch_boolean_value(flag_key: "new-checkout", default_value: false, evaluation_context: ctx)
client.fetch_string_details(flag_key: "accent", default_value: "blue", evaluation_context: ctx)
  • For openfeature-sdk 0.4 or newer (0.6 and newer need Ruby 3.4). init waits up to ready_timeout seconds for the first configuration and fails (provider error state) when none could be loaded; the client keeps trying in the background. close_client: true closes the NanoFlags client on shutdown.
  • The targeting key becomes the NanoFlags key (and wins over an attribute named key). Reasons: DISABLED, DEFAULT, TARGETING_MATCH, SPLIT (the variant is the rule id). Errors: FLAG_NOT_FOUND (or PROVIDER_NOT_READY while nothing is loaded), TYPE_MISMATCH, GENERAL.
  • Test sessions: pass evaluator: -> { NanoFlags.flags_for(nanoflags) } to Provider.new to evaluate through the request's session (resolved by NanoFlags::SessionMiddleware or NanoFlags.with_session). Outside a session it behaves exactly like the client.
  • Flag metadata carries the evaluated revision (openfeature-sdk 0.5+). With SDK versions that support provider events, a new revision emits PROVIDER_CONFIGURATION_CHANGED, and status changes emit PROVIDER_READY and PROVIDER_STALE (PROVIDER_ERROR while nothing is loaded).

Options

OptionDefaultDescription
base_url:https://edge.nanoflags.ioEdge URL.
service:"unknown"The name this process reports under.
poll_interval:30Seconds between polls while no live socket is open. 0 disables polling.
streaming:trueReceive new revisions without polling (live WebSocket, else the event stream). false leaves polling only.
live:truefalse skips the live WebSocket and uses the event stream and polling.
live_poll_interval:300Seconds between safety polls while the live socket is healthy.
live_url:derived from base_urlWebSocket URL of /v1/live when it is not base_url with ws(s):// (advanced).
cache_path: · store: · bootstrap:noneSee Last good config.
verify:on for the hosted edgetrue, false or { public_keys:, require:, fetch_keys: }.
events:10 % sampledfalse or { sample_rate:, flush_interval:, report_interval:, redact: }.
on_change: · on_error:noneListeners registered before the first load.
logger:noneA Logger (for example Rails.logger).
start:truefalse defers background work until you call start.
request_timeout: · http:10 · Net::HTTPHTTP timeout in seconds, and the HTTP adapter.

Error codes

Errors reach on_error as NanoFlags::Error with a code (and http_status where relevant): :network, :unauthorized, :http, :invalid_bundle, :store, :config, :signature, :engine, :session, :environment_deleted. A failed update never changes the configuration in use, and nothing is raised from a variation call.

Closing and shutdown

  • close stops the background threads after a best-effort final telemetry flush (at most 2 seconds). It is idempotent. An at_exit hook closes every client for you.
  • After close, variations keep working on the last configuration; it just stops updating. refresh revalidates now and returns whether a configuration is in use.

Troubleshooting

  1. Every variation returns the default. Check status and last_error. :unauthorized means the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered.
  2. Workers never see new revisions. Make sure the client in each worker has started: call NanoFlags::Client.after_fork from the server's worker-boot hook, or evaluate once (the first call restarts the threads after a fork). A client created with start: false needs an explicit start.
  3. Behind a proxy or with a custom CA. HTTP and the WebSocket honour HTTPS_PROXY / NO_PROXY (a CONNECT tunnel) and SSL_CERT_FILE. If WebSocket upgrades are blocked, transport shows :stream; if the event stream is blocked too, :poll.
  4. Errors with code :signature. The bundle did not verify and was not used. If you pass a custom base_url, pin that edge's keys with verify:.
  5. Errors with code :environment_deleted. The edge closed the socket with 4004. The client stops reconnecting and keeps its last configuration as "stale"; replace the key.
Other languages
Native server SDKs also exist for Python, Go, Java, .NET and PHP. Other languages can read NanoFlags flags through an OpenFeature OFREP provider.