123456789_123456789_123456789_123456789_123456789_

Class: Puma::DSL

Relationships & Source Files
Inherits: Object
Defined in: lib/puma/dsl.rb

Overview

The methods that are available for use inside the configuration file. These same methods are used in ::Puma CLI and the Rack handler internally.

Used manually (via CLI class):

config = Configuration.new({}) do |user_config|
user_config.port 3001
end
config.clamp

puts config.options[:binds] # => "tcp://127.0.0.1:3001"

Used to load file:

$ cat puma_config.rb
port 3002

Resulting configuration:

config = Configuration.new(config_file: "puma_config.rb")
config.clamp

puts config.options[:binds] # => "tcp://127.0.0.1:3002"

You can also find many examples being used by the test suite in test/config.

::Puma v6 adds the option to specify a key name (String or Symbol) to the hooks that run inside the forked workers. All the hooks run inside the Cluster::Worker#run method.

Previously, the worker index and the LogWriter instance were passed to the hook blocks/procs. If a key name is specified, a hash is passed as the last parameter. This allows storage of data, typically objects that are created before the worker that need to be passed to the hook when the worker is shutdown.

The following hooks have been updated:

| DSL Method             |  Options Key            | Fork Block Location |
| before_worker_boot     | :before_worker_boot     | inside, before      |
| before_worker_shutdown | :before_worker_shutdown | inside, after       |
| before_refork          | :before_refork          | inside              |
| after_refork           | :after_refork           | inside              |

Constant Summary

Class Method Summary

Instance Method Summary

Constructor Details

.new(options, config) ⇒ DSL

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 126

def initialize(options, config)
  @config  = config
  @options = options

  @plugins = []
end

Class Method Details

.ssl_bind_str(host, port, opts)

Convenience method so logic can be used in CI.

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 59

def self.ssl_bind_str(host, port, opts)
  verify = opts.fetch(:verify_mode, 'none').to_s

  tls_str =
    if opts[:no_tlsv1_1]  then '&no_tlsv1_1=true'
    elsif opts[:no_tlsv1] then '&no_tlsv1=true'
    else ''
    end

  ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify)

  low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : ''
  backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : ''

  if defined?(JRUBY_VERSION)
    cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name
    cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites]
    protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil

    keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
    keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type]
    if opts[:truststore]
      truststore_additions = "&truststore=#{opts[:truststore]}"
      truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass]
      truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type]
    end

    "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \
      "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}"
  else
    ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil
    ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil
    v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil

    cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil
    key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil
    password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil

    reuse_flag =
      if (reuse = opts[:reuse])
        if reuse == true
          '&reuse=dflt'
        elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout))
          val = +''
          if (size = reuse[:size]) && Integer === size
            val << size.to_s
          end
          if (timeout = reuse[:timeout]) && Integer === timeout
            val << ",#{timeout}"
          end
          if val.empty?
            nil
          else
            "&reuse=#{val}"
          end
        else
          nil
        end
      else
        nil
      end

    "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \
      "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}"
  end
end

Instance Method Details

#_load_from(path)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 133

def _load_from(path)
  if path
    @path = path
    instance_eval(File.read(path), path, 1)
  end
ensure
  _offer_plugins
end

#_offer_plugins

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 142

def _offer_plugins
  @plugins.each do |o|
    if o.respond_to? :config
      @options.shift
      o.config self
    end
  end

  @plugins.clear
end

#activate_control_app(url = "auto", opts = {})

Start the ::Puma control rack application on url. This application can be communicated with to control the main server. Additionally, you can provide an authentication token, so all requests to the control server will need to include that token as a query parameter. This allows for simple authentication.

Check out App::Status to see what the app has available.

Examples:

activate_control_app 'unix:///var/run/pumactl.sock'
activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' }
activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true }
activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true, data_only: true}
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 222

def activate_control_app(url="auto", opts={})
  if url == "auto"
    path = Configuration.temp_path
    @options[:control_url] = "unix://#{path}"
    @options[:control_url_temp] = path
  else
    @options[:control_url] = url
  end

  if opts[:no_token]
    # We need to use 'none' rather than :none because this value will be
    # passed on to an instance of OptionParser, which doesn't support
    # symbols as option values.
    #
    # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488
    auth_token = 'none'
  else
    auth_token = opts[:auth_token]
    auth_token ||= Configuration.random_token
  end

  @options[:control_auth_token] = auth_token
  @options[:control_url_umask] = opts[:umask] if opts[:umask]
  @options[:control_data_only] = opts[:data_only] if opts[:data_only]
end

#add_pem_values_to_options_store(opts) (private)

To avoid adding cert_pem and key_pem as URI params, we store them on the options from where ::Puma binder knows how to find and extract them.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1600

def add_pem_values_to_options_store(opts)
  return if defined?(JRUBY_VERSION)

  @options[:store] ||= []

  # Store cert_pem and key_pem to options[:store] if present
  [:cert, :key].each do |v|
    opt_key = :"#{v}_pem"
    if opts[opt_key]
      index = @options[:store].length
      @options[:store] << opts[opt_key]
      opts[v] = "store:#{index}"
    end
  end
end

#after_booted(&block) Also known as: #on_booted

Code to run after ::Puma is booted (works for both single and cluster modes).

Examples:

after_booted do
  puts 'After booting...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 939

def after_booted(&block)
  Puma.deprecate_method_change :on_booted, __callee__, __method__

  @config.events.after_booted(&block)
