Nov 20, 20267 min read

How to Connect a Go App to RDS Postgres

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.

Illustration for How to Connect a Go App to RDS Postgres

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.

What Does a Basic pgx Connection to RDS Look Like?

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:

~
$ curl -o global-bundle.pem https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem$ go get github.com/jackc/pgx/v5
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.

Why Does TLS Fail Against RDS?

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:

  • The CA bundle is missing in the container. Distroless and scratch images have no RDS CA, so the file must be copied into the image at the path in sslrootcert.
  • The host is an IP or a custom DNS name. 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.
  • The instance uses a newer CA. RDS instances can use one of several certificate authorities, and the certificate rotation docs list them all; the global bundle includes every one, so prefer it over a single regional certificate.

How Should You Size the Pool?

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.

How Do You Use IAM Authentication from Go?

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.

What Network Setup Does the Connection Need?

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.

How Does Encore Connect Go to RDS?

Encore

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.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create orders-api --example=hello-world$ cd orders-api && mkdir -p orders/migrations

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 }
~/orders-api
$ encore run$ curl -X POST localhost:4000/orders -d '{"customer_id":"c-42","total_cents":1999}'$ encore db shell orders

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.

Go and RDS Checklist

  • Use pgx v5 with pgxpool, and Ping at startup.
  • Connect with sslmode=verify-full and the RDS global CA bundle in the image.
  • Connect by endpoint name so hostname verification passes.
  • Keep pool size times replicas well under max_connections.
  • Set MaxConnLifetime so connections recover after failover and rotation.
  • Use IAM tokens through BeforeConnect, or a secret, never a hardcoded password.
  • Allow port 5432 from the service's security group only.

Frequently asked questions

How do I connect Go to an RDS Postgres database?

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.

Does RDS Postgres require SSL?

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.

How do I use IAM authentication for RDS from Go?

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.

How many connections should my Go pool open to RDS?

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders