announcements

Introducing the Zenmanage Ruby SDK

The Zenmanage Ruby SDK is a gem with no runtime dependencies that evaluates flags inside your process, and in Rails it adds controller and view helpers, request-scoped contexts, and a signed webhook that refreshes rules.

The Zenmanage Ruby SDK is on RubyGems as zenmanage. Run bundle add zenmanage, set one environment variable, and a Rails app gets feature_enabled? in its controllers and views, flags evaluated for current_user, and percentage rollouts that give the same user the same answer in a request and in a background job.

Rails makes deploying cheap. Merge to main, let CI run, and the change is live in a few minutes. That speed is also the problem. The new invoice PDF, the rewritten checkout, and the job that backfills a column all go out the moment the deploy does, to every user at once. If it's wrong, rolling back the code doesn't un-send the emails or fix the rows it already wrote.

A flag separates the two. You deploy the code dark, turn it on for yourself, then for 5% of users, then for everyone, and you can turn it off again without another deploy. The Ruby SDK is built so that, in a Rails app, reading a flag is one line in a controller and nothing else to wire up.

What it is

zenmanage evaluates flags locally. It fetches your rules, caches them, and reads each flag against them inside your process, so a flag check doesn't cost a network round trip. It handles boolean, string, number, and JSON flags, targets by context, segment, and attribute, and buckets percentage rollouts with the same CRC32 hash as our other SDKs and the API. It needs Ruby 3.2 or later, has no runtime dependencies, and doesn't require Rails. Without Rails you create a client yourself and the same flags work in Sinatra, Rack, or a plain script.

Getting started

Add the gem and give your app a server key:

bundle add zenmanage

export ZENMANAGE_ENVIRONMENT_TOKEN=srv_your_server_key_here

That's the whole setup. When your app boots, the gem configures itself from the environment, logs to Rails.logger, adds a Rack middleware, and includes its helpers in ActionController::Base and ActionController::API. The key has to be a server key (srv_). Client and mobile keys are rejected. A server key belongs in your environment configuration or Rails credentials, not in source control or a browser.

If you'd rather keep settings in the app, bin/rails generate zenmanage:install writes an initializer to start from:

# config/initializers/zenmanage.rb
Zenmanage.configure do |config|
  config.environment_token = Rails.application.credentials.zenmanage_environment_token
  config.cache_ttl         = 300
end

Flags in controllers and views

Two helpers are available in every controller and view. feature_enabled? answers a yes-or-no question. zen_flags gives you the flag manager when you want a string, a number, or a JSON value:

class CheckoutController < ApplicationController
  def show
    @new_checkout = feature_enabled?("new-checkout")
    @layout       = zen_flags.single("checkout-layout", "classic").as_string
    @page_size    = zen_flags.single("page-size", 20).as_number
  end
end
<% if feature_enabled?("promo-banner") %>
  <%= render "shared/promo_banner" %>
<% end %>

The default you pass to single is the safety net. You get it when the flag isn't in your rules, which includes the case where the rules couldn't be loaded. feature_enabled? defaults to false, so a flag outage shows people the old page, not a 500. For a flag that should fail open, such as a kill switch, pass default: true. And if the token is missing, your app still boots: the gem logs a warning and feature_enabled? returns the default.

Flags for the person making the request

Targeting needs to know who it's evaluating for. If your controller has a current_user, the helpers build a user context from its id and, if it has one, its name. Both are sent to Zenmanage with usage reports. If you'd rather not send the name, or you want a rule to match on an attribute such as the plan, override the private zenmanage_context method:

class ApplicationController < ActionController::Base
  private

  def zenmanage_context
    return unless current_user

    Zenmanage::Context.new(
      "user",
      identifier: current_user.id.to_s, # no name sent
      attributes: [Zenmanage::Attribute.new("plan", [current_user.plan])],
    )
  end
end

Return nil and flags are evaluated with no context at all. That works for flags that are the same for everyone, and it's the right choice for a page that doesn't have a user.

Roll out the risky parts to a few users first

Start a percentage rollout on the flag in Zenmanage, and the SDK puts each user in or out of it from their identifier. It hashes the rollout's salt together with the identifier using CRC32 and maps the result to a bucket from 0 to 99. The user is in the rollout when the bucket falls below the percentage. The same identifier and salt always give the same bucket, so a user doesn't flip between the old and new version from one request to the next, and raising the percentage only adds people. The bucketing post explains why that stability matters, and the progressive rollouts post covers the stages themselves.

In a Rails app the useful part is that the answer doesn't depend on where you ask. Say the new invoice PDF is behind a flag. The controller decides whether to enqueue the new renderer:

class InvoicesController < ApplicationController
  def create
    invoice = current_user.invoices.create!(invoice_params)

    if feature_enabled?("new-invoice-pdf")
      RenderInvoiceJob.perform_later(invoice)
    else
      LegacyInvoiceMailer.with(invoice: invoice).created.deliver_later
    end

    redirect_to invoice
  end
end

Jobs, mailers, and models don't have a request, so they use Zenmanage.flags with an explicit context. Give it the same identifier the controller used, and the same attributes if your rules target on them, and the job lands in the same bucket as the request. Each process evaluates against the rules it has cached, so the two can briefly disagree right after you change the percentage (more on that below):

class RenderInvoiceJob < ApplicationJob
  def perform(invoice)
    context = Zenmanage::Context.single("user", invoice.user_id.to_s)

    if Zenmanage.flags.with_context(context).single("new-invoice-pdf", false).enabled?
      NewInvoiceRenderer.call(invoice)
    else
      LegacyInvoiceRenderer.call(invoice)
    end
  end
end

Start the flag at 1% and watch your error tracker. If the new renderer misbehaves, only about one user in a hundred has seen it, and switching the flag off stops the next one once your processes have reloaded their rules, which can take up to your cache_ttl unless a webhook reaches them first. If it looks clean, move to 10%, then 50%, then everyone, all from the dashboard. The code you deployed doesn't change at any step.

Try a variant on some users

A flag doesn't have to be a boolean. Make it a string, give each layout a value, and let the value pick the template. The checkout-layout read above does exactly that, and a number flag works the same way for a page size or a limit:

def show
  @layout = zen_flags.single("checkout-layout", "classic").as_string

  render @layout == "one-page" ? :one_page : :multi_page
end

Zenmanage decides who sees which layout. It doesn't analyze the outcome. Percentage rollouts are a release control, not an experiment platform, so we don't compute significance for you. Send the variant name to your analytics with the conversion event and judge the result there.

Rules that stay fresh without a restart

Rules are used for cache_ttl seconds, 3600 by default, and the next flag check after that reloads them. While one thread reloads, the others keep using the rules they have. If a reload fails, the current rules stay in use and the SDK tries again 30 seconds later, or sooner if your TTL is shorter. The default cache is in memory, per process. If you run several Puma workers on one machine, the filesystem cache lets them share it, and you can pass your own store with get and set if you'd rather use Rails.cache.

An hour is too long to wait when you've just turned something off. For that, mount the built-in webhook endpoint and point an environment webhook at it:

# config/routes.rb
Rails.application.routes.draw do
  mount Zenmanage::Webhook::Endpoint.new => "/zenmanage/webhook"
end

Set ZENMANAGE_WEBHOOK_SECRET to the webhook's signing secret, which starts with whsec_. The endpoint checks the X-Zenmanage-Signature header, rejects anything that doesn't match, and refreshes the rules when a signed request arrives. The webhooks reference lists the events and payloads.

Three things to know before you ship

A webhook reaches one process

The request lands on whichever Puma worker or host the load balancer picks, and only that process refreshes. The others pick up the change when their cache_ttl passes. If you need a kill switch to take effect everywhere within a minute, set a short cache_ttl, or use the filesystem cache to share rules between the workers on a machine. Don't assume one webhook flips the whole fleet.

No identifier means no rollout

A context without an identifier isn't placed in any percentage rollout, so it gets whatever the flag serves to people outside the rollout. If your 10% rollout looks like it's doing nothing, check that the context you build carries the same ID every time, and that signed-out pages aren't evaluating the flag with no context.

Short scripts can lose the usage report

single tells Zenmanage a flag was used, with the context and the default you passed, so you can see which flags are live and which are dead code. The report is sent in the background and never raises. A web process lives long enough to send it. A rake task or one-off script that exits right away can lose it. To send one and wait for it, call report_usage and join the thread:

flags = Zenmanage.flags
flags.single("new-invoice-pdf", false).enabled?

# Send one more report and wait for it. If both arrive, the flag counts as used twice.
flags.report_usage("new-invoice-pdf")&.join

Where to go next

The Ruby quickstart covers the setup in more detail, including plain Ruby, Sinatra and Rack with the middleware, shared defaults, and JSON flags. The zenmanage-ruby repository has the full README, runnable examples, and the changelog, and the zenmanage page on RubyGems lists every released version to pin.

If your Rails app has a JavaScript front end, the same flags work in the JavaScript SDK. Both SDKs bucket users with the same hash, so a user who's in a rollout on the server is in it in the browser too, as long as you pass the same identifier to both.

Enjoyed this article?

Share it with your network.