end

#after_refork(key = nil, &block)

Note:

Cluster mode with #fork_worker enabled only.

When #fork_worker is enabled, code to run in Worker 0 after all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).

This can be used to re-open any connections to remote servers (database, Redis, ...) that were closed via before_refork.

This can be called multiple times to add several hooks.

Examples:

after_refork do
  puts 'After refork...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1006

def after_refork(key = nil, &block)
  process_hook :after_refork, key, block
end

#after_stopped(&block) Also known as: #on_stopped

Code to run after ::Puma is stopped (works for both single and cluster modes).

Examples:

after_stopped do
  puts 'After stopping...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 954

def after_stopped(&block)
  Puma.deprecate_method_change :on_stopped, __callee__, __method__

  @config.events.after_stopped(&block)
end

#after_worker_boot(&block)

Alias for #after_worker_fork.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 914

alias_method :after_worker_boot, :after_worker_fork

#after_worker_fork(&block) Also known as: #after_worker_boot

Note:

Cluster mode only.

Code to run in the master after a worker has been started. The worker's index is passed as an argument.

This is called every time a worker is to be started.

Examples:

after_worker_fork do
  puts 'After worker fork...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 910

def after_worker_fork(&block)
  process_hook :after_worker_fork, nil, block, cluster_only: true
end

#after_worker_shutdown(&block)

Note:

Cluster mode only.

Code to run in the master right after a worker has stopped. A Cluster::WorkerHandle is passed as an argument.

This can be called multiple times to add several hooks.

Examples:

after_worker_shutdown do |worker_handle|
  puts 'Worker crashed' unless worker_handle.process_status.success?
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 928

def after_worker_shutdown(&block)
  process_hook :after_worker_shutdown, nil, block, cluster_only: true
end

#allow_underscore_headers(allowed = true)

When false, request headers with underscores in their names are discarded. When such headers are present, their names are exposed in env["puma.underscore_headers"] for auditing. This value is client-triggerable, so rate-limit or sample external reporting.

The default is true, but will change to false in a future major version, when this env metadata will be removed.

Examples:

allow_underscore_headers false
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1508

def allow_underscore_headers(allowed=true)
  @options[:allow_underscore_headers] = allowed
end

#app(obj = nil, &block)

Use an object or block as the rack application. This allows the configuration file to be the application itself.

Examples:

app do |env|
  body = 'Hello, World!'

  [
    200,
    {
      'Content-Type' => 'text/plain',
      'Content-Length' => body.length.to_s
    },
    [body]
  ]
end

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 197

def app(obj=nil, &block)
  obj ||= block

  raise "Provide either a #call'able or a block" unless obj

  @options[:app] = obj
end

#before_fork(&block)

Note:

Cluster mode only.

Code to run immediately before master process forks workers (once on boot). These hooks can block if necessary to wait for background operations unknown to ::Puma to finish before the process terminates. This can be used to close any connections to remote servers (database, Redis, ...) that were opened when preloading the code.

This can be called multiple times to add several hooks.

Examples:

before_fork do
  puts "Starting workers..."
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 831

def before_fork(&block)
  process_hook :before_fork, nil, block, cluster_only: true
end

#before_refork(key = nil, &block) Also known as: #on_refork

Note:

Cluster mode with #fork_worker enabled only.

When #fork_worker is enabled, code to run in Worker 0 before all other workers are re-forked from this process, after the server has temporarily stopped serving requests (once per complete refork cycle).

This can be used to trigger extra garbage-collection to maximize copy-on-write efficiency, or close any connections to remote servers (database, Redis, ...) that were opened while the server was running.

This can be called multiple times to add several hooks.

Examples:

before_refork do
  3.times {GC.start}
end

Version:

  • 5.0.0

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 981

def before_refork(key = nil, &block)
  Puma.deprecate_method_change :on_refork, __callee__, __method__

  process_hook :before_refork, key, block, cluster_only: true
end

#before_restart(&block) Also known as: #on_restart

Code to run before doing a restart. This code should close log files, database connections, etc.

This can be called multiple times to add code each time.

Examples:

before_restart do
  puts 'On restart...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 452

def before_restart(&block)
  Puma.deprecate_method_change :on_restart, __callee__, __method__

  process_hook :before_restart, nil, block
end

#before_thread_exit(&block) Also known as: #on_thread_exit

Provide a block to be executed after a thread is trimmed from the thread pool. Note that while this block executes, Puma's main loop is blocked, so no new requests will be picked up.

This hook only runs when a thread in the threadpool is trimmed by ::Puma. It does not run when a thread dies due to exceptions or any other cause.

Return values are ignored. Raising an exception will log a warning.

This hook is useful for cleaning up thread local resources when a thread is trimmed.

This can be called multiple times to add several hooks.

Examples:

before_thread_exit do
  puts 'On thread exit...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1055

def before_thread_exit(&block)
  Puma.deprecate_method_change :on_thread_exit, __callee__, __method__

  process_hook :before_thread_exit, nil, block
end

#before_thread_start(&block) Also known as: #on_thread_start

Provide a block to be executed just before a thread is added to the thread pool. Note that while the block executes, thread creation is delayed, and a request may have to wait. The new thread will not be added to the threadpool until the provided block returns.

Return values are ignored. Raising an exception will log a warning.

This hook is useful for doing something when the thread pool grows.

This can be called multiple times to add several hooks.

Examples:

