LoginSignup
111
82

More than 5 years have passed since last update.

nginx+puma+rails の worker,thread,connection pool 数の目安

Last updated at Posted at 2016-10-17

※間違ってたら指摘を...

前提

MRI(Matz's Ruby Implementation) の前提, JRubyの場合は考え方が変わる。

nginx の worker 数の目安

CPUコア数を基本とする。ただし...

一方で、例えば僕の用途では、現在画像の処理だったりとか、ngx_mrubyのようにリクエストの過程で一部ブロッキングされるような処理も増えてきているため、コア数以上の値に設定しておいた方が性能を発揮できるような状況も増えてきています。
nginxのworkerプロセス数をCPUコア数の倍数で自動的に設定できるモジュールを書いた - 人間とウェブの未来

上記のようにコア数以上に設定した方が良いケースも時としてあるようです。

nginx の worker 数を設定する

以下のように conf を設定してあげれば、nginxがコア数に応じたプロセスを立ち上げてくれる。

/etc/nginx.conf
worker_processes auto;

puma の worker 数の目安

CPUコア数〜1.5倍を基本とする

Use cluster mode and set the number of workers to 1.5x the number of cpu cores in the machine, minimum 2.
https://github.com/puma/puma/blob/master/docs/deployment.md

puma の thread 数の目安

Set the number of threads to desired concurrent requests / number of workers. Puma defaults to 16 and that's a decent number.

デフォルトの 16 therad (1プロセスあたり)はちょうど良いくらいの設定らしい?

Watching your CPU utilization over time and aim for about 70% on average. This means you've got capacity still but aren't starving threads.

目安としてはCPU使用率が平均して70%程度となる状態を目指す。その状態であればカツカツではないけどある程度キャパシティを活用している状態と言えるとのこと。

MRIはGILによって1プロセスの中で同時に動作するスレッドは1スレッドのみに制限されるが、スレッド内でのIO待ち(DB,ファイル等)の間に別スレッドでリクエスト処理できるので、そこそこ効果はあると言われている。

database の connection pool 数の目安

puma の thread 数と同数とする。
database.yml に設定された pool の数はプロセスごとに確保される値なので、thread数を設定すれば十分。

If you are using the Puma web server we recommend setting the pool value to equal ENV['RAILS_MAX_THREADS']
Concurrency and Database Connections in Ruby with ActiveRecord | Heroku Dev Center

puma の worker 数, thread 数, db の connection pool 数 を設定する

手元の Rails 5.1.3 では thread 数と connection pool 数は、環境変数 RAILS_MAX_THREADS に従うようになっていました。

puma の worker 数は環境変数 WEB_CONCURRENCY に従うような設定が記述されていますが、デフォルトでコメントアウトされているのでアンコメントして有効化する必要があります。

config/puma.rb
# thread数
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count

# worker プロセス数
workers ENV.fetch("WEB_CONCURRENCY") { 2 }

db の connection pool 数は、デフォルトで RAILS_MAX_THREADS に従うようになっています。

config/database.yml
default: &default
 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

以下は要確認

参考

111
82
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
111
82