Subscribe

Running Postgres on RDS for production

The RDS settings I would put in Terraform before shorty's Postgres goes live: a private subnet group, a postgres18 parameter group, Multi-AZ, 14 days of point-in-time recovery, a read replica and IAM database auth from Go. Validated locally, nothing applied.

Running Postgres on RDS for production

My own blog runs MySQL in a Docker container on a single t3.small, with nightly dumps and EBS snapshots. That is a choice I made for cost, and for a blog it's the right one. For something like shorty, the URL shortener this tutorial series keeps building, I'd put Postgres on RDS the day it gets real users, because patching, failover and point-in-time recovery stop being my problem.

In this blog we will look at the RDS settings I'd want in Terraform before going live: the network, a parameter group, Multi-AZ against read replicas, backups and PITR, and IAM database auth from Go. Level is intermediate. You need a VPC with private subnets in two AZs (see Building a VPC by hand) and some Terraform. Be clear on one thing: I did not apply any of this. I ran terraform validate with Terraform 1.17.1 and AWS provider 6.73.0, tested the Go code offline, and checked the AWS CLI flags against aws rds ... help from CLI 2.38.6. RDS costs real money, and a Multi-AZ instance plus a replica is three servers.

A private home for the database

The database never gets a public IP. It lives in a subnet group made of private subnets, and its security group only accepts 5432 from the security group of the app.

resource "aws_db_subnet_group" "shorty" {
  name       = "shorty-db"
  subnet_ids = var.private_subnet_ids
}

resource "aws_security_group" "db" {
  name        = "shorty-db"
  description = "Postgres for shorty, only from the app"
  vpc_id      = var.vpc_id
}

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = var.app_security_group_id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
  description                  = "Postgres from the app"
}

Referencing the app's security group instead of a CIDR means a new task or instance in that group gets access, and nothing else in the VPC does. I used the separate aws_vpc_security_group_ingress_rule resource because inline ingress blocks and separate rules fight each other in Terraform if you ever mix them.

The parameter group

Never run production on the default parameter group. The thing is, you can't change it, and the first time you need to change one setting you'll have to swap the group and maybe reboot.

resource "aws_db_parameter_group" "shorty" {
  name   = "shorty-postgres18"
  family = "postgres18"

  parameter {
    name  = "rds.force_ssl"
    value = "1"
  }
  parameter {
    name  = "log_min_duration_statement"
    value = "500"
  }
  parameter {
    name  = "log_lock_waits"
    value = "1"
  }
  parameter {
    name  = "idle_in_transaction_session_timeout"
    value = "60000"
  }
  parameter {
    name         = "shared_preload_libraries"
    value        = "pg_stat_statements,auto_explain"
    apply_method = "pending-reboot"
  }
  parameter {
    name  = "auto_explain.log_min_duration"
    value = "2000"
  }

  lifecycle {
    create_before_destroy = true
  }
}

rds.force_ssl is already on by default since Postgres 15 on RDS. I still write it down so nobody turns it off by accident. Slow statements over 500 ms go to the log, and the two preloaded libraries are what Finding slow queries with pg_stat_statements and auto_explain uses. shared_preload_libraries is a static parameter, so it only takes effect after a reboot, and Terraform wants apply_method = "pending-reboot" for it or the apply fails.

idle_in_transaction_session_timeout kills sessions that opened a transaction and went quiet for a minute. Those hold locks and block vacuum. It's an easy bug to write in Go, a forgotten tx.Rollback() on one error path is all it takes.

The instance

resource "aws_db_instance" "shorty" {
  identifier     = "shorty-prod"
  engine         = "postgres"
  engine_version = "18"
  instance_class = var.instance_class

  allocated_storage     = 50
  max_allocated_storage = 200
  storage_type          = "gp3"
  storage_encrypted     = true

  db_name                             = "shorty"
  username                            = "shorty_admin"
  manage_master_user_password         = true
  iam_database_authentication_enabled = true

  db_subnet_group_name   = aws_db_subnet_group.shorty.name
  vpc_security_group_ids = [aws_security_group.db.id]
  publicly_accessible    = false
  multi_az               = true
  parameter_group_name   = aws_db_parameter_group.shorty.name
  ca_cert_identifier     = "rds-ca-rsa2048-g1"

  backup_retention_period  = 14
  backup_window            = "19:00-19:30"
  maintenance_window       = "sun:20:00-sun:21:00"
  copy_tags_to_snapshot    = true
  delete_automated_backups = false

  auto_minor_version_upgrade = true
  apply_immediately          = false

  database_insights_mode          = "standard"
  enabled_cloudwatch_logs_exports = ["postgresql"]

  deletion_protection       = true
  skip_final_snapshot       = false
  final_snapshot_identifier = "shorty-prod-final"
}

