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 incode.namespaceandcode.function. c.use "OpenTelemetry::Instrumentation::Rails"alone traces nothing. Useuse_allor name each instrumentation.- Puma cluster mode works without a fork hook. The
at_exitshutdown is what sends the last batch. - Sidekiq jobs start their own trace by default. Use
propagation_style: :childfor one trace.
Gems and versions
What each gem does, and which releases to pin on an older Ruby or Rails.
opentelemetry-sdkis the tracer, the sampler and the batch processor.opentelemetry-exporter-otlpsends spans as OTLP over HTTP with protobuf encoding. Ruby has no gRPC exporter.opentelemetry-instrumentation-alldepends 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:
| Ruby | sdk | exporter-otlp | instrumentation-all | instrumentation-rails |
|---|---|---|---|---|
| 3.3 and newer | 1.13.x | 0.37.x | 0.102.x | 0.42.x |
| 3.2 | 1.10.0 | 0.32.0 | 0.91.0 | 0.40.0 |
| 3.1 | 1.10.0 | 0.32.0 | 0.85.0 | 0.38.0 |
| 3.0 | 1.7.0 | 0.29.1 | 0.71.1 | 0.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.
| Library | Span | Kind |
|---|---|---|
| Rack + Action Pack | GET /orders/:id, one per request | server |
| Active Record | Order query, Order#save and other model operations | internal |
| pg, mysql2, trilogy | One per SQL statement, with the statement text | client |
| Action View | render_template.action_view, render_partial, render_collection, render_layout | internal |
| Net::HTTP | GET plus a connect span for a new connection | client |
| Faraday | GET | client |
| Redis | The command, such as SET or PIPELINED | client |
| Active Job | default publish on perform_later, default process on run | producer, consumer |
| Action Mailer | process.action_mailer when the mail is built, deliver.action_mailer when it is sent | internal |
| Sidekiq | default publish on enqueue, default process on run | producer, 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 indb.statement. Literal values become?by default (db_statement: :obfuscate).:omitdrops the statement and:includekeeps it raw, customer data included. - SQLite has no driver instrumentation. A fresh
rails newgets 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:
| Instrumentation | Default attributes | Opt-in |
|---|---|---|
| Rack, Net::HTTP, Faraday | Stable: http.request.method, url.path | old and http/dup still work, both deprecated |
| pg, mysql2, Redis | Old: db.system, db.statement | None in these versions |
| Trilogy | Old: db.system, db.statement | database 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: trueon Faraday for both. - To skip hosts such as a metadata endpoint, set
untraced_hostsonOpenTelemetry::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.:childputs the job under the request.:nonestarts 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 throughRails.loggeralso 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_loggingoff.
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.nameanddeployment.environment.name. Addservice.versionto compare releases. - Sampling. The default,
parentbased_always_on, keeps everything.parentbased_traceidratiokeeps 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
SIGTERMby itself. Without theat_exitline, 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_PROTOCOLunset. The Ruby exporter only doeshttp/protobuf. - Kill switch.
OTEL_SDK_DISABLED=trueturns 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"
The Ruby instrumentation doc covers Sinatra, plain Ruby scripts and the EU endpoint.