Frameworks 12 min read

OpenTelemetry for Ruby on Rails: tracing setup

Three gems and one initializer trace every request, query, outgoing call and background job. Here is the setup, what each span looks like, and the fixes for the usual problems. Tested with Rails 8.1 and OpenTelemetry Ruby SDK 1.13 (November 2026).

David Granzin By David Granzin

OpenTelemetry for Rails is three gems and one initializer. The SDK hooks into Rack, Action Pack, Active Record, your HTTP clients and your job queue, and sends spans over OTLP to any backend that speaks it.

Minimal setup

Three steps give you a traced app. Add the gems and run bundle install:

# Gemfile
gem "opentelemetry-sdk"
gem "opentelemetry-exporter-otlp"
gem "opentelemetry-instrumentation-all"

Create one initializer. It runs in every Rails process: web, console, runners, rake tasks and Sidekiq.

# config/initializers/opentelemetry.rb
require "opentelemetry/sdk"
require "opentelemetry/exporter/otlp"
require "opentelemetry/instrumentation/all"

OpenTelemetry::SDK.configure do |c|
  c.service_name = ENV.fetch("OTEL_SERVICE_NAME", "shop")
  c.use_all
end

# The SDK has no exit hook of its own. Send the last batch on shutdown.
at_exit { OpenTelemetry.tracer_provider.shutdown }

Tell the exporter where to send spans, then start the app:

export OTEL_SERVICE_NAME="shop"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318"

One request to a page that loads a record and renders a template now produces this trace:

shipping.quote is a custom span, covered below.

Key takeaways

  • Request spans are named GET /orders/:id. The controller and action are in code.namespace and code.function.
  • c.use "OpenTelemetry::Instrumentation::Rails" alone traces nothing. Use use_all or name each instrumentation.
  • Puma cluster mode works without a fork hook. The at_exit shutdown is what sends the last batch.
  • Sidekiq jobs start their own trace by default. Use propagation_style: :child for one trace.

Gems and versions

What each gem does, and which releases to pin on an older Ruby or Rails.

  • opentelemetry-sdk is the tracer, the sampler and the batch processor.
  • opentelemetry-exporter-otlp sends spans as OTLP over HTTP with protobuf encoding. Ruby has no gRPC exporter.
  • opentelemetry-instrumentation-all depends on every instrumentation gem the project ships, around 50. Each one does nothing unless its library is loaded.

For a shorter dependency list, swap the last gem for opentelemetry-instrumentation-rails (the Action and Active libraries) and add what else you use: opentelemetry-instrumentation-rack, -pg, -net_http, -faraday, -redis, -sidekiq.

As of November 2026 the current releases need Ruby 3.3 and Rails 7.1. On an older Ruby, Bundler resolves to the last release that supports it:

Rubysdkexporter-otlpinstrumentation-allinstrumentation-rails
3.3 and newer1.13.x0.37.x0.102.x0.42.x
3.21.10.00.32.00.91.00.40.0
3.11.10.00.32.00.85.00.38.0
3.01.7.00.29.10.71.10.34.1

The Rails floor is not a gem dependency, so Bundler will not catch it. An instrumentation that finds an older Rails logs that it was not installed and traces nothing. Pin opentelemetry-instrumentation-rails yourself:

  • Rails 7.1 and newer: 0.42.x
  • Rails 7.0: 0.38.0, even when your Ruby is new
  • Rails 6.1: 0.34.1

Initializer options

How to choose which instrumentations load and how to configure them. use_all installs every instrumentation whose library is present, and the SDK logs one line per instrumentation at boot with its options.

With no endpoint set, the exporter posts to http://localhost:4318/v1/traces, the default port of a local Collector. To see spans before you have anywhere to send them, print them:

OTEL_TRACES_EXPORTER=console bin/rails server

Then, in a second terminal:

curl localhost:3000/orders/1

c.service_name wins over OTEL_SERVICE_NAME when both are set, which is why the initializer reads the variable itself. With neither, the service is called unknown_service.

Options with use_all and use

use_all takes a hash keyed by instrumentation class name. Each value is that instrumentation's options, and enabled: false turns one off. A production starting point:

OpenTelemetry::SDK.configure do |c|
  c.service_name = ENV.fetch("OTEL_SERVICE_NAME", "shop")
  c.use_all(
    # Keep health checks out of your traces.
    "OpenTelemetry::Instrumentation::Rack" => { untraced_endpoints: ["/up"] },
    # One span per template, partial and layout is a lot. Off until you need it.
    "OpenTelemetry::Instrumentation::ActionView" => { enabled: false },
    # No Redis spans outside a request or job (Sidekiq's own polling).
    "OpenTelemetry::Instrumentation::Redis" => { trace_root_spans: false },
    "OpenTelemetry::Instrumentation::Sidekiq" => {
      span_naming: :job_class,
      propagation_style: :child
    }
  )
end

To install only what you name, call c.use once per instrumentation:

OpenTelemetry::SDK.configure do |c|
  c.use "OpenTelemetry::Instrumentation::Rack", { untraced_endpoints: ["/up"] }
  c.use "OpenTelemetry::Instrumentation::ActionPack"
  c.use "OpenTelemetry::Instrumentation::ActiveRecord"
  c.use "OpenTelemetry::Instrumentation::Net::HTTP"
  c.use "OpenTelemetry::Instrumentation::PG", { db_statement: :obfuscate }
  c.use "OpenTelemetry::Instrumentation::Sidekiq", { propagation_style: :child }
end

Trap

c.use "OpenTelemetry::Instrumentation::Rails" on its own installs nothing useful. The Rails gem only loads the Action Pack, Action View, Active Record, Active Job and Active Support gems, and c.use needs each one named. Without Rack and Action Pack there are no request spans, so every query and outgoing call becomes its own one-span trace.

What gets traced

The spans each library produces, with the names and kinds you will see in a trace view.

LibrarySpanKind
Rack + Action PackGET /orders/:id, one per requestserver
Active RecordOrder query, Order#save and other model operationsinternal
pg, mysql2, trilogyOne per SQL statement, with the statement textclient
Action Viewrender_template.action_view, render_partial, render_collection, render_layoutinternal
Net::HTTPGET plus a connect span for a new connectionclient
FaradayGETclient
RedisThe command, such as SET or PIPELINEDclient
Active Jobdefault publish on perform_later, default process on runproducer, consumer
Action Mailerprocess.action_mailer when the mail is built, deliver.action_mailer when it is sentinternal
Sidekiqdefault publish on enqueue, default process on runproducer, consumer

Request span names: route, not controller#action

There is one span per request. Rack opens it when the request arrives, and Action Pack renames it and adds the controller once Rails has routed it:

name: "GET /orders/:id"   kind: server
http.request.method        "GET"
http.route                 "/orders/:id"
url.path                   "/orders/1"
http.response.status_code  200
code.namespace             "OrdersController"
code.function              "show"

The name is the HTTP method and the route pattern, so /orders/1 and /orders/2 group together. Older versions used OrdersController#show. If your dashboards depend on that, ask for it:

c.use_all(
  "OpenTelemetry::Instrumentation::ActionPack" => { span_naming: :class }
)
  • No matching route: the span keeps the name GET.
  • 500: span status is error.
  • 404 from ActiveRecord::RecordNotFound: the exception is recorded as an event and the status stays unset.

Database spans

Two layers trace the database, and they answer different questions.

  • Active Record wraps model operations: spans like Order query, with no attributes. It shows which model was loaded.
  • The driver (pg, mysql2, trilogy) creates a client span per statement with the SQL in db.statement. Literal values become ? by default (db_statement: :obfuscate). :omit drops the statement and :include keeps it raw, customer data included.
  • SQLite has no driver instrumentation. A fresh rails new gets Active Record spans and no SQL.

Attribute names mix two generations of the semantic conventions, and OTEL_SEMCONV_STABILITY_OPT_IN controls only part of it:

InstrumentationDefault attributesOpt-in
Rack, Net::HTTP, FaradayStable: http.request.method, url.pathold and http/dup still work, both deprecated
pg, mysql2, RedisOld: db.system, db.statementNone in these versions
TrilogyOld: db.system, db.statementdatabase gives db.system.name and db.query.text; database/dup emits both

Net::HTTP and Faraday

Outgoing calls get a client span named after the method, with server.address, url.path or url.full, and http.response.status_code. The instrumentation also injects the traceparent header, which lets the next service continue the trace. See context propagation.

  • Faraday on its default Net::HTTP adapter produces one span, not two. Set enable_internal_instrumentation: true on Faraday for both.
  • To skip hosts such as a metadata endpoint, set untraced_hosts on OpenTelemetry::Instrumentation::Net::HTTP.

