liveBook · Manning

Poolboy

As explained in Elixir in Action, Third Edition

Poolboy is an Erlang/Elixir library that manages pools of worker processes through checkout and checkin operations.

Poolboy is an Erlang library that provides a mature process-pool implementation for Elixir systems. Add it through Mix, fetch it with Hex, and commit mix.lock for reproducible builds. section 11.2.1

Poolboy coordinates workers through a managed lifecycle:

  • Start a pool manager under the supervision tree with a configured worker module and pool size. section 11.2.2
  • Check out a worker, perform the operation, and check it in when finished; callers wait when every worker is busy. section 11.2.2
  • Recover from failures by returning workers after crashed clients and replacing crashed workers. section 11.2.2

Database operations through a pool

Define a child specification with a locally registered pool, three Todo.DatabaseWorker processes, and the database folder as worker arguments. Wrap store and get operations in :poolboy.transaction, which supplies a worker PID to the operation function. section 11.2.2

Listing 11.5 Starting a Poolboy-powered pool (todo_poolboy/lib/todo/database.ex)
defmodule Todo.Database do
  @db_folder "./persist"
 
  def child_spec(_) do
    File.mkdir_p!(@db_folder)
 
    :poolboy.child_spec(
      __MODULE__,                             #1
      [                                       #2
        name: {:local, __MODULE__},           #2
        worker_module: Todo.DatabaseWorker,   #2
        size: 3                               #2
      ],                                      #2
 
      [@db_folder]                            #3
    )
  end
 
  ...
end

Inspect the child specification that registers the pool, selects its worker module, sets its size, and supplies startup arguments. section 11.2.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains configuration, checkout and checkin behavior, transactional use, and crash recovery without detailing Poolboy internals.
Examples
Demonstrates a Todo database pool configured with three workers and transaction-wrapped store and get operations.
What it assumes
Assumes familiarity with Elixir applications, Mix projects, supervision trees, and GenServer-based workers.
What you can do after
Operate a supervised worker pool through child specifications and :poolboy.transaction calls.
How it connects
Connects process pools with supervision trees, GenServer workers, monitors, links, Mix, Hex, and Erlang libraries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.