Connecting Go to Amazon RDS for PostgreSQL with pgx: the connection string, TLS with the RDS certificate bundle, pool sizing against max_connections, IAM database authentication tokens, network setup, and an approach where the database is provisioned from the Go code.

Connecting Go to Amazon RDS for PostgreSQL takes a pgx pool and a connection string, and it works on the first try from an EC2 box in the same subnet.
Problems arrive later, with TLS errors under sslmode=verify-full, too many connections after a scale-out, and a password the security team wants replaced with IAM tokens. This guide covers each for a Go service, then a setup where the database is declared in the Go code.
pgx v5 is the default Postgres driver for Go, and pgxpool gives a concurrency-safe pool. Download the RDS global certificate bundle next to the binary, or bake it into the container image, so the client can verify the server:
package store
import (
"context"
"fmt"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func Open(ctx context.Context) (*pgxpool.Pool, error) {
dsn := fmt.Sprintf(
"host=%s port=5432 dbname=%s user=%s password=%s sslmode=verify-full sslrootcert=/etc/ssl/rds/global-bundle.pem",
os.Getenv("DB_HOST"), os.Getenv("DB_NAME"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"),
)
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = 10
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.MaxConnLifetime = 30 * time.Minute
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, err
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, err
}
return pool, nil
}
Ping at startup turns a wrong security group into a clear error at boot instead of a timeout on the first request, and MaxConnLifetime recycles connections so they move to a new primary after a failover or pick up a rotated password.
The RDS PostgreSQL SSL guide notes that rds.force_ssl defaults to on for PostgreSQL 15 and later, so a client using sslmode=disable is rejected outright. sslmode=require encrypts but does not check the certificate, which is why it appears to work and leaves the connection open to interception. With verify-full, the usual failures are:
sslrootcert.verify-full checks the hostname against the certificate, so connect with the RDS endpoint name, or with an RDS Proxy endpoint, which has its own certificate.RDS sets max_connections from instance memory, so a small instance allows far fewer connections than people expect, and each one costs server memory. pgxpool defaults MaxConns to the larger of 4 and the CPU count, per the pgxpool docs, and that number applies per process. Multiply it by replicas, services and migration jobs, keep the total well under max_connections minus a margin for admin sessions, and put RDS Proxy or PgBouncer in front once autoscaling makes the replica count unpredictable.
IAM authentication replaces the password with a token signed by the app's IAM role, valid for 15 minutes. The database user needs the rds_iam role, the IAM policy needs rds-db:connect on arn:aws:rds-db:REGION:ACCOUNT:dbuser:DBI_RESOURCE_ID/app_user, and the pool generates a fresh token for each new connection, following the Go example in the RDS docs:
package store
import (
"context"
"os"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/rds/auth"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func OpenWithIAM(ctx context.Context) (*pgxpool.Pool, error) {
awsCfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return nil, err
}
host, region := os.Getenv("DB_HOST"), awsCfg.Region
cfg, err := pgxpool.ParseConfig("host=" + host + " port=5432 dbname=app user=app_user " +
"sslmode=verify-full sslrootcert=/etc/ssl/rds/global-bundle.pem")
if err != nil {
return nil, err
}
cfg.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
token, err := auth.BuildAuthToken(ctx, host+":5432", region, "app_user", awsCfg.Credentials)
if err != nil {
return err
}
cc.Password = token
return nil
}
return pgxpool.NewWithConfig(ctx, cfg)
}
Tokens are only checked when a connection opens, so existing connections live past the 15 minutes, and IAM authentication has a connection rate limit, which is one more reason to keep pools long-lived rather than reconnecting per request.
The database belongs in private subnets with no public access, and its security group should allow port 5432 only from the security group of the Go service, not from a CIDR range. A Go service on Fargate or Lambda in the same VPC then connects by endpoint name, while developers reach it through a bastion, SSM port forwarding or a separate development database. Most "connection timed out" errors from Go are this layer, not the driver.
Encore brings infrastructure from code, so the database is declared in Go next to the service that queries it. When you deploy to AWS, Encore provisions RDS for PostgreSQL in your own account with the networking set up, and Encore provisions an IAM role for the service. The service code is the same as on your laptop.
Run in your terminal to get started locally.
The schema is a plain SQL migration that Encore applies in order:
-- orders/migrations/1_orders.up.sql
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id TEXT NOT NULL,
total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX orders_by_customer ON orders (customer_id, created_at DESC);
The service declares the database and queries it with the same placeholders you would use with pgx:
// orders/orders.go
package orders
import (
"context"
"errors"
"time"
"encore.dev/beta/errs"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{
Migrations: "./migrations",
})
type CreateParams struct {
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
}
type Order struct {
ID int64 `json:"id"`
CustomerID string `json:"customer_id"`
TotalCents int64 `json:"total_cents"`
CreatedAt time.Time `json:"created_at"`
}
//encore:api public method=POST path=/orders
func Create(ctx context.Context, p *CreateParams) (*Order, error) {
if p.CustomerID == "" || p.TotalCents < 0 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "customer_id and a non-negative total are required"}
}
o := &Order{CustomerID: p.CustomerID, TotalCents: p.TotalCents}
err := db.QueryRow(ctx, `
INSERT INTO orders (customer_id, total_cents) VALUES ($1, $2)
RETURNING id, created_at`, p.CustomerID, p.TotalCents).Scan(&o.ID, &o.CreatedAt)
return o, err
}
//encore:api public method=GET path=/orders/:id
func Get(ctx context.Context, id int64) (*Order, error) {
o := &Order{ID: id}
err := db.QueryRow(ctx, `
SELECT customer_id, total_cents, created_at FROM orders WHERE id = $1`, id,
).Scan(&o.CustomerID, &o.TotalCents, &o.CreatedAt)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.NotFound, Message: "order not found"}
}
return o, err
}
encore run starts Postgres locally and applies the migration, and encore db shell opens psql against it. On deploy to your AWS account, the same db handle connects to RDS, Encore provisions an IAM role for the service, and the AWS infrastructure docs describe the database roles it creates so each service only reaches its own databases. If the database already exists, it can be imported rather than recreated.
With the database declared in the Go code, an agent adding a refunds table writes the migration and the endpoint in one change and tests both against local Postgres, with no connection string or password to look up.
Best fit: Go teams on AWS who want RDS Postgres in their own account and the same database code running locally.
pgxpool, and Ping at startup.sslmode=verify-full and the RDS global CA bundle in the image.max_connections.MaxConnLifetime so connections recover after failover and rotation.BeforeConnect, or a secret, never a hardcoded password.Use pgx v5 and create a pgxpool.Pool from a connection string with the RDS endpoint, port 5432, the database name, a user and sslmode=verify-full with sslrootcert pointing at the RDS global certificate bundle. Run the Go service in the same VPC, and allow its security group on port 5432 in the database's security group.
Yes. For RDS for PostgreSQL 15 and later, the rds.force_ssl parameter defaults to 1, so non-SSL connections are rejected. Use sslmode=verify-full with the RDS certificate bundle so the client also checks the server's identity.
Enable IAM authentication on the instance, grant the rds_iam role to the database user, allow rds-db:connect for that user in the app's IAM policy, and generate a token with auth.BuildAuthToken from aws-sdk-go-v2/feature/rds/auth. Tokens last 15 minutes, so generate a fresh one for each new connection in pgxpool's BeforeConnect hook.
Size it so that every instance of every service together stays well below the database's max_connections, which RDS derives from instance memory. pgxpool defaults to the larger of 4 and the number of CPUs, which is reasonable per instance, but ten replicas of three services multiply it quickly.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.