before_thread_start do
  puts 'On thread start...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1027

def before_thread_start(&block)
  Puma.deprecate_method_change :on_thread_start, __callee__, __method__

  process_hook :before_thread_start, nil, block
end

#before_worker_boot(key = nil, &block) Also known as: #on_worker_boot

Note:

Cluster mode only.

Code to run in a worker on boot to set up the process before the app is loaded. The worker's index is passed as an argument.

This can be called multiple times to add several hooks.

Examples:

before_worker_boot do
  puts 'Before worker boot...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 847

def before_worker_boot(key = nil, &block)
  Puma.deprecate_method_change :on_worker_boot, __callee__, __method__

  process_hook :before_worker_boot, key, block, cluster_only: true
end

#before_worker_fork(&block) Also known as: #on_worker_fork

Note:

Cluster mode only.

Code to run in the master right before a worker is started. The worker's index is passed as an argument.

This can be called multiple times to add several hooks.

Examples:

before_worker_fork do
  puts 'Before worker fork...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 890

def before_worker_fork(&block)
  Puma.deprecate_method_change :on_worker_fork, __callee__, __method__

  process_hook :before_worker_fork, nil, block, cluster_only: true
end

#before_worker_shutdown(key = nil, &block) Also known as: #on_worker_shutdown

Note:

Cluster mode only.

Code to run immediately before a worker shuts down (after it has finished processing HTTP requests). The worker's index is passed as an argument. These hooks can block if necessary to wait for background operations unknown to ::Puma to finish before the process terminates.

This can be called multiple times to add several hooks.

Examples:

before_worker_shutdown do
  puts 'On worker shutdown...'
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 870

def before_worker_shutdown(key = nil, &block)
  Puma.deprecate_method_change :on_worker_shutdown, __callee__, __method__

  process_hook :before_worker_shutdown, key, block, cluster_only: true
end

#bind(url)

Bind the server to url. "tcp://", "unix://" and "ssl://" are the only accepted protocols. Multiple urls can be bound to, calling bind does not overwrite previous bindings.

The default is "tcp://[::]:9292" when IPv6 interfaces are available, otherwise "tcp://0.0.0.0:9292".

You can use query parameters within the url to specify options:

  • Set the socket backlog depth with backlog, default is 1024.
  • Set up an SSL certificate with key & cert.
  • Set up an SSL certificate for mTLS with key, cert, ca and verify_mode.
  • Set whether to optimize for low latency instead of throughput with low_latency, default is to not optimize for low latency. This is done via Socket::TCP_NODELAY.
  • Set socket permissions with umask.

Examples:

Backlog depth

bind 'unix:///var/run/puma.sock?backlog=512'

SSL cert

bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem'

SSL cert for mutual TLS (mTLS)

bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer'

Disable optimization for low latency

bind 'tcp://[::]:9292?low_latency=false'

Socket permissions

bind 'unix:///var/run/puma.sock?umask=0111'

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 290

def bind(url)
  @options[:binds] ||= []
  @options[:binds] << url
end

#bind_to_activated_sockets(bind = true)

Bind to (systemd) activated sockets, regardless of configured binds.

Systemd can present sockets as file descriptors that are already opened. By default ::Puma only uses these if it was explicitly told to bind to the socket, otherwise it closes them. Since only SSL config on a bind is relevant for activated sockets (unix and TCP socket options are ignored), this often means duplicating configuration for no benefit.

This method tells the launcher to bind to all activated sockets, regardless of existing binds. Passing 'only' also clears any configured binds so that only activated sockets are used.

The default is nil.

Examples:

Use any systemd activated sockets as well as configured binds

bind_to_activated_sockets

Only bind to systemd activated sockets, ignoring other binds

bind_to_activated_sockets 'only'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 319

def bind_to_activated_sockets(bind=true)
  @options[:bind_to_activated_sockets] = bind
end

#clean_thread_locals(which = true)

Alias for #fiber_per_request.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 387

alias clean_thread_locals fiber_per_request

#clear_binds!

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 295

def clear_binds!
  @options[:binds] = []
end

#cluster(&block)

Note:

Cluster mode only.

Code to run only in cluster mode. Runs after all config files are loaded.

This can be called multiple times.

Examples:

cluster do
  prune_bundler
end

Raises:

  • (ArgumentError)
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 808

def cluster(&block)
  raise ArgumentError, "A block must be provided to `cluster`" unless block

  @options[:cluster] ||= []
  @options[:cluster] << block
end

#custom_logger(custom_logger)

Pass in a custom logging class instance.

Examples:

custom_logger Logger.new('t.log')
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 511

def custom_logger(custom_logger)
  @options[:custom_logger] = custom_logger
end

#debug

Show debugging info.

The default is false.

Examples:

debug
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 522

def debug
  @options[:debug] = true
end

#default_host

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 157

def default_host
  @options[:default_host] || Configuration.default_tcp_host
end

#directory(dir)

The directory to operate out of.

The default is the current directory.

Examples:

directory '/u/apps/lolcat'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1089

def directory(dir)
  @options[:directory] = dir.to_s
end

#drain_on_shutdown(which = true)

When shutting down, drain the accept socket of pending connections and process them before waiting for in-flight requests to finish.

The default is nil.

Examples:

drain_on_shutdown

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 399

def drain_on_shutdown(which=true)
  @options[:drain_on_shutdown] = which
end

#early_hints(answer = true)

Enable HTTP 103 Early Hints responses.

