achenet
sharing postgrex link between different handlers/keeping postgrex link as state using plug
Hello,
I’m building a small REST API using Bandit and Plug, with Postgrex to talk to the database.
I currently have my code set up so each handler will call Postgrex.start_link, get a pid, and then call Postgrex.query! with that pid to interact with the database.
I have two questions:
Is it possible to have just one postgrex link shared between all handlers? Like some sort of shared state that the handlers can use to all use the same pid to interact with the database?
If so, is it better to have one shared pid for all handlers, or create a new link to get a new pid with each request?
First Post!
ruslandoga
Postgrex.start_link starts a pool of connections that can be named and safely accessed from any process.
iex(1)> Mix.install [:postgrex]
:ok
iex(2)> Postgrex.start_link(pool_size: 5, name: MyPool, database: "example", username: "postgres", password: "postgres", hostname: "localhost", port: 5432)
{:ok, #PID<0.202.0>}
iex(3)> Postgrex.query!(MyPool, "select 1", [], [])
%Postgrex.Result{
command: :select,
columns: ["?column?"],
rows: [[1]],
num_rows: 1,
connection_id: 55,
messages: []
}
If so, is it better to have one shared
pidfor all handlers, or create a new link to get a newpidwith each request?
Depends on your use case. But usually, for small requests that happen often, it’s more efficient to reuse an existing pool of connections.