Custom spans and exceptions

Auto-instrumentation shows time spent in libraries. For your own code, get a tracer once and wrap the work in in_span:

# app/models/shipping_quote.rb
class ShippingQuote
  Tracer = OpenTelemetry.tracer_provider.tracer("shop.shipping", "1.0.0")

  def call(order)
    Tracer.in_span("shipping.quote", attributes: { "order.id" => order.id }) do |span|
      rate = order.total_cents > 5000 ? 0 : 499
      span.set_attribute("shipping.rate_cents", rate)
      span.add_event("rate.computed")
      rate
    end
  end
end

The span becomes a child of the current span, so in a controller it lands under the request.

If the block raises, in_span records the exception as an event, sets the status to error and re-raises. Do it by hand only when you rescue the error yourself, because a rescued exception never reaches the instrumentation:

def show
  @rate = RateService.fetch(order)
rescue Faraday::TimeoutError => e
  span = OpenTelemetry::Trace.current_span
  span.record_exception(e, attributes: { "order.id" => order.id })
  span.status = OpenTelemetry::Trace::Status.error("rate service timeout")
  render plain: "try again later", status: :service_unavailable
end

In a controller, OpenTelemetry::Trace.current_span is the request span. Keep error status for 5xx responses and unhandled exceptions. A declined card or a validation failure answered with a 4xx is the server working as designed: call record_exception if the exception is worth keeping, and leave the status alone.

Sidekiq and Active Job

Workers are traced with no extra setup, because the Sidekiq process runs the same initializer. Enqueueing creates a producer span, running the job creates a consumer span, and the trace context travels in the job payload. propagation_style decides how the two relate:

Trace IDs from two real runs. The first two spans come from the web process, the last two from Sidekiq.

  • :link (default) keeps request traces short. A job that runs an hour later does not stretch the request's trace.
  • :child puts the job under the request.
  • :none starts a new trace with no link.

Spans are named after the queue by default (default process). span_naming: :job_class gives ReceiptJob process. Active Job has the same two options: set them on OpenTelemetry::Instrumentation::ActiveJob if you enqueue through perform_later.

Logs with trace_id

A trace ID on a log line takes you from an error message to the request that produced it. Rails has three ways to add one, from least to most setup.

Tagged logging

config.log_tags accepts a proc. Rack's instrumentation runs before the Rails logger middleware, so the request span is already current:

# config/initializers/log_trace.rb
Rails.application.config.log_tags = [
  :request_id,
  ->(_request) {
    ctx = OpenTelemetry::Trace.current_span.context
    "trace_id=#{ctx.hex_trace_id} span_id=#{ctx.hex_span_id}" if ctx.valid?
  }
]
[b4e164cd-01bf-47da-98fe-0354ef28aac4] [trace_id=19bd5d306884558ae674d10283bbe348 span_id=1be3995503386c11] Processing by OrdersController#show as */*
[b4e164cd-01bf-47da-98fe-0354ef28aac4] [trace_id=19bd5d306884558ae674d10283bbe348 span_id=1be3995503386c11] loaded order 1

Tags are computed once per request, so every line carries the request span's ID, even inside child spans.

Lograge

If you use lograge for one JSON line per request, add the IDs as custom options:

# config/initializers/lograge.rb
Rails.application.configure do
  config.lograge.enabled = true
  config.lograge.formatter = Lograge::Formatters::Json.new
  config.lograge.custom_options = lambda do |_event|
    ctx = OpenTelemetry::Trace.current_span.context
    ctx.valid? ? { trace_id: ctx.hex_trace_id, span_id: ctx.hex_span_id } : {}
  end
end
{"method":"GET","path":"/orders/1","format":"*/*","controller":"OrdersController","action":"show","status":200,"duration":23.76,"view":3.07,"db":0.91,"trace_id":"bf5fccc60f9894c4e20ffab2f53db011","span_id":"8d91381ce0a2b530"}

OpenTelemetry logs

Ruby's logs signal is usable but not stable. As of November 2026 the logs SDK, the OTLP logs exporter and the Logger bridge are all 0.x, and none is part of opentelemetry-instrumentation-all:

# Gemfile
gem "opentelemetry-logs-sdk"
gem "opentelemetry-exporter-otlp-logs"
gem "opentelemetry-instrumentation-logger"