The default is nil.

Examples:

early_hints
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 557

def early_hints(answer=true)
  @options[:early_hints] = answer
end

#enable_keep_alives(enabled = true)

When true, keep-alive connections are maintained on inbound requests. Enabling this setting reduces the number of TCP operations, reducing response times for connections that can send multiple requests in a single connection.

When Puma receives more incoming connections than available ::Puma threads, enabling the keep-alive behavior may result in processing requests out-of-order, increasing overall response time variance. Increased response time variance means that the overall average of response times might not change, but more outliers will exist. Those long-tail outliers may significantly affect response times for some processed requests.

When false, ::Puma closes the connection after each request, requiring the client to open a new request. Disabling this setting guarantees that requests will be processed in the order they are fully received, decreasing response variance and eliminating long-tail outliers caused by keep-alive behavior. The trade-off is that the number of TCP operations required will increase.

The default is true.

Examples:

enable_keep_alives false
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1493

def enable_keep_alives(enabled=true)
  @options[:enable_keep_alives] = enabled
end

#environment(environment)

Set the environment in which the Rack app will run. The value must be a string.

The default is "development".

Examples:

environment 'production'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 411

def environment(environment)
  @options[:environment] = environment
end

#extra_runtime_dependencies(answer = [])

When using prune_bundler, if extra runtime dependencies need to be loaded to initialize your app, then this setting can be used. This includes any ::Puma plugins.

Before bundler is pruned, the gem names supplied will be looked up in the bundler context and then loaded again after bundler is pruned. Only applies if prune_bundler is used.

Examples:

extra_runtime_dependencies ['gem_name_1', 'gem_name_2']
extra_runtime_dependencies ['puma_worker_killer', 'puma-heroku']

See Also:

  • Puma::Launcher#extra_runtime_deps_directories
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1182

def extra_runtime_dependencies(answer = [])
  @options[:extra_runtime_dependencies] = Array(answer)
end

#fiber_per_request(which = true) Also known as: #clean_thread_locals

Use a clean fiber per request which ensures a clean slate for fiber locals and fiber storage. Also provides a cleaner backtrace with less ::Puma internal stack frames.

The default is false.

Examples:

fiber_per_request
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 383

def fiber_per_request(which=true)
  @options[:fiber_per_request] = which
end

#first_data_timeout(seconds)

Define how long the TCP socket stays open when no data has been received.

The default is 30 seconds.

Examples:

first_data_timeout 40

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 344

def first_data_timeout(seconds)
  @options[:first_data_timeout] = Integer(seconds)
end

#force_shutdown_after(val = :forever)

How long to wait for threads to stop when shutting them down. Specifying :immediately will cause ::Puma to kill the threads immediately. Otherwise the value is the number of seconds to wait.

::Puma always waits a few seconds after killing a thread for it to try to finish up its work, even in :immediately mode.

The default is :forever.

Examples:

force_shutdown_after 30

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 429

def force_shutdown_after(val=:forever)
  i = case val
      when :forever
        -1
      when :immediately
        0
      else
        Float(val)
      end

  @options[:force_shutdown_after] = i
end

#fork_worker(after_requests = 1000)

Note:

This is experimental.

Note:

Cluster mode only.

When enabled, workers will be forked from worker 0 instead of from the master process. This option is similar to preload_app because the app is preloaded before forking, but it is compatible with phased restart.

This option also enables the refork command (SIGURG), which optimizes copy-on-write performance in a running app.

A refork will automatically trigger once after the specified number of requests (default 1000), or pass 0 to disable auto refork.

The default is nil.

Examples:

fork_worker
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1445

def fork_worker(after_requests=1000)
  @options[:fork_worker] = Integer(after_requests)
end

#get(key, default = nil)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 165

def get(key,default=nil)
  @options[key.to_sym] || default
end

#http_content_length_limit(limit)

Specify the maximum request payload size, in bytes. If the value of the Content-Length header exceeds this limit, an HTTP 413 status code is returned.

This limit is only applicable when the client sends a Content-Length header, or Transfer-Encoding is chunked. Otherwise there is no request body.

The default is nil.

http_content_length_limit 2_000_000_000

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1559

def http_content_length_limit(limit)
  @options[:http_content_length_limit] = limit
end

#idle_timeout(seconds)

If a new request is not received within this number of seconds, begin shutting down.

The default is nil.

Examples:

idle_timeout 60

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 370

def idle_timeout(seconds)
  @options[:idle_timeout] = Integer(seconds)
end

#inject(&blk)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 161

def inject(&blk)
  instance_eval(&blk)
end

#io_selector_backend(backend)

Specify the backend for the IO selector.

Provided values will be passed directly to NIO::Selector.new, with the exception of :auto which will let nio4r choose the backend.

Check the documentation of NIO::Selector.backends for the list of valid options. Note that the available options on your system will depend on the operating system. If you want to use the pure Ruby backend (not recommended due to its comparatively low performance), set environment variable NIO4R_PURE to true.

The default is :auto.

Examples:

io_selector_backend :epoll

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1530

def io_selector_backend(backend)
  @options[:io_selector_backend] = backend.to_sym
end

#load(file)

Load additional configuration from a file. Files get loaded later via Configuration#load.

Examples:

load 'config/puma/production.rb'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 254

def load(file)
  @options[:config_files] ||= []
  @options[:config_files] << file
end

#log_formatter(&block)