A few of these deserve a line each.

engine_version = "18" gives you the latest 18.x minor at creation time, and auto_minor_version_upgrade keeps moving it inside the maintenance window. The newest RDS minor I could find announced was 18.6 in August. Run aws rds describe-db-engine-versions --engine postgres --query 'DBEngineVersions[].EngineVersion' in your region before you pick.

manage_master_user_password = true makes RDS create the admin password in Secrets Manager and rotate it. No password in your .tfvars, and none in the state file. I actually care about that a lot, the Terraform for my blog was written so that no secret ever lands in state, and this is the RDS way of doing the same.

gp3 with max_allocated_storage lets the disk grow by itself when it fills up. It doesn't shrink back, so don't set the ceiling higher than you'd be willing to pay for.

The windows are UTC. 19:00 is half past midnight in India, when shorty would be quiet.

database_insights_mode = "standard" is there because Performance Insights as a console is gone, AWS moved it into CloudWatch Database Insights with an end-of-life date of 31 July 2026. Standard mode is the free one.

And the last three lines stop a terraform destroy or a renamed resource from eating the database. With deletion_protection the API refuses to delete it at all until you flip it off in a separate apply.

Multi-AZ or a read replica

These two get mixed up all the time, basically they solve different problems.

Multi-AZ (the instance kind, as above) keeps a standby in another AZ and writes to it synchronously. You can't read from the standby. If the primary or its AZ dies, RDS flips the DNS name to the standby, usually in a minute or two, and your app reconnects to the same endpoint. That's for availability.

A read replica copies asynchronously, has its own endpoint, and you can send reads to it. It can lag behind the primary, so a user who just created a link might not see it on the replica yet. That's for scaling reads. For shorty, where every redirect is a read of one row by its code, a replica would take load off the primary nicely. Whether that lag is OK is the read-your-writes question from Consistency explained with examples.

resource "aws_db_instance" "shorty_replica" {
  identifier          = "shorty-prod-replica"
  replicate_source_db = aws_db_instance.shorty.identifier
  instance_class      = var.instance_class
  storage_encrypted   = true

  vpc_security_group_ids = [aws_security_group.db.id]
  parameter_group_name   = aws_db_parameter_group.shorty.name
  publicly_accessible    = false
  multi_az               = false

  backup_retention_period = 0
  skip_final_snapshot     = true
}

There is also a third option, a Multi-AZ DB cluster with two readable standbys. It costs more again. I'd start with Multi-AZ instance only and add a replica when the numbers say so.

Backups and point-in-time recovery

With backup_retention_period = 14, RDS takes a daily snapshot and keeps the transaction logs, so you can restore to any second in the last 14 days. It's the same idea as WAL archiving with pgBackRest, which I set up by hand in Backups and point-in-time recovery for self-hosted Postgres with pgBackRest, except AWS runs it.

The part people don't expect: a restore never goes back into the same instance. It creates a new one only. You look at the data there and then either copy rows back or move the app over.

aws rds describe-db-instances --db-instance-identifier shorty-prod \
  --query 'DBInstances[0].LatestRestorableTime'

aws rds restore-db-instance-to-point-in-time \
  --source-db-instance-identifier shorty-prod \
  --target-db-instance-identifier shorty-restore-1405 \
  --restore-time 2026-12-08T14:04:00Z \
  --db-subnet-group-name shorty-db \
  --vpc-security-group-ids sg-0123456789abcdef0 \
  --db-parameter-group-name shorty-postgres18 \
  --no-multi-az --no-publicly-accessible