# config/initializers/opentelemetry.rb, above OpenTelemetry::SDK.configure
require "opentelemetry-logs-sdk"
require "opentelemetry/exporter/otlp_logs"
require "opentelemetry/instrumentation/logger"

No other wiring is needed: requiring opentelemetry-logs-sdk patches OpenTelemetry::SDK.configure, which then builds the logger provider and an OTLP log exporter (OTEL_LOGS_EXPORTER defaults to otlp). That is why the requires must come before configure.

  • The bridge patches Ruby's Logger, so everything written through Rails.logger also becomes an OTLP log record sent to /v1/logs.
  • Each record carries the innermost span's ID, so a SQL debug line points at the query's span.
  • In development the body includes ANSI colour codes until you turn colorize_logging off.

To keep 0.x gems out of the request path, write JSON to stdout with trace_id and let a Collector's filelog receiver ship the lines.

Puma cluster mode and forking

Forking servers need no hook. A background thread started in the parent does not exist in the child, and the SDK handles that itself: the batch span processor stores the process ID, and when a span finishes under a different ID it clears the inherited buffer and starts a new export thread.

Process IDs from a run with two workers and preload_app!. Both workers exported.

# config/puma.rb
workers ENV.fetch("WEB_CONCURRENCY", 2)
preload_app!
# No before_worker_boot hook is needed for OpenTelemetry.

The same applies to Unicorn and Passenger. Resource attributes are computed once, in the master, so every worker reports the master's process.pid. Do not use it to tell workers apart.

Production settings

Keep deployment details out of the initializer and set them in the environment:

export OTEL_SERVICE_NAME="shop"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,service.version=1.4.2"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://collector:4318"
export OTEL_EXPORTER_OTLP_COMPRESSION="gzip"

# Keep 10% of new traces, and follow the caller's decision when there is one.
export OTEL_TRACES_SAMPLER="parentbased_traceidratio"
export OTEL_TRACES_SAMPLER_ARG="0.1"

# Batch span processor. These are the defaults.
export OTEL_BSP_SCHEDULE_DELAY=5000
export OTEL_BSP_MAX_QUEUE_SIZE=2048
export OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
  • Resource attributes. Every backend filters on service.name and deployment.environment.name. Add service.version to compare releases.
  • Sampling. The default, parentbased_always_on, keeps everything. parentbased_traceidratio keeps a share of new traces and respects an upstream service's decision. The sampling guide covers moving the decision into a Collector.
  • Batching. Spans wait in a queue of 2048 and leave in batches of 512 every 5 seconds. A full queue drops its oldest spans, so raise the size or cut span volume.
  • Shutdown. The SDK does not flush on SIGTERM by itself. Without the at_exit line, a Puma worker stopped by a deploy exits with up to 5 seconds of spans in memory. With it, forked workers inherit the hook and send their last batch.
  • Protocol. Leave OTEL_EXPORTER_OTLP_PROTOCOL unset. The Ruby exporter only does http/protobuf.
  • Kill switch. OTEL_SDK_DISABLED=true turns the SDK into a no-op without a code deploy.

Common problems

The errors and gaps people hit most, each with its fix.

No spans from rails console, a runner or a rake task

The process ended before the first 5-second export. The at_exit hook in the initializer fixes this for every process type. A task can also flush explicitly:

# lib/tasks/import.rake
task import_orders: :environment do
  tracer = OpenTelemetry.tracer_provider.tracer("shop.tasks")
  tracer.in_span("import_orders") { OrderImport.run }
ensure
  OpenTelemetry.tracer_provider.shutdown
end

"Unable to export 1 spans" in tests and development

The exporter could not reach the endpoint. On a laptop that is usually the default localhost:4318 with nothing listening. Turn the export off where you do not want it:

# Turn the SDK off in tests
OTEL_SDK_DISABLED=true bin/rails test

# Or keep spans but export nothing
OTEL_TRACES_EXPORTER=none bin/rails test

"The grpc transport protocol is not supported"

Something set OTEL_EXPORTER_OTLP_PROTOCOL=grpc. The SDK warns once at boot and exports nothing. Unset it and use port 4318, not 4317. The OTLP guide explains the two transports.

Sidekiq jobs are not linked to the request

They are, by a span link, which many trace views show less prominently than a parent. Set propagation_style: :child on Sidekiq, and on Active Job if you use it. If there is no link at all, check that the web process and the worker both run the initializer.

Sidekiq floods the backend with Redis spans