Provide a block to format log messages. The block receives the message string and should return the formatted string.

Examples:

log_formatter do |str|
  "[#{Time.now}] #{str}"
end

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 585

def log_formatter(&block)
  @options[:log_formatter] = block
end

#log_requests(which = true)

Enable request logging, the inverse of #quiet.

The default is false.

Examples:

log_requests

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 502

def log_requests(which=true)
  @options[:log_requests] = which
end

#lowlevel_error_handler(obj = nil, &block)

Use obj or block as the low level error handler. This allows the configuration file to change the default error on the server.

Examples:

lowlevel_error_handler do |err|
  [200, {}, ["error page"]]
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1116

def lowlevel_error_handler(obj=nil, &block)
  obj ||= block
  raise "Provide either a #call'able or a block" unless obj
  @options[:lowlevel_error_handler] = obj
end

#max_fast_inline(num_of_requests)

Deprecated.

Use #max_keep_alive instead.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1451

def max_fast_inline(num_of_requests)
  Puma.deprecate_method_change :max_fast_inline, __method__, :max_keep_alive
  @options[:max_keep_alive] ||= Float(num_of_requests) unless num_of_requests.nil?
end

#max_io_threads(max)

Configure the max number of IO threads.

When request handlers know the current requests will no longer use a significant amount of CPU, they can mark the current request as IO bound using env.

Threads marked as IO bound are allowed to go over the max thread limit. Any IO thread over the limit is counted as a regular thread, so a configuration of 5 regular threads and 5 IO threads may also allow, for example, 3 regular threads and 7 IO threads to process requests concurrently.

The default is 0.

Examples:

threads 5
max_io_threads 5
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 636

def max_io_threads(max)
  max = Integer(max)
  if max < 0
    raise "The maximum number of IO threads (#{max}) must be a positive number"
  end

  @options[:max_io_threads] = max
end

#max_keep_alive(num_of_requests)

The number of requests a keep-alive client can submit before being closed. Note that some applications (server to server) may benefit from a very high number or Float::INFINITY.

The default is 999.

Examples:

max_keep_alive 20

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1467

def max_keep_alive(num_of_requests)
  @options[:max_keep_alive] = Float(num_of_requests) unless num_of_requests.nil?
end

#mutate_stdout_and_stderr_to_sync_on_write(enabled = true)

Ensures STDOUT and STDERR are immediately flushed to the underlying operating system and are not buffered internally.

The default is true.

Examples:

mutate_stdout_and_stderr_to_sync_on_write false
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1542

def mutate_stdout_and_stderr_to_sync_on_write(enabled=true)
  @options[:mutate_stdout_and_stderr_to_sync_on_write] = enabled
end

#on_booted(&block)

Alias for #after_booted.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 945

alias_method :on_booted, :after_booted

#on_refork(key = nil, &block)

Alias for #before_refork.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 987

alias_method :on_refork, :before_refork

#on_restart(&block)

Alias for #before_restart.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 458

alias_method :on_restart, :before_restart

#on_stopped(&block)

Alias for #after_stopped.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 959

alias_method :on_stopped, :after_stopped

#on_thread_exit(&block)

Alias for #before_thread_exit.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1061

alias_method :on_thread_exit, :before_thread_exit

#on_thread_start(&block)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1033

alias_method :on_thread_start, :before_thread_start

#on_worker_boot(key = nil, &block)

Alias for #before_worker_boot.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 853

alias_method :on_worker_boot, :before_worker_boot

#on_worker_fork(&block)

Alias for #before_worker_fork.

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 896

alias_method :on_worker_fork, :before_worker_fork

#on_worker_shutdown(key = nil, &block)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 876

alias_method :on_worker_shutdown, :before_worker_shutdown

#out_of_band(&block)

Code to run out-of-band when the worker is idle. These hooks run immediately after a request has finished processing and there are no busy threads on the worker. The worker doesn't accept new requests until this code finishes.

This hook is useful for running out-of-band garbage collection or scheduling asynchronous tasks to execute after a response.

This can be called multiple times to add several hooks.

Examples:

out_of_band do
  GC.start
end
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1078

def out_of_band(&block)
  process_hook :out_of_band, nil, block
end

#persistent_timeout(seconds)

Define how long persistent connections can be idle before ::Puma closes them.

The default is 65 seconds.

Examples:

persistent_timeout 30

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 357

def persistent_timeout(seconds)
  @options[:persistent_timeout] = Integer(seconds)
end

#pidfile(path)

Store the PID of the server in the file at path.

Examples:

pidfile '/u/apps/lolcat/tmp/pids/puma.pid'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 476

def pidfile(path)
  @options[:pidfile] = path.to_s
end

#plugin(name)

Load the named plugin for use by this configuration.

Examples:

plugin :tmp_restart
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 174

def plugin(name)
  @plugins << @config.load_plugin(name)
end

#port(port, host = nil)

Define the TCP port to bind to. Use #bind for more advanced options.

The default is 9292.

Examples:

port 3000
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 330

def port(port, host=nil)
  host ||= default_host
  bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s
end

#preload_app!(answer = true)

Note:

Cluster mode only.

Note:

When using #fork_worker, this only applies to worker 0.

Preload the application before forking the workers; this conflicts with the phased restart feature.

The default is true if your app uses more than 1 worker.

Examples:

preload_app!
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1104

def preload_app!(answer=true)
  @options[:preload_app] = answer
end

#process_hook(options_key, key, block, cluster_only: false) (private)

