Skip to content
RailsDev.io

How to Build a Fail-Safe LLM Gateway in Rails for Multi-Provider AI Routing

Learn how to design a resilient LLM gateway in Rails with automatic model failover, rate limiting, and unified cost tracking across providers.

Diagram: API Controller → Gateway Router → Provider Clients → Fallback Logic → Metrics & Limits
On this page
  1. What is a Rails LLM gateway and why do I need one?
  2. How do I design a multi‑provider routing layer?
  3. Which gems and services simplify the implementation?
  4. How to add automatic model fallbacks, rate‑limiting, and cost controls?
  5. How to monitor, test, and evolve the gateway in production?
  6. Frequently asked questions
  7. Conclusion

I built a Rails LLM gateway to let a single Rails endpoint route requests to OpenAI, Anthropic, and self‑hosted Llama CPP models, automatically falling back when a provider throttles, applying per‑user rate limits, and capping spend based on configurable budgets. The result is a resilient, cost‑aware AI layer you can drop into any Rails app.

What is a Rails LLM gateway and why do I need one?

A Rails LLM gateway is a thin service‑oriented layer that abstracts away the quirks of each LLM provider behind a unified Rails controller. It lets you call POST /ai/completions without worrying whether the request ends up at OpenAI, Anthropic, or a local llama.cpp server.

  • It centralises authentication, logging, and error handling.
  • It shields your app from provider‑specific outages—if a provider returns an error, the gateway can retry with a cheaper fallback.
  • It gives you a single place to enforce business rules like “no more than a set amount of AI spend per month per team”.

In practice, this means you can iterate on prompts and model choices without touching the rest of your codebase. The gateway becomes the contract between your product logic and the ever‑changing AI ecosystem.

How do I design a multi‑provider routing layer?

The core idea is a router service that selects a provider based on a priority list, cost profile, and current health. I usually model this as a plain Ruby class that receives a request hash and returns a response hash.

ruby
# app/services/ai/router.rb
class Ai::Router
  Provider = Struct.new(:name, :client, :cost_per_token, :fallback_to)

  def initialize
    @providers = [
      Provider.new(:openai,   OpenAiClient.new,   0.0005, :anthropic),
      Provider.new(:anthropic, AnthropicClient.new, 0.0004, :local),
      Provider.new(:local,    LlamaCppClient.new, 0.0001, nil)
    ]
  end

  def call(payload)
    provider = select_provider(payload)
    provider.client.complete(payload)
  rescue ProviderError => e
    Rails.logger.warn "Provider #{provider.name} failed: #{e.message}"
    fallback = provider.fallback_to && find(name: provider.fallback_to)
    fallback ? fallback.client.complete(payload) : raise
  end

  private

  def select_provider(payload)
    # Simple cost‑aware selection; replace with more sophisticated logic later.
    @providers.min_by { |p| p.cost_per_token }
  end

  def find(**criteria)
    @providers.find { |p| criteria.all? { |k, v| p[k] == v } }
  end
end

The router is deliberately stateless; all runtime decisions are derived from configuration files (config/ai_providers.yml) and a tiny health cache stored in Redis. This keeps the service testable and easy to hot‑swap providers without a deploy.

Provider selection criteria (simplified)

Provider Fallback target
OpenAI Anthropic
Anthropic Local Llama CPP
Local Llama CPP none

I favour the cheapest provider that meets latency expectations, but you can flip the matrix to prioritize reliability or model capability instead.

Which gems and services simplify the implementation?

Rails already ships with ActiveSupport::Cache and ActiveJob, which I lean on heavily. For HTTP calls I use HTTParty (lightweight) or Faraday if I need middleware. The following gems cover most of the boilerplate:

