Nitish
Nitish

Reputation: 13

create a default number of db connections at startup golang

I want some idle db connections to always there on application startup.

I can only see MaxIdleConns and MaxOpenConns in Golang. I don't see any setMinIdle func. Help is appreciated.

Upvotes: 0

Views: 1176

Answers (1)

Vlad Bogomolov
Vlad Bogomolov

Reputation: 358

To target the main part of your question, you could iterate a decided number of times and make a parallel request to your database before marking your app as started. (For instance for k8s readiness probe).

In general, when selecting a configuration for the connection pool configuration, there are few things to consider:

  1. By default, no limit of open connections is present, thus if some bug occurs or an unexpected high influx of incoming requests, it may be impactful for DB. That's why one should set SetMaxOpenConns.
  2. If connections will live forever, it's also not the very best situation. As they take memory and DB resources. So - set SetMaxIdleConns, remember, it's default value is 2.

The common practice for a production-grade setup is to set the DB connection pool to have a limit on MaxOpenConns, which depends on expected requests per second, number of workers and configuration of the database. As for MaxIdleConns — it should be set to a fraction of MaxOpenConns, consider set your expectation on what's the dispersion of simultaneous requests. Like 25 % or 50% of MaxOpenConns.

Upvotes: 2

Related Questions