Raises:

  • (ArgumentError)
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1616

def process_hook(options_key, key, block, cluster_only: false)
  raise ArgumentError, "expected #{options_key} to be given a block" unless block

  @config.hooks[options_key] = true

  @options[options_key] ||= []
  hook_options = { block: block, cluster_only: cluster_only }
  hook_options[:id] = if ON_WORKER_KEY.include?(key.class)
    key.to_sym
  elsif key.nil?
    nil
  else
    raise "'#{options_key}' key must be String or Symbol"
  end
  @options[options_key] << hook_options
end

#prune_bundler(answer = true)

Note:

Cluster mode only.

Note:

This is incompatible with #preload_app!.

Note:

This is only supported for RubyGems 2.2+.

This option is used to allow your app and its gems to be properly reloaded when not using preload.

When set, if ::Puma detects that it's been invoked in the context of Bundler, it will cleanup the environment and re-run itself outside the Bundler environment, but directly using the files that Bundler has setup.

This means that ::Puma is now decoupled from your Bundler context and when each worker loads, it will be loading a new Bundler context and thus can float around as the release dictates.

The default is false.

Examples:

prune_bundler

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1146

def prune_bundler(answer=true)
  @options[:prune_bundler] = answer
end

#queue_requests(answer = true)

When true, a worker thread that receives a client with an incomplete request body hands the client to a Reactor thread and returns to the pool. The Reactor re-enqueues the client once the body has been received. This frees workers from blocking on slow client sends and enables HTTP keep-alive. A worker must still receive each client first, so this does not queue new connections when the pool is saturated.

When false, no Reactor runs. A worker thread reads each request synchronously and remains occupied for the duration of the client's request send, and HTTP keep-alive is disabled. Consider running ::Puma behind a reverse proxy such as nginx that can buffer requests and protect ::Puma from slow clients.

The default is true.

Examples:

queue_requests false

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1325

def queue_requests(answer=true)
  @options[:queue_requests] = answer
end

#quiet(which = true)

Disable request logging, the inverse of #log_requests.

The default is false.

Examples:

quiet

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 489

def quiet(which=true)
  @options[:log_requests] = !which
end

#rack_url_scheme(scheme = nil)

Set env['rack.url_scheme']. Only necessary if X-Forwarded-Proto is not being set by your proxy. Normal values are 'http' or 'https'.

The default is nil.

Examples:

rack_url_scheme 'https'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 546

def rack_url_scheme(scheme=nil)
  @options[:rack_url_scheme] = scheme
end

#rackup(path)

Load path as a rackup file.

The default is "config.ru".

Examples:

rackup '/u/apps/lolcat/config.ru'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 533

def rackup(path)
  @options[:rackup] ||= path.to_s
end

#raise_exception_on_sigterm(answer = true)

Raises a SignalException when SIGTERM is received. In environments where SIGTERM is something expected, you can suppress these with this option.

This can be useful for example in Kubernetes, where rolling restart is guaranteed usually on the infrastructure level.

The default is true.

Examples:

raise_exception_on_sigterm false

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1164

def raise_exception_on_sigterm(answer=true)
  @options[:raise_exception_on_sigterm] = answer
end

#restart_command(cmd)

Command to use to restart ::Puma. This should be just how to load ::Puma itself (i.e. ruby -Ilib bin/puma), not the arguments to ::Puma, as those are the same as the original process.

Examples:

restart_command '/u/app/lolcat/bin/restart_puma'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 467

def restart_command(cmd)
  @options[:restart_cmd] = cmd.to_s
end

#set_default_host(host)

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 153

def set_default_host(host)
  @options[:default_host] = host
end

#set_remote_address(val = :socket)

Control how the remote address of the connection is set. This is configurable because to calculate the true socket peer address a kernel syscall is required which for very fast rack handlers slows down the handling significantly.

There are 5 possible values:

  1. :socket - read the peername from the socket using the syscall. This is the normal behavior. If this fails for any reason (e.g., if the peer disconnects between the connection being accepted and the getpeername system call), Puma will return "0.0.0.0"
  2. :localhost - set the remote address to "127.0.0.1"
  3. header: <http_header>- set the remote address to the value of the provided http header. For instance: set_remote_address header: "X-Real-IP". Only the first word (as separated by spaces or comma) is used, allowing headers such as X-Forwarded-For to be used as well. If this header is absent, Puma will fall back to the behavior of :socket
  4. proxy_protocol: :v1- set the remote address to the value read from the HAproxy PROXY protocol, version 1. If the request does not have the PROXY protocol attached to it, will fall back to :socket
  5. <Any string> - this allows you to hardcode remote address to any value you wish. Because Puma never uses this field anyway, its format is entirely in your hands.

The default is :socket.

Examples:

set_remote_address :localhost
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1398

def set_remote_address(val=:socket)
  case val
  when :socket
    @options[:remote_address] = val
  when :localhost
    @options[:remote_address] = :value
    @options[:remote_address_value] = "127.0.0.1".freeze
  when String
    @options[:remote_address] = :value
    @options[:remote_address_value] = val
  when Hash
    if hdr = val[:header]
      @options[:remote_address] = :header
      @options[:remote_address_header] = "HTTP_" + hdr.upcase.tr("-", "_")
    elsif protocol_version = val[:proxy_protocol]
      @options[:remote_address] = :proxy_protocol
      protocol_version = protocol_version.downcase.to_sym
      unless [:v1].include?(protocol_version)
        raise "Invalid value for proxy_protocol - #{protocol_version.inspect}"
      end
      @options[:remote_address_proxy_protocol] = protocol_version
    else
      raise "Invalid value for set_remote_address - #{val.inspect}"
    end
  else
    raise "Invalid value for set_remote_address - #{val}"
  end