Sidekiq polls Redis constantly, and each command outside a job becomes a one-span trace (INFO, SSCAN, PIPELINED). Set trace_root_spans: false on the Redis instrumentation.

Too many Action View spans

Every template, partial, collection and layout is a span, and nested partials can produce hundreds per page. Disable the instrumentation with enabled: false, or from the environment:

# Module name, upper case, "::" becomes "_". ActionView has no underscore.
export OTEL_RUBY_INSTRUMENTATION_ACTIONVIEW_ENABLED=false

The name comes from the Ruby module, not the gem: ACTIONVIEW, ACTIVERECORD. The underscored form is silently ignored.

Health checks fill the trace list

Add the path to untraced_endpoints on the Rack instrumentation. For patterns, untraced_requests takes a lambda that receives the Rack env and returns true to skip.

The service shows up as unknown_service

Neither c.service_name nor OTEL_SERVICE_NAME was set in that process. Sidekiq and cron containers often miss it.

Send it to Maple

Maple accepts OTLP directly, so the initializer stays as it is. Set the endpoint and pass your ingest key in the Authorization header. There is no protocol line because Ruby has no gRPC exporter: it always sends http/protobuf.

export OTEL_SERVICE_NAME="shop"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
A trace waterfall in Maple for a POST /api/checkout request: 15 spans across 6 services on a timeline, with the failing span marked as an error.
A Rails request with its queries and outgoing calls shows up as a waterfall like this.

The Ruby instrumentation doc covers Sinatra, plain Ruby scripts and the EU endpoint.

Sources and further reading

FAQ

자주 묻는 질문

How do I add OpenTelemetry to a Rails app?
Add opentelemetry-sdk, opentelemetry-exporter-otlp and opentelemetry-instrumentation-all to the Gemfile, then create config/initializers/opentelemetry.rb that calls OpenTelemetry::SDK.configure with c.use_all. Set OTEL_EXPORTER_OTLP_ENDPOINT to your Collector or backend. Requests, Active Record queries, outgoing HTTP calls and Sidekiq jobs are traced with no further code.
Does OpenTelemetry Ruby support auto-instrumentation?
Yes, in two forms. The usual one is in-process: opentelemetry-instrumentation-all plus c.use_all in an initializer patches Rails, Active Record, HTTP clients and Sidekiq with no changes to your application code. There is also a zero-code gem, opentelemetry-auto-instrumentation, loaded with RUBYOPT="-r opentelemetry-auto-instrumentation" and installed with gem install rather than the Gemfile. As of November 2026 it is at version 0.1.0, so the initializer is the safer choice for production.
Does OpenTelemetry Ruby support logs and metrics?
Traces are stable. Logs and metrics ship as separate gems that are still on 0.x versions: opentelemetry-logs-sdk with opentelemetry-exporter-otlp-logs, and opentelemetry-metrics-sdk with opentelemetry-exporter-otlp-metrics. They work, but their APIs can still change. Many teams keep writing logs to stdout with a trace_id field and let a Collector ship them.
Does OpenTelemetry work with Puma in cluster mode?
Yes, with no extra hook. The batch span processor notices that the process ID changed and restarts its export thread in each forked worker, including with preload_app!. Add an at_exit hook that calls OpenTelemetry.tracer_provider.shutdown so a worker sends its last batch when it stops.
Why are my Sidekiq jobs in a different trace than the request?
That is the default. The Sidekiq instrumentation uses propagation_style :link, so a job starts a new trace with a span link back to the span that enqueued it. Set propagation_style to :child to make the job a child span in the request's trace.
Why do I see no spans from rails console, a runner or a rake task?
Spans are exported in batches every 5 seconds by a background thread, and the Ruby SDK does not flush on exit by itself. A short process ends before the first export. Call OpenTelemetry.tracer_provider.shutdown before the process exits, or register it with at_exit in the initializer.
Does the Ruby OTLP exporter support gRPC?
No. opentelemetry-exporter-otlp sends OTLP over HTTP with protobuf encoding. If OTEL_EXPORTER_OTLP_PROTOCOL is set to grpc, the SDK logs a warning and exports nothing. Leave the variable unset or use http/protobuf, and point the endpoint at port 4318.

오늘 첫 트레이스를 확인하세요.

SDK를 추가하고 OTLP 익스포터를 Maple로 향하게 하면 트레이스가 도착합니다.

maple.dev: OpenTelemetry 위의 옵저버빌리티