Gem Use case Example
httparty Simple REST calls HTTParty.post(url, body: json, headers: headers)
faraday Middleware stack (retry, logging) `Faraday.new(url) {
redis Health cache, rate‑limit counters Redis.current.setex(key, 60, "healthy")
activejob Background retries for long completions Ai::CompletionJob.perform_later(payload)
dry-validation Payload schema enforcement Ai::Schema.call(params)

If you prefer a higher‑level abstraction, the ruby‑llm community gem (gem "ruby-llm") wraps OpenAI, Anthropic, and local models behind a common interface, but I found it adds an extra layer of indirection that makes debugging harder.

Service you might outsource to

If you need a managed multi‑provider token pool, the AI Marketplace offers wholesale pricing at $5 /mo for unlimited access, pooling usage across hundreds of billions of tokens. Their pricing sheet shows typical discounts of 60 % on DeepSeek V4.1 Flash and 40 % on GLM‑5.3, which can dramatically lower the per‑token cost in the router’s cost_per_token field. More details are on the /services/ai-software-development page.

Verification note: The discount percentages and token pricing are based on the AI Marketplace’s public pricing table and may vary by region or membership tier.

How to add automatic model fallbacks, rate‑limiting, and cost controls?

1. Automatic fallbacks

The router’s rescue ProviderError block (see earlier) already retries with the next provider. To make this robust:

  • Health checks – ping each provider every minute and store a boolean in Redis.
  • Circuit breaker – after several consecutive failures, mark the provider “open” for a cooldown period.
ruby
# app/services/ai/health_monitor.rb
class Ai::HealthMonitor
  COOLDOWN = 5.minutes

  def self.record_success(name)
    Redis.current.set("ai:health:#{name}", "healthy")
  end

  def self.record_failure(name)
    failures = Redis.current.incr("ai:failures:#{name}")
    if failures >= 3
      Redis.current.setex("ai:health:#{name}", COOLDOWN.to_i, "unhealthy")
    end
  end

  def self.healthy?(name)
    Redis.current.get("ai:health:#{name}") != "unhealthy"
  end
end

The router checks Ai::HealthMonitor.healthy?(provider.name) before selecting it.

2. Rate‑limiting per user or tenant

Rails 7 introduced ActiveSupport::Cache::RateLimiter (experimental). I prefer a Redis‑backed token bucket:

ruby
# app/services/ai/rate_limiter.rb
class Ai::RateLimiter
  LIMIT = 1_000 # tokens per day per user (example)

  def self.allowed?(user_id, token_count)
    key = "ai:rate:#{user_id}"
    current = Redis.current.get(key).to_i
    if current + token_count <= LIMIT
      Redis.current.incrby(key, token_count)
      Redis.current.expire(key, 24.hours.to_i) unless Redis.current.ttl(key) > 0
      true
    else
      false
    end
  end
end

Before calling the router, the controller validates:

ruby
def create
  payload = params.require(:prompt)
  unless Ai::RateLimiter.allowed?(current_user.id, payload[:max_tokens].to_i)
    render json: { error: "Rate limit exceeded" }, status: :too_many_requests and return
  end
  response = Ai::Router.new.call(payload)
  render json: response
end

3. Cost controls

Because each provider has a different per‑token price, the router can compute an estimated cost and abort if it exceeds a budget.

ruby
class Ai::CostGuard
  MAX_DAILY_SPEND = 50.00 # USD per tenant (example)

  def self.within_budget?(tenant_id, provider, token_estimate)
    cost = provider.cost_per_token * token_estimate
    spent = Redis.current.get("ai:spend:#{tenant_id}")&.to_f || 0.0
    (spent + cost) <= MAX_DAILY_SPEND
  end

  def self.record_spend(tenant_id, amount)
    Redis.current.incrbyfloat("ai:spend:#{tenant_id}", amount)
  end
end

Integrate it in the router:

ruby
def call(payload)
  provider = select_provider(payload)
  estimate = payload[:max_tokens].to_i
  unless Ai::CostGuard.within_budget?(payload[:tenant_id], provider, estimate)
    raise Ai::BudgetExceeded, "Daily AI spend limit reached"
  end
  response = provider.client.complete(payload)
  Ai::CostGuard.record_spend(payload[:tenant_id], provider.cost_per_token * estimate)
  response
end

4. Configuration via YAML

All thresholds live in config/ai_gateway.yml so you can tweak them without a code change.

yaml
# config/ai_gateway.yml
rate_limit:
  tokens_per_day: 1_000
budget:
  daily_usd: 50.0
providers:
  openai:
    api_key: <%= ENV['OPENAI_API_KEY'] %>
    cost_per_token: 0.0005
  anthropic:
    api_key: <%= ENV['ANTHROPIC_API_KEY'] %>
    cost_per_token: 0.0004
  local:
    endpoint: http://localhost:8080/v1/completions
    cost_per_token: 0.0001

Rails loads it with Rails.application.config_for(:ai_gateway).

How to monitor, test, and evolve the gateway in production?

A gateway is only as good as the observability you attach to it. I recommend three layers:

  1. Structured logging – JSON logs with fields provider, tenant_id, token_count, cost_usd, duration_ms. Tools like Logstash or Datadog can then aggregate spend per tenant.
  2. Metrics – Export Prometheus counters (ai_requests_total, ai_fallbacks_total, ai_rate_limited_total) and gauges (ai_current_spend_usd). The prometheus_exporter gem makes this painless.
  3. Alerting – Set alerts on sudden spikes in fallback rate or spend exceeding a threshold. Slack webhooks are handy for immediate notifications.

Testing strategy

  • Unit tests – Stub each client with WebMock and assert that the router picks the cheapest healthy provider.
  • Integration tests – Spin up a local llama.cpp server in Docker and run end‑to‑end requests through the controller.
  • Chaos testing – Use a simple script that forces an error from OpenAI to verify fallback logic.
ruby
# test/services/ai/router_test.rb
class Ai::RouterTest < ActiveSupport::TestCase
  test "fallback to anthropic when openai errors" do
    OpenAiClient.any_instance.stubs(:complete).raises(Ai::ProviderError.new("error"))
    AnthropicClient.any_instance.expects(:complete).once
    router = Ai::Router.new
    router.call(prompt: "Hello", max_tokens: 10)
  end
end

Continuous improvement

Because model capabilities evolve, I keep the provider list in a separate Git submodule that points to a curated providers.yml. When a new model becomes available, I add a row, update the cost, and run the test suite. The router’s selection algorithm can be swapped out for a machine‑learning‑driven optimizer without touching the controller.

For deeper integration with AI‑driven UI, see my earlier posts on the AG‑UI protocol [/blog/ag-ui-protocol-for-rails-apps] and AI‑powered Rails CLI extensions [/blog/ai-powered-rails-cli-extensions]. They show how the same gateway can feed prompts to background jobs that generate code snippets or UI components on demand.

Frequently asked questions

How does the gateway handle streaming responses?

I wrap the provider’s HTTP stream in an ActionController::Live response, forwarding each chunk to the client. If a fallback occurs mid‑stream, I close the connection and ask the client to retry; this is a known limitation until providers expose true resumable streams.

Can I use the gateway for embeddings as well as completions?

Yes. The router can be extended with a separate EmbeddingRouter that follows the same health‑check and cost‑guard patterns. The only change is the client method (client.embed) and the expected payload shape.

What if a provider changes its API version?

Because each client class isolates the HTTP contract, you only need to bump the version in that class and update the corresponding tests. The router remains untouched, which is the main benefit of this architecture.

Is the gateway compatible with Rails API‑only apps?

Absolutely. All the code lives in app/services and the controller can be an Api::V1::AiController that inherits from ActionController::API. No view rendering is required.

How do I audit spend for compliance purposes?

Store every request’s provider, token_count, and cost_usd in a dedicated ai_audit_logs table. Then you can generate CSV exports per tenant for finance or GDPR audits. Rails’ has_secure_token helps generate immutable request IDs.

Conclusion

Building a Rails LLM gateway gives you a single point of control over model selection, cost, and reliability, turning a chaotic multi‑provider landscape into a predictable service layer. Start by sketching the provider matrix, implement the router and health monitor, then layer on rate‑limiting, budgeting, and observability. When you’re ready to scale or need custom integrations, consider partnering with our AI development team via the [/services/ai-software-development] page, or simply book a discovery call to discuss your specific needs.

See the related service for hands‑on help. Primary source: the official project page.

Keep reading