end

#shutdown_debug(val = true, on_force: false)

When a shutdown is requested, the backtraces of all the threads will be written to $stdout. This can help figure out why shutdown is hanging.

If on_force is true, the backtraces will be written only when the shutdown is forced i.e. not graceful.

The default is nil.

Examples:

shutdown_debug

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1343

def shutdown_debug(val = true, on_force: false)
  @options[:shutdown_debug] = val && on_force ? :on_force : val
end

#silence_fork_callback_warning

Disable the warning when running in single mode with a cluster-only callback hook defined.

The default is false.

Examples:

silence_fork_callback_warning
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 773

def silence_fork_callback_warning
  @options[:silence_fork_callback_warning] = true
end

#silence_single_worker_warning

Note:

Cluster mode only.

Disable warning message when running in cluster mode with a single worker.

Cluster mode has some overhead of running an additional 'control' process in order to manage the cluster. If only running a single worker it is likely not worth paying that overhead vs running in single mode with additional threads instead.

There are some scenarios where running cluster mode with a single worker may still be warranted and valid under certain deployment scenarios, see https://github.com/puma/puma/issues/2534

Moving from workers = 1 to workers = 0 will save 10-30% of memory use.

The default is false.

Examples:

silence_single_worker_warning
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 762

def silence_single_worker_warning
  @options[:silence_single_worker_warning] = true
end

#single(&block)

Note:

Single mode only.

Code to run only in single mode. Runs after all config files are loaded.

This can be called multiple times.

Examples:

single do
  silence_fork_callback_warning
end

Raises:

  • (ArgumentError)
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 789

def single(&block)
  raise ArgumentError, "A block must be provided to `single`" unless block

  @options[:single] ||= []
  @options[:single] << block
end

#ssl_bind(host, port, opts = {})

Instead of using #bind and manually constructing a URI like:

bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'

you can use this method.

When binding on localhost you don't need to specify cert and key, ::Puma will assume you are using the localhost gem and try to load the appropriate files.

When using the options hash parameter, the reuse: value is either true, which sets reuse 'on' with default values, or a hash, with :size and/or :timeout keys, each with integer values.

The cert: options hash parameter can be the path to a certificate file including all intermediate certificates in PEM format.

The cert_pem: options hash parameter can be a String containing the certificate and all intermediate certificates in PEM format.

Examples:

ssl_bind '127.0.0.1', '9292', {
  cert: path_to_cert,
  key: path_to_key,
  ssl_cipher_filter: cipher_filter, # optional
  ssl_ciphersuites: ciphersuites,   # optional
  verify_mode: verify_mode,         # default 'none'
  verification_flags: flags,        # optional, not supported by JRuby
  reuse: true                       # optional
}

Using self-signed certificate with the localhost gem:

ssl_bind '127.0.0.1', '9292'

Alternatively, you can provide cert_pem and key_pem:

ssl_bind '127.0.0.1', '9292', {
  cert_pem: File.read(path_to_cert),
  key_pem: File.read(path_to_key),
  reuse: {size: 2_000, timeout: 20} # optional
}

For JRuby, two keys are required: keystore & keystore_pass

ssl_bind '127.0.0.1', '9292', {
  keystore: path_to_keystore,
  keystore_pass: password,
  ssl_cipher_list: cipher_list,     # optional
  verify_mode: verify_mode          # default 'none'
}
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 694

def ssl_bind(host, port, opts = {})
  add_pem_values_to_options_store(opts)
  bind self.class.ssl_bind_str(host, port, opts)
end

#state_path(path)

Use path as the file to store the server info state. This is used by pumactl to query and control the server.

Examples:

state_path '/u/apps/lolcat/tmp/pids/puma.state'
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 705

def state_path(path)
  @options[:state] = path.to_s
end

#state_permission(permission)

Use permission to restrict permissions for the state file. By convention, permission is an octal number (e.g. 0640 or 0o640).

Examples:

state_permission 0600
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 715

def state_permission(permission)
  @options[:state_permission] = permission
end

#stdout_redirect(stdout = nil, stderr = nil, append = false)

Redirect STDOUT and STDERR to files specified. The append parameter specifies whether the output is appended, and defaults to false.

Examples:

stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr'
stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 569

def stdout_redirect(stdout=nil, stderr=nil, append=false)
  @options[:redirect_stdout] = stdout
  @options[:redirect_stderr] = stderr
  @options[:redirect_append] = append
end

#supported_http_methods(methods)

Note:

If the methods value is :any, no method check will be performed, similar to ::Puma v5 and earlier.

Supported http methods, which will replace Const::SUPPORTED_HTTP_METHODS. The value of :any will allow all methods, otherwise, the value must be an array of strings. Note that methods are all uppercase.

Const::SUPPORTED_HTTP_METHODS is conservative, if you want a complete set of methods, the methods defined by the IANA Method Registry are pre-defined as the constant Const::IANA_HTTP_METHODS.

Examples:

Adds 'PROPFIND' to existing supported methods

supported_http_methods(Puma::Const::SUPPORTED_HTTP_METHODS + ['PROPFIND'])

