ruby 65 lines · 2 tabs

API monitoring with custom instrumentation

Alex Kumar Jan 2026
2 tabs
class ExternalApiClient
  def fetch_user_data(user_id)
    ActiveSupport::Notifications.instrument(
      'api.external_service',
      service: 'user_service',
      operation: 'fetch_user',
      user_id: user_id
    ) do
      response = HTTP.get("https://api.example.com/users/#{user_id}")

      if response.status.success?
        JSON.parse(response.body)
      else
        raise ApiError, "Failed to fetch user: #{response.status}"
      end
    end
  rescue StandardError => e
    ActiveSupport::Notifications.instrument(
      'api.external_service.error',
      service: 'user_service',
      operation: 'fetch_user',
      error: e.class.name
    )
    raise e
  end
end
2 files · ruby Explain with highlit

Production visibility requires more than basic request logging. I instrument critical code paths using ActiveSupport::Notifications to publish custom metrics that monitoring services consume. Each instrumented block publishes events with timing data, metadata, and success/failure indicators. I track business metrics like API calls to external services, cache hit rates, and background job durations. These metrics feed into dashboards and alerts that surface degradations before they become outages. The instrumentation API is lightweight and doesn't require external dependencies—I can log to Rails logger in development and ship to Datadog or StatsD in production by subscribing to the notification channel.


Related snips

Share this code

Here's the card — post it anywhere.

API monitoring with custom instrumentation — share card
Link copied