feat: implementing pgbouncer configuration to allow for pooled connections

This commit is contained in:
Ceferino Patino 2026-04-02 22:06:01 -05:00
commit f225b43aa4
Signed by: c4patino
SSH key fingerprint: SHA256:Wu+cU1t+7zVT9wzew/4meNmeulo66NzMqc22MdDBgXI
3 changed files with 61 additions and 16 deletions

View file

@ -5,13 +5,14 @@
pkgs,
...
}: let
inherit (lib) types mkIf mkOption concatStringsSep hasAttr getAttr;
inherit (lib) types mkIf mkOption concatStringsSep hasAttr getAttr genAttrs;
inherit (lib.${namespace}) getAttrByNamespace mkOptionsWithNamespace;
inherit (config.networking) hostName;
base = "${namespace}.services.storage.postgresql";
cfg = getAttrByNamespace config base;
port = 5600;
port = 5601;
pgbouncerPort = 5600;
in {
options = with types;
mkOptionsWithNamespace base {
@ -37,11 +38,14 @@ in {
permissionEntries =
cfg.databases
|> getAttr hostName
|> map (service: "host ${service} ${service} 0.0.0.0/0 md5")
|> concatStringsSep "\n";
|> map (service: ''
host ${service} ${service} 127.0.0.1/32 scram-sha-256
'')
|> concatStringsSep "";
in ''
# TYPE DATABASE USER ADDRESS METHOD
local all all trust
# TYPE DATABASE USER ADDRESS METHOD
local all all trust
host all pgbouncer_auth 127.0.0.1/32 scram-sha-256
${permissionEntries}
'';
@ -58,20 +62,58 @@ in {
postgresqlBackup = {
enable = true;
databases = [
"forgejo"
"grafana"
"vaultwarden"
"terraform"
];
databases =
cfg.databases
|> getAttr hostName;
compression = "zstd";
compressionLevel = 4;
startAt = "*-*-* 23:00:00";
};
pgbouncer = {
enable = true;
settings = {
pgbouncer = {
listen_addr = "0.0.0.0";
listen_port = pgbouncerPort;
default_pool_size = 10;
max_client_conn = 500;
pool_mode = "transaction";
stats_users = "pgbouncer_auth";
auth_file = config.sops.secrets."postgresql/pgbouncer/auth_file".path;
auth_type = "scram-sha-256";
auth_user = "pgbouncer_auth";
auth_dbname = "postgres";
auth_query = "SELECT uname, phash FROM pgbouncer_lookup($1)";
ignore_startup_parameters =
["extra_float_digits"]
|> concatStringsSep "\n";
};
databases =
cfg.databases
|> getAttr hostName
|> (dbs: dbs ++ ["postgres"])
|> (dbs: genAttrs dbs (db: "host=127.0.0.1 port=${toString port} dbname=${db}"));
};
};
};
networking.firewall.allowedTCPPorts = [port];
sops.secrets = let
inherit (config.users.users) pgbouncer;
in {
"postgresql/pgbouncer/auth_file" = {
owner = pgbouncer.name;
group = pgbouncer.group;
};
};
${namespace}.services.storage.impermanence.folders = ["/var/lib/postgresql"];
${namespace}.services.storage.impermanence.folders = [
"/var/lib/postgresql"
"/var/lib/pgbouncer"
];
};
}

Binary file not shown.

File diff suppressed because one or more lines are too long