Restricts methods to the array elements

supported_http_methods %w[HEAD GET POST PUT DELETE OPTIONS PROPFIND]

Restricts methods to the methods in the IANA Registry

supported_http_methods Puma::Const::IANA_HTTP_METHODS

Allows any method

supported_http_methods :any
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1584

def supported_http_methods(methods)
  if methods == :any
    @options[:supported_http_methods] = :any
  elsif Array === methods && methods == (ary = methods.grep(String).uniq) &&
    !ary.empty?
    @options[:supported_http_methods] = ary
  else
    raise "supported_http_methods must be ':any' or a unique array of strings"
  end
end

#tag(string)

Additional text to display in process listing.

If you do not specify a tag, ::Puma will infer it. If you do not want ::Puma to add a tag, use an empty string.

The default is the current file or directory base name.

Examples:

tag 'app name'
tag ''
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1198

def tag(string)
  @options[:tag] = string.to_s
end

#threads(min, max = min)

Configure the number of threads to use to answer requests.

It can be a single fixed number, or a min and a max.

The default is taken from the PUMA_MIN_THREADS / PUMA_MAX_THREADS environment variables (or MIN_THREADS / MAX_THREADS if the PUMA_ variables are not set). If those environment variables are also unset, the default is 0, 5 in MRI or 0, 16 for other interpreters.

Examples:

threads 5
threads 0, 16
threads 5, 5
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 605

def threads(min, max = min)
  min = Integer(min)
  max = Integer(max)
  if min > max
    raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})"
  end

  if max < 1
    raise "The maximum number of threads (#{max}) must be greater than 0"
  end

  @options[:min_threads] = min
  @options[:max_threads] = max
end

#wait_for_less_busy_worker(val = 0.005)

Note:

Cluster mode with >= 2 workers only.

Note:

Interpreters with forking support only.

Maximum delay of worker accept loop.

Attempts to route traffic to less-busy workers by causing a busy worker to delay listening on the socket, allowing workers which are not processing as many requests to pick up new requests first.

The default is 0.005 seconds.

To turn off this feature, set the value to 0.

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1364

def wait_for_less_busy_worker(val=0.005)
  @options[:wait_for_less_busy_worker] = val.to_f
end

#worker_boot_timeout(timeout)

Note:

Cluster mode only.

Set the worker timeout for booting.

The default is 60 seconds.

Examples:

worker_boot_timeout 60

See Also:

  • Puma::Cluster::Worker#ping_timeout
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1255

def worker_boot_timeout(timeout)
  @options[:worker_boot_timeout] = Integer(timeout)
end

#worker_check_interval(interval)

Note:

Cluster mode only.

Set the interval for checking workers.

The default is 5 seconds.

Examples:

worker_check_interval 10

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1213

def worker_check_interval(interval)
  @options[:worker_check_interval] = Float(interval)
end

#worker_culling_strategy(strategy)

Note:

Cluster mode only.

Set the strategy for worker culling.

There are two possible values:

  1. :youngest - the youngest workers (i.e. the workers that were the most recently started) will be culled.
  2. :oldest - the oldest workers (i.e. the workers that were started the longest time ago) will be culled.

The default is :youngest.

Examples:

worker_culling_strategy :oldest

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1292

def worker_culling_strategy(strategy)
  strategy = strategy.to_sym

  if ![:youngest, :oldest].include?(strategy)
    raise "Invalid value for worker_culling_strategy - #{strategy}"
  end

  @options[:worker_culling_strategy] = strategy
end

#worker_shutdown_timeout(timeout)

Note:

Cluster mode only.

Set the timeout for worker shutdown.

The default is 30 seconds.

Examples:

worker_shutdown_timeout 90

See Also:

  • Puma::Cluster::Worker#term
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1270

def worker_shutdown_timeout(timeout)
  @options[:worker_shutdown_timeout] = Integer(timeout)
end

#worker_timeout(timeout)

Note:

Cluster mode only.

Verifies that all workers have checked in to the master process within the given timeout. If not, the worker process will be restarted. This is not a request timeout, it is to protect against a hung or dead process. Setting this value will not protect against slow requests.

This value must be greater than worker_check_interval.

The default is 60 seconds.

Examples:

worker_timeout 60

See Also:

  • Puma::Cluster::Worker#ping_timeout
[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 1233

def worker_timeout(timeout)
  timeout = Integer(timeout)
  min = @options.fetch(:worker_check_interval, Configuration::DEFAULTS[:worker_check_interval])

  if timeout <= min
    raise "The minimum worker_timeout must be greater than the worker reporting interval (#{min})"
  end

  @options[:worker_timeout] = timeout
end

#workers(count)

How many worker processes to run. Typically this is set to the number of available cores.

The default is the value of the environment variable WEB_CONCURRENCY if set, otherwise 0. Passing :auto will set the value to Concurrent.available_processor_count (requires the concurrent-ruby gem). On some platforms (e.g. under CPU quotas) this may be fractional, and ::Puma will round down. If it rounds down to 0, ::Puma will run in single mode and cluster-only hooks like #before_worker_boot will not execute. If you rely on cluster-only hooks, set an explicit worker count.

A value of 0 or nil means run in single mode.

Examples:

workers 2
workers :auto

See Also:

[ GitHub ]

  
# File 'lib/puma/dsl.rb', line 738

def workers(count)
  @options[:workers] = count.nil? ? 0 : @config.send(:parse_workers, count)
end