Pass the subnet group, security group and parameter group yourself. If you leave them out the restored instance gets defaults, including the VPC's default security group, and then the app can't reach it and you lose ten minutes wondering why. LatestRestorableTime is usually about five minutes behind now, that's how often RDS ships the logs.

IAM database auth from Go

With IAM auth the app has no database password at all. It signs a short-lived token with its role and sends that as the password. First, inside the database, as the admin user:

CREATE USER shorty_app;
GRANT rds_iam TO shorty_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO shorty_app;

Then the role of the app needs rds-db:connect on that user.

data "aws_iam_policy_document" "rds_connect" {
  statement {
    actions = ["rds-db:connect"]
    resources = [
      "arn:aws:rds-db:${var.region}:${data.aws_caller_identity.current.account_id}:dbuser:${aws_db_instance.shorty.resource_id}/shorty_app",
    ]
  }
}

Note the resource_id. It's the db-ABCD... ID, not the shorty-prod name, and using the name is the classic mistake here. The policy looks fine and every login fails with PAM authentication failed.

On the Go side, pgx has a BeforeConnect hook that runs for every new connection, which is exactly where a fresh token belongs. This uses feature/rds/auth v1.7.12 and pgx v5.13.0.

package rdsdb

import (
    "context"
    "fmt"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/feature/rds/auth"
    "github.com/jackc/pgx/v5"
    "github.com/jackc/pgx/v5/pgxpool"
)

// Config builds a pool config whose every new connection gets a fresh IAM
// token. user is a database role that was granted rds_iam; caFile is the RDS
// CA bundle (global-bundle.pem).
func Config(awsCfg aws.Config, host, user, dbname, caFile string) (*pgxpool.Config, error) {
    dsn := fmt.Sprintf("host=%s port=5432 user=%s dbname=%s sslmode=verify-full sslrootcert=%s",
        host, user, dbname, caFile)
    cfg, err := pgxpool.ParseConfig(dsn)
    if err != nil {
        return nil, err
    }
    cfg.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
        token, err := auth.BuildAuthToken(ctx, fmt.Sprintf("%s:5432", host),
            awsCfg.Region, user, awsCfg.Credentials)
        if err != nil {
            return fmt.Errorf("build rds auth token: %w", err)
        }
        cc.Password = token
        return nil
    }
    return cfg, nil
}

func Open(ctx context.Context, awsCfg aws.Config, host, user, dbname, caFile string) (*pgxpool.Pool, error) {
    cfg, err := Config(awsCfg, host, user, dbname, caFile)
    if err != nil {
        return nil, err
    }
    return pgxpool.NewWithConfig(ctx, cfg)
}

The token is just a presigned URL built locally, no AWS call involved, so I could test it without an account. I called BeforeConnect with fake static credentials and checked the result.

token: shorty-prod.abc123xyz.ap-south-1.rds.amazonaws.com:5432?Action=connect&DBUser=shorty_app&X...
--- PASS: TestBeforeConnectSetsToken (0.00s)

The token is valid for 15 minutes (X-Amz-Expires=900), but it only matters at login. A connection that is already open stays open after the token expires. TLS is required for IAM auth, and verify-full needs the RDS CA bundle from https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem baked into the image. My old post Golang: Connecting to postgres using ssl goes through the certificate part.

AWS recommends IAM auth when you open fewer than about 200 new connections per second. With a pool that is never a problem, and if you are anywhere near that, you want PgBouncer or RDS Proxy anyway.

Getting a psql prompt

The database is private, so how do you run that CREATE USER? I don't open a bastion with SSH. I use the same SSM setup as my Docker host (Running a Docker host on EC2 with SSM instead of SSH) and forward a port through any instance in the VPC.

aws ssm start-session --target i-0123456789abcdef0 \
  --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters '{"host":["shorty-prod.abc123xyz.ap-south-1.rds.amazonaws.com"],"portNumber":["5432"],"localPortNumber":["15432"]}'

Then in another terminal, psql "host=localhost port=15432 user=shorty_admin dbname=shorty sslmode=require", with the admin password from the Secrets Manager secret that manage_master_user_password created. The instance needs to be in a security group the database allows, so for this one-off I'd put a temporary rule in and remove it again after.

Before the first real apply, I'd read the plan twice. Mainly for multi_az and the instance class, those two decide most of the bill.