Multi-tenant Configuration with Rails.app.creds
Multi-tenant SaaS apps have a configuration problem: tenants need different settings. Different API keys. Different feature access. Different rate limits.
The typical solution is a settings JSON column on the Tenant model, with code scattered everywhere:
# This gets old fast
api_key = current_tenant.settings.dig("stripe", "api_key") ||
Rails.application.credentials.dig(:stripe, :api_key)
Rails 8.2’s CombinedConfiguration offers a cleaner approach. If you haven’t seen the basics yet, check out 5 Unexpected Ways to Use Rails.app.creds first. Then come back here to see how to extend it for multi-tenancy.
Build a tenant configuration backend, chain it with your defaults, and access everything through Rails.app.creds. The same code works whether a tenant has overrides or not.
The Architecture
┌─────────────────────────────────────────────────────────┐
│ Rails.app.creds │
│ .option(:stripe, :api_key) │
└────────────────────────┬────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Tenant │ │ ENV │ │ Credentials │
│ Settings │ │ │ │ │
│ (Dynamic) │ │ (Deploy) │ │ (Default) │
└─────────────┘ └─────────────┘ └─────────────┘
First non-nil value wins
Tenant settings override ENV, which overrides credentials. Your app code doesn’t know or care where the value came from.
Step 1: Tenant Settings Model
First, give tenants a place to store their configuration:
# db/migrate/xxx_add_settings_to_tenants.rb
class AddSettingsToTenants < ActiveRecord::Migration[8.0]
def change
add_column :tenants, :settings, :jsonb, default: {}, null: false
end
end
# app/models/tenant.rb
class Tenant < ApplicationRecord
validates :settings, json: true # Use a JSON schema validator
# Convenience methods
def setting(*keys)
keys.reduce(settings.deep_symbolize_keys) { |h, k| h.is_a?(Hash) ? h[k] : nil }
end
def set_setting(*keys, value)
current = settings.deep_dup
*path, final = keys
target = path.reduce(current) { |h, k| h[k.to_s] ||= {} }
target[final.to_s] = value
update!(settings: current)
end
end
Step 2: Current Tenant
Use CurrentAttributes to track the current tenant:
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :tenant
def tenant=(tenant)
super
# Reload configuration when tenant changes
Rails.app.creds.reload if Rails.app.creds.respond_to?(:reload)
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_current_tenant
private
def set_current_tenant
Current.tenant = current_user&.tenant
end
end
Step 3: Tenant Configuration Backend
Now build the configuration backend:
# lib/tenant_configuration.rb
class TenantConfiguration
def require(*keys)
value = option(*keys)
value.nil? ? nil : value # Return nil to pass to next backend
end
def option(*keys, default: nil)
return nil unless Current.tenant
value = Current.tenant.setting(*keys)
value.nil? ? nil : value # Don't use default here, let chain handle it
end
def keys
return [] unless Current.tenant
flatten_keys(Current.tenant.settings.deep_symbolize_keys)
end
def reload
# Settings are read fresh from tenant each time
end
private
def flatten_keys(hash, prefix = [])
return [] unless hash.is_a?(Hash)
hash.flat_map do |k, v|
current = prefix + [k]
v.is_a?(Hash) ? flatten_keys(v, current) : [current]
end
end
end
Step 4: Wire It Up
# config/initializers/credentials.rb
Rails.app.creds = ActiveSupport::CombinedConfiguration.new(
TenantConfiguration.new, # Tenant overrides first
Rails.app.envs, # Then ENV
Rails.app.credentials # Then defaults
)
That’s it. Now Rails.app.creds.option(:stripe, :api_key) automatically checks the current tenant’s settings first.
Using Tenant Configuration
Different API keys per tenant
Let enterprise tenants use their own Stripe account:
# app/services/payment_service.rb
class PaymentService
def initialize
@stripe_key = Rails.app.creds.require(:stripe, :secret_key)
end
def charge(amount)
Stripe::Charge.create(
{ amount: amount, currency: "usd" },
{ api_key: @stripe_key }
)
end
end
Admin UI for tenants to set their key:
# app/controllers/settings/integrations_controller.rb
class Settings::IntegrationsController < ApplicationController
def update
Current.tenant.set_setting(:stripe, :secret_key, params[:stripe_secret_key])
redirect_to settings_integrations_path, notice: "Stripe configured!"
end
end
Per-tenant feature flags
# credentials.yml.enc (defaults)
features:
advanced_analytics: false
api_access: false
white_label: false
# Tenant settings (for premium tenant)
{
"features": {
"advanced_analytics": true,
"api_access": true
}
}
# In your code - same as before
if Rails.app.creds.option(:features, :advanced_analytics, default: false)
render_advanced_analytics
end
Premium tenants see advanced analytics. Everyone else doesn’t. No conditional logic needed.
Per-tenant rate limits
# credentials.yml.enc (defaults)
limits:
api_requests_per_hour: 1000
storage_gb: 5
team_members: 10
# Tenant settings (enterprise tenant)
{
"limits": {
"api_requests_per_hour": 50000,
"storage_gb": 500,
"team_members": -1 # unlimited
}
}
# app/services/rate_limiter.rb
class RateLimiter
def allowed?(action)
limit = Rails.app.creds.option(:limits, action, default: 100)
return true if limit == -1 # Unlimited
current_count(action) < limit
end
end
Admin Interface
Build an admin panel for managing tenant configuration:
# app/controllers/admin/tenant_settings_controller.rb
class Admin::TenantSettingsController < AdminController
def show
@tenant = Tenant.find(params[:tenant_id])
@available_settings = available_settings_schema
@current_settings = @tenant.settings
end
def update
@tenant = Tenant.find(params[:tenant_id])
@tenant.update!(settings: merged_settings)
redirect_to admin_tenant_settings_path(@tenant), notice: "Settings updated"
end
private
def available_settings_schema
{
features: {
advanced_analytics: { type: :boolean, default: false, plans: [:pro, :enterprise] },
api_access: { type: :boolean, default: false, plans: [:enterprise] },
white_label: { type: :boolean, default: false, plans: [:enterprise] }
},
limits: {
api_requests_per_hour: { type: :integer, default: 1000, min: 100, max: 100_000 },
storage_gb: { type: :integer, default: 5, min: 1, max: 1000 },
team_members: { type: :integer, default: 10, min: 1, max: 500 }
},
integrations: {
stripe: { secret_key: { type: :secret } },
sendgrid: { api_key: { type: :secret } }
}
}
end
def merged_settings
@tenant.settings.deep_merge(settings_params.to_h)
end
end
Caching Tenant Settings
For high-traffic apps, cache tenant settings:
# lib/cached_tenant_configuration.rb
class CachedTenantConfiguration
CACHE_TTL = 5.minutes
def option(*keys, default: nil)
return nil unless Current.tenant
settings = cached_settings
value = keys.reduce(settings) { |h, k| h.is_a?(Hash) ? h[k] : nil }
value.nil? ? nil : value
end
def reload
return unless Current.tenant
Rails.cache.delete(cache_key)
end
private
def cached_settings
Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) do
Current.tenant.settings.deep_symbolize_keys
end
end
def cache_key
"tenant_settings/#{Current.tenant.id}/#{Current.tenant.updated_at.to_i}"
end
end
The cache key includes updated_at, so settings changes invalidate immediately.
Audit Logging for Compliance
Enterprise tenants often need audit logs. Wrap the tenant configuration:
# lib/audited_tenant_configuration.rb
class AuditedTenantConfiguration
def initialize(backend)
@backend = backend
end
def option(*keys, default: nil)
value = @backend.option(*keys, default: default)
log_access(keys, value, :option) if value
value
end
def require(*keys)
value = @backend.require(*keys)
log_access(keys, value, :require) if value
value
end
delegate :keys, :reload, to: :@backend
private
def log_access(keys, value, method)
TenantConfigAuditLog.create!(
tenant: Current.tenant,
keys: keys.join("."),
method: method,
accessed_at: Time.current,
user: Current.user,
request_id: Current.request_id
)
end
end
Testing Multi-tenant Configuration
# test/lib/tenant_configuration_test.rb
class TenantConfigurationTest < ActiveSupport::TestCase
setup do
@tenant = tenants(:acme)
@config = TenantConfiguration.new
end
test "returns nil without current tenant" do
Current.tenant = nil
assert_nil @config.option(:features, :custom)
end
test "returns tenant setting when present" do
Current.tenant = @tenant
@tenant.update!(settings: { "features" => { "custom" => true } })
assert_equal true, @config.option(:features, :custom)
end
test "returns nil for missing settings (passes to next backend)" do
Current.tenant = @tenant
@tenant.update!(settings: {})
assert_nil @config.option(:features, :custom)
end
end
# test/integration/tenant_configuration_integration_test.rb
class TenantConfigurationIntegrationTest < ActionDispatch::IntegrationTest
test "tenant settings override defaults" do
tenant = tenants(:acme)
tenant.update!(settings: { "features" => { "dark_mode" => true } })
sign_in users(:acme_admin)
# Tenant setting
assert Rails.app.creds.option(:features, :dark_mode, default: false)
# Falls through to credentials for unset values
assert_equal "default_key", Rails.app.creds.option(:api, :key, default: "default_key")
end
end
Security Considerations
Validate tenant input
Never trust tenant-provided configuration blindly:
class Tenant < ApplicationRecord
validate :settings_schema_valid
ALLOWED_SETTINGS = {
features: %i[advanced_analytics api_access white_label],
limits: %i[api_requests_per_hour storage_gb team_members],
integrations: { stripe: %i[secret_key], sendgrid: %i[api_key] }
}.freeze
private
def settings_schema_valid
settings.each_key do |key|
unless ALLOWED_SETTINGS.key?(key.to_sym)
errors.add(:settings, "contains invalid key: #{key}")
end
end
end
end
Encrypt sensitive settings
For API keys and secrets, encrypt at rest:
class Tenant < ApplicationRecord
encrypts :settings # Rails 7+ encryption
end
Rate limit settings changes
Prevent abuse:
class Settings::IntegrationsController < ApplicationController
before_action :rate_limit_settings_changes
private
def rate_limit_settings_changes
key = "settings_change:#{Current.tenant.id}"
if Rails.cache.read(key).to_i > 10
render json: { error: "Too many settings changes" }, status: :too_many_requests
else
Rails.cache.increment(key, 1, expires_in: 1.hour)
end
end
end
The Full Stack
Here’s the complete configuration chain for a production multi-tenant app:
# config/initializers/credentials.rb
tenant_config = CachedTenantConfiguration.new
audited_tenant_config = AuditedTenantConfiguration.new(tenant_config)
Rails.app.creds = ActiveSupport::CombinedConfiguration.new(
audited_tenant_config, # Tenant settings (cached, audited)
Rails.app.envs, # ENV overrides (for ops)
Rails.app.credentials # Defaults
)
Lookup order:
- Tenant settings - Customizations for this specific tenant
- ENV variables - Ops can override anything in emergencies
- Encrypted credentials - Sensible defaults
Your application code stays clean:
# Works for any tenant, with any configuration source
api_key = Rails.app.creds.require(:stripe, :secret_key)
limit = Rails.app.creds.option(:limits, :api_requests, default: 1000)
enabled = Rails.app.creds.option(:features, :new_ui, default: false)
Wrapping Up
Multi-tenant configuration doesn’t need to be scattered conditionals and JSON digging. With CombinedConfiguration:
- Build a tenant backend that reads from
Current.tenant.settings - Chain it first so tenant settings override defaults
- Access configuration uniformly via
Rails.app.creds
The result: tenant customization without code complexity. Enterprise tenants get their own API keys, feature flags, and limits. Your code stays clean and testable.
New to Rails.app.creds? Start with 5 Unexpected Ways to Use Rails.app.creds for the fundamentals.
See PR #56404 for the CombinedConfiguration implementation.