postgres.go49 lines, 1.6 KB
| 1 | // Package postgres connects services to PostgreSQL through a pgx connection pool. |
| 2 | package postgres |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/jackc/pgx/v5/pgxpool" |
| 10 | ) |
| 11 | |
| 12 | // NewPool creates a connection pool of up to maxConns connections to the |
| 13 | // database at dsn, and checks that the database is reachable before returning it. |
| 14 | func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) { |
| 15 | cfg, err := pgxpool.ParseConfig(dsn) |
| 16 | if err != nil { |
| 17 | return nil, fmt.Errorf("postgres: parse dsn: %w", err) |
| 18 | } |
| 19 | |
| 20 | // Pool sizing: a few warm connections, and a hard cap well below |
| 21 | // Postgres's max_connections, so many replicas can share one server. |
| 22 | cfg.MinConns = min(2, maxConns) |
| 23 | cfg.MaxConns = maxConns |
| 24 | |
| 25 | // Recycle connections now and then, so load rebalances after a failover. |
| 26 | // The jitter stops every connection from reconnecting at the same moment. |
| 27 | cfg.MaxConnLifetime = time.Hour |
| 28 | cfg.MaxConnLifetimeJitter = 5 * time.Minute |
| 29 | cfg.MaxConnIdleTime = 15 * time.Minute |
| 30 | cfg.HealthCheckPeriod = 30 * time.Second |
| 31 | cfg.ConnConfig.ConnectTimeout = 5 * time.Second |
| 32 | // A span for every query, in the trace that ran it. |
| 33 | cfg.ConnConfig.Tracer = queryTracer{} |
| 34 | |
| 35 | pool, err := pgxpool.NewWithConfig(ctx, cfg) |
| 36 | if err != nil { |
| 37 | return nil, fmt.Errorf("postgres: create pool: %w", err) |
| 38 | } |
| 39 | |
| 40 | // The pool connects lazily. Ping now, so a bad DSN or a database that is |
| 41 | // down fails at startup, instead of on the first request. |
| 42 | pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 43 | defer cancel() |
| 44 | if err := pool.Ping(pingCtx); err != nil { |
| 45 | pool.Close() |
| 46 | return nil, fmt.Errorf("postgres: ping: %w", err) |
| 47 | } |
| 48 | return pool, nil |
| 49 | } |