0

I have a rails application running with puma server. Is there any way, we can see how many number of threads used in application currently ?

Manikandan
  • 3,025
  • 2
  • 19
  • 28
  • Possible duplicate of [Puma, how to know the number of active threads](https://stackoverflow.com/questions/43862767/puma-how-to-know-the-number-of-active-threads) – kvantour Jan 28 '18 at 18:25

1 Answers1

0

I was wondering about the same thing a while ago and came upon this issue. The author included the code they ended up using to collect those stats:

module PumaThreadLogger

  def initialize *args
    ret = super *args
    Thread.new do
      while true

        # Every X seconds, write out what the state of this dyno is in a format that Librato understands.
        sleep 5

        thread_count = 0
        backlog = 0
        waiting = 0

        # I don't do the logging or string stuff inside of the mutex. I want to get out of there as fast as possible
        @mutex.synchronize {
          thread_count = @workers.size
          backlog = @todo.size
          waiting = @waiting
        }

        # For some reason, even a single Puma server (not clustered) has two booted ThreadPools.
        # One of them is empty, and the other is actually doing work
        # The check above ignores the empty one
        if (thread_count > 0)

          # It might be cool if we knew the Puma worker index for this worker, but that didn't look easy to me.
          # The good news: By using the PID we can differentiate two different workers on two different dynos with the same name
          # (which might happen if one is shutting down and the other is starting)
          source_name = "#{Process.pid}"

          # If we have a dyno name, prepend it to the source to make it easier to group in the log output
          dyno_name = ENV['DYNO']
          if (dyno_name)
            source_name="#{dyno_name}."+source_name
          end
          msg = "source=#{source_name} "

          msg += "sample#puma.backlog=#{backlog} sample#puma.active_connections=#{thread_count - waiting} sample#puma.total_threads=#{thread_count}"
          Rails.logger.info msg
        end
      end
    end
    ret
  end
end

module Puma
  class ThreadPool
    prepend PumaThreadLogger
  end
end

This code contains logic that is specific to heroku, but the core of collecting the @workers.size and logging it will work in any environment.

Jan Bussieck
  • 1,039
  • 12
  • 26