Ecto checkout connection

Hi,

I have a long running GenServer that makes frequent calls using Ecto.

Now I know you can use Repo.checkout/2 to checkout a connection for the lifetime of a function, but can I do the same for my GenServer process? It seems inefficient to keep re-creating a connection that I know it’s going to be used frequently by a single process.

Or am I missing something?

Thanks

Inefficient according to which criteria?

Your GenServer probably accesses the DB in response to messages send to it. How do you know these messages will be sent back-to-back in a quick succession, forever? IMO you don’t know that so it is much safer to have Repo.checkout wrap the part of the DB-accessing code inside your handle_call function body.

Ecto’s underlying pool manager poolboy is quite fast and efficient and can quickly check-out / check-in the underlying resource (in this case DB connections). Don’t concern yourself with that.

Finally, if you expect bursty workloads where you wouldn’t need GenServer but more likely just directly spawn a Task and such then yes, I’d give unfettered access to that if I expect it will end in the next, say, 3 to 15 seconds (those values depend on your pool config e.g. queue_target and the various timeouts).

Checkout doesn’t create a connection. It checks out one from a pool, which keeps a fixed amount of connections active all the time.

Ecto doesn’t use poolboy anymore. DBConnection implements its own pooling: db_connection/connection_pool.ex at master · elixir-ecto/db_connection · GitHub

2 Likes

Ah, I stand corrected then. Been a while since I was checking the source.

Thanks, that makes sense