💎 Ruby Integration Guide
Learn how to instrument your Ruby applications with the TraceKit Ruby SDK for distributed tracing, metrics, and code monitoring.
90% Automatic Tracing!
With the right gems, most of your application will be traced automatically with minimal setup. No need to manually instrument every controller or method.
Prerequisites
- • Ruby 2.7 or higher (Ruby 3.0+ recommended)
- • An active TraceKit account
- • A generated API key from the API Keys page
🔍 What Gets Traced Automatically?
With proper setup, these operations are traced automatically with zero manual instrumentation:
| Component | Setup | Auto-Traced? |
|---|---|---|
| HTTP Endpoints | Rails/Sinatra/Rack instrumentation | ✓ Yes |
| ActiveRecord Queries | ActiveRecord instrumentation | ✓ Yes |
| HTTP Client Calls | Net::HTTP/Faraday instrumentation | ✓ Yes |
| Redis Operations | Redis instrumentation | ✓ Yes |
| Sidekiq Jobs | Sidekiq instrumentation | ✓ Yes |
| Custom Business Logic | Manual spans (optional) | Manual |
📦 Installation
Add the TraceKit Ruby SDK to your Gemfile:
# Gemfile
gem 'tracekit'
# Then run:
bundle install⚙️ Basic Setup
Configure the TraceKit SDK:
Rails Applications (Auto-Configuration via .env)
For Rails applications, TraceKit automatically configures itself using environment variables:
# .env file
TRACEKIT_API_KEY=ctxio_abc123...
TRACEKIT_ENDPOINT={ appURL }
TRACEKIT_SERVICE_NAME=my-rails-app
TRACEKIT_ENVIRONMENT=production
TRACEKIT_CODE_MONITORING=true
# That's it! The TraceKit Railtie automatically:
# - Loads configuration from ENV variables
# - Initializes OpenTelemetry with OTLP exporters
# - Adds Rack middleware for request instrumentation
# - Sets up graceful shutdownNon-Rails Applications (Manual Configuration)
For non-Rails applications, configure the SDK manually:
require 'tracekit'
# Configure the SDK
Tracekit.configure do |config|
config.api_key = ENV['TRACEKIT_API_KEY']
config.service_name = 'my-service'
config.endpoint = '{ appURL }'
config.environment = 'production'
config.enable_code_monitoring = true
end
# For Rack applications, add middleware
use Tracekit::Middleware
# At application shutdown
at_exit { Tracekit.shutdown }🚀 Framework Integration
TraceKit SDK provides first-class support for popular Ruby frameworks with automatic instrumentation.
Ruby on Rails
# Your controllers are automatically traced!
class UsersController < ApplicationController
def index
# This action is automatically traced!
@users = User.all
render json: @users
end
def create
sdk = Tracekit.sdk
# Track metrics
sdk.counter("user.created").add(1)
# Capture snapshot with context
sdk.capture_snapshot("user-create", {
email: params[:email],
name: params[:name]
})
@user = User.create!(user_params)
render json: @user, status: :created
end
private
def user_params
params.require(:user).permit(:name, :email)
end
endSinatra
# app.rb
require 'sinatra'
require 'tracekit'
# Configure TraceKit
Tracekit.configure do |config|
config.api_key = ENV['TRACEKIT_API_KEY']
config.service_name = 'my-sinatra-app'
config.endpoint = '{ appURL }'
end
# Add TraceKit middleware
use Tracekit::Middleware
# Routes are automatically traced!
get '/api/users' do
sdk = Tracekit.sdk
# Track metrics
sdk.counter("api.users.requests").add(1)
content_type :json
User.all.to_json
end⚡ Automatic Instrumentation Libraries
These libraries automatically create child spans for common operations. Set them up once, and every call is traced automatically.
ActiveRecord Queries
Automatically trace all database operations:
# ActiveRecord is automatically instrumented by TraceKit
# All queries are automatically traced!
User.all # Traced!
User.find(1) # Traced!
User.where(active: true) # Traced!
User.create(name: 'Alice') # Traced!HTTP Client Calls
Automatically trace all outgoing HTTP requests:
# Net::HTTP is automatically instrumented by TraceKit
require 'net/http'
# All HTTP requests are automatically traced!
uri = URI('https://api.example.com/users')
response = Net::HTTP.get_response(uri) # Traced!Redis Operations
Trace Redis commands automatically:
# Redis operations are automatically traced by TraceKit
redis = Redis.new(host: 'localhost', port: 6379)
redis.set('key', 'value') # Traced!
redis.get('key') # Traced!🔧 Manual Instrumentation (Optional)
For custom business logic that isn't covered by auto-instrumentation libraries, you can manually create spans. This is optional and only needed for specific operations you want to measure.
def process_order(order_id)
sdk = Tracekit.sdk
# Capture snapshot at key moments
sdk.capture_snapshot("order-processing-start", {
orderId: order_id,
status: "processing"
})
# Track metrics
sdk.counter("orders.processed").add(1)
sdk.gauge("orders.active").inc
# Validation logic here...
# Track duration
start_time = Time.now
result = charge_payment(order_id)
duration_ms = ((Time.now - start_time) * 1000).round(2)
sdk.histogram("order.payment.duration").record(duration_ms)
# Capture completion snapshot
sdk.capture_snapshot("order-processing-complete", {
orderId: order_id,
status: "completed",
duration: duration_ms
})
sdk.gauge("orders.active").dec
end🔐 Environment Variables
Best practice: Store sensitive configuration in environment variables:
# .env
TRACEKIT_API_KEY=ctxio_your_generated_api_key_here
TRACEKIT_ENDPOINT={ appURL }
TRACEKIT_SERVICE_NAME=my-rails-app
TRACEKIT_ENVIRONMENT=production
TRACEKIT_CODE_MONITORING=true🏭 Production Configuration
Production Checklist
- • Use HTTPS/TLS for the OTLP endpoint
- • Store API keys in a secrets manager (AWS Secrets Manager, HashiCorp Vault)
- • Set appropriate service names and versions
- • Configure resource attributes (deployment.environment, host.name, etc.)
- • Adjust sampling rates if needed for high-traffic services
🔧 Troubleshooting
Traces Not Appearing?
- Verify your API key is correct and not revoked
- Check the endpoint URL matches your TraceKit instance
- Ensure all required gems are installed
- Check application logs for OpenTelemetry errors
- Verify TraceKit is running and accessible
✅ Complete Example
Here's a complete working Rails example:
# Complete Rails example with TraceKit SDK
# Gemfile
gem 'tracekit'
# .env
TRACEKIT_API_KEY=ctxio_your_generated_api_key_here
TRACEKIT_ENDPOINT={ appURL }
TRACEKIT_SERVICE_NAME=rails-api
TRACEKIT_ENVIRONMENT=production
TRACEKIT_CODE_MONITORING=true
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
# Automatically traced - no code changes needed!
@users = User.all
render json: @users
end
def show
# Automatically traced - no code changes needed!
@user = User.find(params[:id])
render json: @user
end
def create
sdk = Tracekit.sdk
# Track metrics
sdk.counter("users.created").add(1)
# Capture snapshot for debugging
sdk.capture_snapshot("user-creation", {
email: params[:email],
name: params[:name]
})
@user = User.create!(user_params)
render json: @user, status: :created
end
private
def user_params
params.require(:user).permit(:name, :email)
end
end
# That's it! Your Rails app now has:
# - Distributed tracing with automatic span creation
# - Metrics collection (counters, gauges, histograms)
# - Code monitoring with non-breaking snapshotsYou're all set!
Your Ruby application is now sending traces to TraceKit. Visit the Dashboard to see your traces.
Custom Metrics
The TraceKit Ruby SDK includes a lightweight metrics API for tracking counters, gauges, and histograms.
Counter
Track monotonically increasing values (requests, events):
sdk = Tracekit.sdk
# Create a counter with tags
counter = sdk.counter("http.requests.total", {
service: "api",
endpoint: "/users"
})
# Increment the counter
counter.add(1)
counter.add(5) # Add specific valueGauge
Track values that can go up or down (queue size, connections):
sdk = Tracekit.sdk
# Create a gauge
gauge = sdk.gauge("memory.usage.bytes")
# Set absolute value
gauge.set(1024 * 1024 * 512) # 512 MB
# Increment/decrement
gauge.inc # +1
gauge.inc(10) # +10
gauge.dec # -1
gauge.dec(5) # -5Histogram
Track value distributions (latencies, sizes):
sdk = Tracekit.sdk
# Create a histogram with tags
histogram = sdk.histogram("http.request.duration", {
unit: "ms"
})
# Record values
histogram.record(123.45)
histogram.record(67.89)Note: Metrics are automatically buffered and exported via OTLP. View them in the Metrics Explorer.
🚀 Next Steps
- • Add auto-instrumentation libraries for components you use (Redis, Sidekiq, MongoDB, etc.)
- • Explore your traces on the Traces page to identify performance bottlenecks
- • Optionally add custom spans for specific business logic you want to measure
- • Configure sampling for high-traffic services to reduce overhead
- • Set up alert rules to get notified when issues occur