# NewRelic APM on Hanami 2

**URL:** <https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872>\
**Category:** general\
**Created:** [October 21, 2023, 12:27am UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872 "2023-10-21T00:27:14Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [October 21, 2023, 12:27am UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/1 "2023-10-21T00:27:14Z")

</div>

I spent some time this week implementing New Relic for Hanami 2. I would not recommend it, unless New Relic decides to officially support the framework, for reasons I will get into. I do not have the luxury of choosing an APM vendor presently.

The Ruby agent has seen better days. It is a labyrinthine codebase full of legacy baggage. The documentation website is _years_ out-of-date and full of dead links. The APIs are highly dependent on magic strings that are only ever gestured at in documentation, but never fully explained.

It took me a week to make this work when it should have been an afternoon.

## Controller Instrumentation

This part doesn’t stray far from the docs so I’ll be brief

```ruby
module Actions::Instrumentation
	def self.included(klass)
		klass.include NewRelic::Agent::Instrumentation::ControllerInstrumentation
		klass.extend HandlerTracing
	end

	module HanderTracing
		def method_added(method_name)
			super
			
			return unless method_name == :handler
			return if public_instance_methods.include?(:handle_with_newrelic_transaction_tracer)
			
			add_transaction_tracer :handle, params: 'args[0].params.to_h'
		end
	end
end

```

Since we know the public interface of every Action, I see no sense in manually tracing them. However, you can’t just trace it from the base class because redefining the method in a child class will break the method alias chain it’s doing. This still has the weakness that if you subclass a traced class you’ll break the chain.

It would be preferable to use `prepend` here. There are parts of New Relic’s agent that use it, but not here. Their metaprogramming doesn’t even use kwargs yet.

I tried constructing my own method tracing instead, but the process encapsulated in `add_transaction_trigger` is so convoluted I was unable to get Actions to show up correctly.

## Dependency Instrumentation

This is the interesting part. My first inclination was to use the `dry-monitor` plugin and feed that into New Relic like they do with `ActiveSupport::Notifications`.

There are two problems with the implementation of `dry-monitor` in `dry-system` that make this not viable:

1. monitors must declare the key when registering a handler
2. there is no way to enumerate keys before the container is frozen

So either I had to manually manage the list of keys to trace (yuck) or I had to find a way to trace a frozen container.

Perhaps I’ll come back to it, but I decided to drop `dry-monitor` but take its implementation as inspiration.

I wrote an alternative Proxy object based on `Dry::System::Plugins::Monitoring::Proxy`

```ruby
class Instrumentation::Proxy
	extend Dry::Core::Cache
	include NewRelic::Agent::MethodTracer

	def self.for(target, name:, methods: [])
		traced_methods =
			if methods.empty?
				target.public_methods - Object.public_instance_methods
			else
				methods
			end

		fetch_or_store name, methods do
			Class.new(self) do
				traced_methods.each do |method_name|
					class_eval <<~RUBY, __FILE__ , __LINE__ + 1
						def #{method_name}(...)
							trace_execution_scoped(["#{name}/#{method_name}"]) do
								__getobj__.public_send(#{method_name.inspect}, ...)
							end
						end
					RUBY
				end
				
				define_singleton_method(: __traced_methods__ ) { traced_methods }
				define_singleton_method(:inspect) { "#<Proxy transaction=#{name.inspect}" }
				
				define_method(:class) { target.class }
			end
		end
	end
end

```

A `class_eval` was necessary because I am taking a decorator approach, `add_method_tracer` does not work because it can’t detect the method object from within a SimpleDelegator.

### Configuration

```ruby
class Hanami::Config
	class Instrumentation
		include Dry::Configurable

		setting :tracing_enabled, default: false
		setting :do_not_trace, default: []
	  
		def ignore?(key) = config.do_not_trace.any? { key.to_s.start_with?(_1) }

		private
		
		def method_missing(name, ...)
			if config.respond_to?(name)
				config.public_send(name, ...)
			else
				super
			end
		end
		
		def respond_to_missing?(name, _include_all = false)
			config.respond_to?(name) || super
		end
	end
	
	setting :instrumentation, default: Instrumentation.new, mutable: true
end

```

More on this later

### Decoration

Next, I need a way to decorate all my container keys. I really don’t want to manage all keys by hand, so `Container#decorate` is out. It would be really nice to have a hook that fires after finalization but _before_ freeze.

I decided on a Key resolver. Perhaps hooking into the component loader would have made more sense, I don’t know. I’ll see how this goes.

```ruby
class Instrumentation::KeyResolver < Dry::Core::Container::Resolver
	attr_reader :slice_name
	attr_reader :config
	
	def initialize(slice, ...)
		super(...)
		@slice_name = slice.slice_name.namespace_name
		@config = slice.config.instrumentation
		@proxy = nil
	end
	
	def call(container, key)
		return super unless config.tracing_enabled
		return super if config.ignore?(key)
		
		target = super
		
		if target.singleton_class < Proxy
			target
		else
			proxy(target)
		end
	end
	
	def without_trace(container, key, &)
		method(:call).super_method.(container, key, &)
	end
	
	private
	
	def proxy(key, target)
		Proxy.for(target, name: "Custom/#{slice_name}/#{key}", methods: traceable_methods(target)).new(target)
	end
	
	def traceable_methods(target)
		if target.respond_to?(: __trace_methods__ )
			target. __trace_methods__
		elsif target.class.respond_to?(: __trace_methods__ )
			target.class. __trace__ methods
		else
			[]
		end
	end
end

```

That `Custom/` prefix on the name is one of those magic strings I mentioned.

I’m defining a ` __trace_methods__ ` convention because I kind of hate how New Relic pollutes all your objects with DSL.

That’s all the pieces, now to link them together.

```ruby
module Instrumentation
	module ResolveWithoutTrace
		module Container
			def resolve_without_trace(key, &)
				config.resolver.without_trace(_container, key, &)
			end
		end
		
		module Slice
			def resolve_without_trace(...) = container.resolve_without_trace(...)
		end
	end
	
	def self.included(slice)
		slice.container.after(:configure) do |container|
			container.config.resolver = KeyResolver.new(slice)
			container.extend ResolveWithoutTrace::Container
			slice.extend ResolveWithoutTrace::Slice
		end
	end
end

class App < Hanami::App
	include Instrumentation

	config.instrumentation.tracing_enabled = NewRelic::Agent.config[:agent_enabled]

	config.instrumentation.do_not_trace = %w[
		actions
		logger
		inflector
		persistence
		settings
	]
end

class SCIM::App < Hanami::Slice
	include Instrumentation
	
	config.instrumentation.do_not_trace += %w[crypto]
end

```

## Conclusion

This felt a lot harder than it should have been. Perhaps my choice of decorator pattern contributed to this, but honestly I had the most trouble getting the controller instrumentation to work. I like that the instrumentation is arms-length from the actual business objects.

This is more of a post-mortem than a recommendation. We’ll see if I stick by this in the future, but for now it appears to serve my needs.

---

<div class="post-metadata">

**Author:** ![jodosha](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/jodosha/32/710_2.png) [@jodosha](https://discourse.hanakai.org/u/jodosha)\
**Post date:** [October 21, 2023, 8:00am UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/2 "2023-10-21T08:00:32Z")

</div>

@alassek Thanks for sharing your experience. I totally get your frustration, which is a direct consequence of a Ruby monopoly.

Anything that we should’ve done or that we can do to make this integration less painful?

---

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [October 21, 2023, 10:34pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/3 "2023-10-21T22:34:53Z")

</div>

I think the structure of Hanami made this significantly easier to do, because I was able to decorate my entire application thanks to the dependency system. If New Relic had anything approaching a reasonable API this would have been easy.

I think the only thing that I would have really wanted is the ability to enumerate the keys before the container freeze. That would have made decorating them significantly easier.

That is more a conversation regarding `dry-system` than Hanami per se.

---

<div class="post-metadata">

**Author:** ![jodosha](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/jodosha/32/710_2.png) [@jodosha](https://discourse.hanakai.org/u/jodosha)\
**Post date:** [October 23, 2023, 8:49am UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/4 "2023-10-23T08:49:12Z")

</div>

> [@alassek](#):
>
> I think the only thing that I would have really wanted is the ability to enumerate the keys before the container freeze. That would have made decorating them significantly easier.

@timriley This is useful input for when we’ll design the App boot lifecycle API.

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/solnic/32/757_2.png) [@solnic](https://discourse.hanakai.org/u/solnic)\
**Post date:** [October 25, 2023, 12:25pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/5 "2023-10-25T12:25:01Z")

</div>

Why not hooking into `Container.finalize` and do it there? Production monitoring should be configured only there anyway. Knowing keys upfront would require scanning the filesystem first, which would slow down booting process and even if we did that, it would not guarantee that all the keys would be present because you can register things manually via provider files and use whatever keys you want.

---

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [October 25, 2023, 3:53pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/6 "2023-10-25T15:53:32Z")

</div>

[`before_finalize`](https://github.com/dry-rb/dry-system/blob/main/lib/dry/system/container.rb#L322) fires before keys are populated, [`after_finalize`](https://github.com/dry-rb/dry-system/blob/main/lib/dry/system/container.rb#L333) fires after `freeze` has been called.

I agree that monitoring should ideally be done here. There is no need to know the keys upfront, I just want to enumerate and decorate them before the container is frozen. That should be done as late in the process as possible.

Is there an actual reason why `after_finalize` needs to take place after freeze? Is it possible to call that before `freeze`? Or perhaps we could introduce `before_freeze` for this if not.

---

<div class="post-metadata">

**Author:** ![solnic](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/solnic/32/757_2.png) [@solnic](https://discourse.hanakai.org/u/solnic)\
**Post date:** [October 25, 2023, 4:08pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/7 "2023-10-25T16:08:39Z")

</div>

That’s too bad 😕 I think we should add a way to hook into it via`before_freeze` like you suggested and make it public API 🙂

---

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [October 25, 2023, 7:09pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/8 "2023-10-25T19:09:50Z")

</div>

Here is a potential surgical fix for this problem: [Defer `Dry::System::Container` freeze](https://github.com/hanami/hanami/pull/1360).

The `freeze` call is gated by an argument, so Hanami can defer this until after the hooks run.

---

<div class="post-metadata">

**Author:** ![timriley](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/timriley/32/621_2.png) [@timriley](https://discourse.hanakai.org/u/timriley)\
**Post date:** [October 30, 2023, 9:50am UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/9 "2023-10-30T09:50:00Z")

</div>

This is great discussion, folks!

> [@alassek](#):
>
> Here is a potential surgical fix for this problem: [Defer `Dry::System::Container` freeze](https://github.com/hanami/hanami/pull/1360).

I’ve responded in the PR with a suggestion that I think dry-container is probably the better suited place for this. Keen for your thoughts, @alassek.

While I’m here:

> [@solnic](#):
>
> Why not hooking into `Container.finalize` and do it there? Production monitoring should be configured only there anyway.

From my perspective I think that running a prepared-only Hanami app (i.e. _not_ running Hanami.boot) is a completely valid way of operating Hanami for certain circumstances (imagine e.g. a serverless function that needs to run just one narrow slice of a fuller app).

In addition, we never fully boot Hanami in dev mode, either.

This does have an impact on what hooks make the most sense for extending framework behaviour.

---

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [June 15, 2024, 10:09pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/10 "2024-06-15T22:09:50Z")

</div>

I didn’t mean for this to take so long (sorry about that) but here is the PR that implements our current design: [Make Container hooks more useful for dynamic registration by alassek · Pull Request #274 · dry-rb/dry-system · GitHub](https://github.com/dry-rb/dry-system/pull/274)

---

<div class="post-metadata">

**Author:** ![alassek](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.hanakai.org/alassek/32/532_2.png) [@alassek](https://discourse.hanakai.org/u/alassek)\
**Post date:** [August 14, 2026, 5:27pm UTC](https://discourse.hanakai.org/t/newrelic-apm-on-hanami-2/872/11 "2026-08-14T17:27:27Z")

</div>

I noticed we were missing database telemetry in NewRelic. This appears to be a consequence of moving to Hanami’s ROM integration, but I’m not 100% certain. The Sequel integration was simply not sending data at all.

I don’t care to spend much more time navigating NewRelic’s codebase. But I do know that ROM provides its own telemetry as a plugin

```ruby
# Within our DB Provider configuration
sql.plugin relations: :instrumentation do |plugin|
  plugin.notifications = slice["notifications"]
end

```

```ruby
module Instrumentation
  class SQL
    def on_sql(event)
      return unless defined?(NewRelic::Agent::Tracer)

      payload = event.payload
      elapsed_ms = payload[:time]
      return unless elapsed_ms

      query = payload[:query].to_s
      operation = NewRelic::Agent::Datastores::MetricHelper.operation_from_sql(query)

      start_time = Process.clock_gettime(Process::CLOCK_REALTIME) - (elapsed_ms / 1000.0)

      segment = NewRelic::Agent::Tracer.start_datastore_segment(
        product: "Postgres",
        operation: operation,
        start_time: start_time
      )

      segment.notice_sql(query)
    rescue => err
      NewRelic::Agent.logger&.warn("rom-sql NewRelic listener failed: #{err.message}")
    ensure
      segment&.finish
    end
  end
end

```

Since the `notifications` bus is global for the whole app, this needs to be subscribed exactly once.

```ruby
module Instrumentation
  # snip

  def self.included(slice)
    # snip

    if slice.app?
      slice.container.after(:finalize) do |container|
        container.resolve("notifications").subscribe(SQL.new)
      end
    end
  end
end

```
