ruby 87 lines · 4 tabs

Percentage-Based Feature Flag Rollout With a Stable Bucketing Gate in Rails

Shared by codesnips Sep 2026
4 tabs
class FeatureFlag < ApplicationRecord
  validates :key, presence: true, uniqueness: true
  validates :percentage,
            numericality: { only_integer: true,
                            greater_than_or_equal_to: 0,
                            less_than_or_equal_to: 100 }

  scope :by_key, ->(key) { find_by(key: key.to_s) }

  def enabled_for?(actor)
    return false unless enabled?
    return false if percentage.zero?
    return true  if percentage >= 100

    actor_id = actor.respond_to?(:id) ? actor.id : actor
    return false if actor_id.blank?

    bucket_for(actor_id) < percentage
  end

  private

  def bucket_for(actor_id)
    seed = "#{key}:#{actor_id}"
    Digest::SHA256.hexdigest(seed).to_i(16) % 100
  end
end
4 files · ruby Explain with highlit

Percentage rollouts let a team ship a feature to a fraction of users and ramp it up without redeploying. The naive approach — rand < percentage — is wrong because it re-rolls the dice on every request, so a user flickers in and out of the feature. The correct pattern is stable bucketing: hash a stable identifier into a fixed range and compare that bucket against the rollout percentage, so a given user's membership only changes when the percentage crosses their bucket.

In FeatureFlag model, each flag is a durable row keyed by a unique key, with an integer percentage (0–100) and an enabled boolean master switch. The core logic lives in enabled_for?, which short-circuits when the flag is off or fully rolled out, then calls bucket_for to derive a deterministic value. bucket_for salts the actor id with the flag key and runs it through Digest::SHA256, taking the number modulo 100. Salting with the key is important: without it the same user would land in the same bucket for every flag, so early adopters of one feature would always be early adopters of everything. The by_key scope and validations keep lookups and data clean.

Because flags are read on nearly every request, FeatureGate service wraps FeatureFlag.by_key in Rails.cache.fetch with a short TTL so the database isn't hit constantly, while still letting percentage changes propagate within seconds. It exposes a simple on?(key, actor) predicate and a bust helper to clear the cache after an admin edits a flag. Fetching a missing flag returns a safe false default rather than raising.

FeaturesController concern mixes require_feature and feature_on? into controllers. require_feature acts as a before_action-style gate that renders 404 when the current user isn't in the rollout, hiding the feature's existence entirely. feature_on? is exposed as a helper_method so views can conditionally render UI. The trade-off of this design is that bucketing is only as stable as the actor id, and anonymous users need a persistent surrogate id; the pattern also assumes uniform hash distribution, which SHA256 provides in practice. It's the right tool for gradual canary releases and kill-switch style flags.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Percentage-Based Feature Flag Rollout With a Stable Bucketing Gate in Rails — share card
Link copied