SDKs
Ruby SDK
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.On this page
Install
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.
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;
TimeandDatebecome ISO 8601 strings).keyis the stable identity used for percentage rollouts. - The
logger:you pass receives the client's diagnostics at debug level, andlast_erroralways holds the latest error.
Typed variations and details
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| Field | Meaning |
|---|---|
value | The 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_id | The matching rule (zero-based index), or nil. |
in_rollout · bucket | For percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99). |
revision | The configuration revision the result came from. |
trace | A list of NanoFlags::Engine::TraceStep explaining the decision step by step. |
error · json · type_name | Why 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.
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| Field | Meaning |
|---|---|
revision · previous_revision | The new revision and the one it replaced (nil for the first). |
checksum | Checksum 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_ms | For 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_changeandon_errorreturn an unsubscribe lambda. - A text
pingevery 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 everylive_poll_interval(300 s) as a safety net.live: falseskips the socket. - Close code
4004means the environment of the key was deleted: the last configuration stays in use,statusbecomes"stale",on_errorreceives:environment_deletedand 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/streamopen: eachrevisionevent makes it fetch/v1/bundlewithIf-None-Match, verify the bundle and swap it in. Polling everypoll_interval(30 s;0disables 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: falseuses polling only.
Readiness and status
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 usewait_until_ready(timeout)blocks until a configuration is in use or the first load attempt failed, for at mosttimeoutseconds (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.
preload_app!
on_worker_boot { NanoFlags::Client.after_fork } # start each worker's threads right awayNanoFlags::Client.after_forkrestarts 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, passstart: falsethere and callFLAGS.startinon_worker_bootinstead: a client created withstart: falseonly starts whenstartis called. - Unicorn: call
NanoFlags::Client.after_forkfromafter_forkinconfig/unicorn.rb.
Rails and Sidekiq
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
)
endSidekiq 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.
# any Rack app: use NanoFlags::SessionMiddleware, FLAGS
config.middleware.use NanoFlags::SessionMiddleware, FLAGS # reads x-nanoflags-session, resolves it once per request# 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.revisionFLAGS.session(token, service:)asks the edge once per token and service (GET /v1/session, the token inX-NanoFlags-Session,serviceinX-NanoFlags-Service, default: the client'sservice) and caches the answer until the session expires. Unknown tokens are remembered for 15 s, failed lookups for 3 s (:sessionerrors). 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 whencallreturns. - 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.
| API | Description |
|---|---|
session(token, service: nil) | Returns a NanoFlags::SessionEvaluator: the typed variations and their details, evaluate, active?, id, expires_at, revision. |
NanoFlags::SessionMiddleware | Rack 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_headers | The 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").
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 answerscache_pathwrites atomically with mode0600and 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 withgetandset(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.
# 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_errorreceives code:signature. - A bundle naming an unknown key id (a key rotation) loads
GET /v1/keysonce, at most once a minute.verify: true(orfetch_keys: true) uses the edge's/v1/keysfor a self-hosted edge;verify: falseturns verification off. - Bundles signed for another environment than the first accepted one are refused.
- Bundles for a newer evaluation engine than
NanoFlags::Engine::VERSIONare 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"}.
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 allredact 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
gem "nanoflags-openfeature"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-sdk0.4 or newer (0.6 and newer need Ruby 3.4).initwaits up toready_timeoutseconds for the first configuration and fails (provider error state) when none could be loaded; the client keeps trying in the background.close_client: truecloses the NanoFlags client onshutdown. - The targeting key becomes the NanoFlags
key(and wins over an attribute namedkey). Reasons:DISABLED,DEFAULT,TARGETING_MATCH,SPLIT(the variant is the rule id). Errors:FLAG_NOT_FOUND(orPROVIDER_NOT_READYwhile nothing is loaded),TYPE_MISMATCH,GENERAL. - Test sessions: pass
evaluator: -> { NanoFlags.flags_for(nanoflags) }toProvider.newto evaluate through the request's session (resolved byNanoFlags::SessionMiddlewareorNanoFlags.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 emitsPROVIDER_CONFIGURATION_CHANGED, and status changes emitPROVIDER_READYandPROVIDER_STALE(PROVIDER_ERRORwhile nothing is loaded).
Options
| Option | Default | Description |
|---|---|---|
base_url: | https://edge.nanoflags.io | Edge URL. |
service: | "unknown" | The name this process reports under. |
poll_interval: | 30 | Seconds between polls while no live socket is open. 0 disables polling. |
streaming: | true | Receive new revisions without polling (live WebSocket, else the event stream). false leaves polling only. |
live: | true | false skips the live WebSocket and uses the event stream and polling. |
live_poll_interval: | 300 | Seconds between safety polls while the live socket is healthy. |
live_url: | derived from base_url | WebSocket URL of /v1/live when it is not base_url with ws(s):// (advanced). |
cache_path: · store: · bootstrap: | none | See Last good config. |
verify: | on for the hosted edge | true, false or { public_keys:, require:, fetch_keys: }. |
events: | 10 % sampled | false or { sample_rate:, flush_interval:, report_interval:, redact: }. |
on_change: · on_error: | none | Listeners registered before the first load. |
logger: | none | A Logger (for example Rails.logger). |
start: | true | false defers background work until you call start. |
request_timeout: · http: | 10 · Net::HTTP | HTTP 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
closestops the background threads after a best-effort final telemetry flush (at most 2 seconds). It is idempotent. Anat_exithook closes every client for you.- After
close, variations keep working on the last configuration; it just stops updating.refreshrevalidates now and returns whether a configuration is in use.
Troubleshooting
- Every variation returns the default. Check
statusandlast_error.:unauthorizedmeans the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered. - Workers never see new revisions. Make sure the client in each worker has started: call
NanoFlags::Client.after_forkfrom the server's worker-boot hook, or evaluate once (the first call restarts the threads after a fork). A client created withstart: falseneeds an explicitstart. - Behind a proxy or with a custom CA. HTTP and the WebSocket honour
HTTPS_PROXY/NO_PROXY(a CONNECT tunnel) andSSL_CERT_FILE. If WebSocket upgrades are blocked,transportshows:stream; if the event stream is blocked too,:poll. - Errors with code
:signature. The bundle did not verify and was not used. If you pass a custombase_url, pin that edge's keys withverify:. - Errors with code
:environment_deleted. The edge closed the socket with4004. The client stops reconnecting and keeps its last configuration as"stale"; replace the key.