How IAM database authentication works on Amazon RDS for PostgreSQL, how to enable it, create the database user and IAM policy, generate tokens with the AWS CLI, Go and Node, the limits to plan for, and how Encore handles database credentials on AWS.

RDS IAM database authentication lets an application log in to Postgres with a 15 minute token signed by its AWS role instead of a password stored somewhere, which avoids keeping a database password in a .env file. The trade is more setup in three places, the instance, the database and IAM, each of which can fail with the same unhelpful PAM authentication failed error.
This guide walks through each step for RDS for PostgreSQL, with token generation from the AWS CLI, Go and Node, the limits that matter in production, and how Encore handles database credentials for apps it deploys to AWS.
Figures and limits are from the IAM database authentication overview.
The token is a presigned request for the rds-db:connect action, built with Signature Version 4 from the caller's AWS credentials, the database hostname, port, region and user name. Generating it is local cryptography, with no call to AWS, which is why CloudTrail has nothing to log. The client sends the token as the password, RDS verifies the signature and checks that the signing identity is allowed to connect as that database user, and the session is then an ordinary Postgres session: the token does not affect it after login, so a pool connection opened at 09:00 keeps working at 17:00.
Application code therefore has to generate a token per new connection rather than once at startup, since a pool that opens a connection 20 minutes after boot needs a fresh one, and when the signing credentials are temporary, as they are for ECS task roles and Lambda, they must still be valid at the moment of connecting.
New instances take --enable-iam-database-authentication on create-db-instance, and in Terraform the setting is iam_database_authentication_enabled = true on aws_db_instance. Users without rds_iam keep logging in with passwords after the change, so you can move one user at a time, and the enabling guide covers the console path.
Connect as the master user and create a login role for the application, grant it rds_iam, and give it the privileges it needs:
-- Run as the master user, connected to the orders database.
CREATE USER orders_app;
GRANT rds_iam TO orders_app;
GRANT CONNECT ON DATABASE orders TO orders_app;
GRANT USAGE ON SCHEMA public TO orders_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO orders_app;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO orders_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO orders_app;
On PostgreSQL a user with rds_iam can only log in with a token, even if it also has a password, so never grant it to the master user: you would lock yourself out of password logins for the account that fixes things. The user name in the database and in the IAM policy must match exactly, including case.
The IAM policy names the database user by the instance's resource ID, the db-... value from step 1, not by the instance identifier. For Aurora, use the cluster resource ID (cluster-...), and for connections through RDS Proxy, the proxy's prx-... ID, as described in the IAM policy guide. In Terraform, for an ECS task role:
# iam_db_auth.tf
variable "db_instance_id" { type = string }
variable "task_role_name" { type = string }
data "aws_db_instance" "orders" {
db_instance_identifier = var.db_instance_id
}
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
# Turn on IAM database authentication on the instance itself
# (in the aws_db_instance resource that manages it):
# iam_database_authentication_enabled = true
resource "aws_iam_role_policy" "orders_db_connect" {
name = "orders-db-connect"
role = var.task_role_name
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "rds-db:connect"
# Instance resource ID (db-...), not the instance name.
Resource = "arn:aws:rds-db:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:dbuser:${data.aws_db_instance.orders.resource_id}/orders_app"
}]
})
}
The ARN takes a wildcard in the user part (.../db-ABCDEFGHIJKL01234/*), but naming the user keeps one role from logging in as another. The global condition keys aws:SourceIp, aws:SourceVpc and aws:SourceVpce are not supported for rds-db:connect, so network restrictions belong in security groups.
From a machine that can reach the instance, with credentials for an identity that has the policy:
The hostname passed to generate-db-auth-token must be the RDS endpoint the client connects to; a custom Route 53 name pointing at the instance produces a token RDS rejects.
The AWS SDK for Go v2 signs tokens with auth.BuildAuthToken from feature/rds/auth. With pgx, set the token in BeforeConnect, which the pool calls before every new connection:
// main.go
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"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 newPool(ctx context.Context) (*pgxpool.Pool, error) {
host := os.Getenv("DB_HOST") // orders-db.abc123.us-east-1.rds.amazonaws.com
user := os.Getenv("DB_USER") // orders_app, granted rds_iam
endpoint := host + ":5432"
cfg, err := config.LoadDefaultConfig(ctx) // ECS task role, Lambda role, or local profile
if err != nil {
return nil, err
}
// No password in the DSN. verify-full checks the server certificate against the
// RDS CA bundle, which IAM authentication requires anyway.
dsn := fmt.Sprintf(
"host=%s port=5432 dbname=orders user=%s sslmode=verify-full sslrootcert=/etc/ssl/rds/global-bundle.pem",
host, user,
)
pcfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
pcfg.MaxConns = 10
// Tokens are valid for 15 minutes but only checked at login, so
// sign a fresh one for every new connection.
pcfg.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
token, err := auth.BuildAuthToken(ctx, endpoint, cfg.Region, user, cfg.Credentials)
if err != nil {
return fmt.Errorf("build rds auth token: %w", err)
}
cc.Password = token
return nil
}
return pgxpool.NewWithConfig(ctx, pcfg)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pool, err := newPool(ctx)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
var who string
if err := pool.QueryRow(ctx, "SELECT current_user").Scan(&who); err != nil {
log.Fatal(err)
}
log.Printf("connected as %s", who)
}
Ship global-bundle.pem in the image (copy it in at build time rather than downloading on start), and keep sslmode=verify-full so the token is only sent to a server whose certificate checks out. The AWS samples in the Go connection guide build one token for a single sql.Open, which works for a script but fails for a pool once the first token is older than 15 minutes.
The JavaScript SDK has Signer in @aws-sdk/rds-signer, and pg accepts a function for password that it calls for each new connection:
// db.ts
import { readFileSync } from "node:fs";
import { Signer } from "@aws-sdk/rds-signer";
import pg from "pg";
const host = process.env.DB_HOST!; // orders-db.abc123.us-east-1.rds.amazonaws.com
const user = process.env.DB_USER!; // orders_app, granted rds_iam
// Uses the default credential chain: ECS task role, Lambda role, or a local profile.
const signer = new Signer({ hostname: host, port: 5432, username: user });
export const pool = new pg.Pool({
host,
port: 5432,
database: "orders",
user,
// Called for every new connection, so each login gets a fresh token.
password: () => signer.getAuthToken(),
ssl: {
ca: readFileSync("/etc/ssl/rds/global-bundle.pem", "utf8"),
rejectUnauthorized: true,
},
max: 10,
});
export async function whoami(): Promise<string> {
const { rows } = await pool.query<{ current_user: string }>("SELECT current_user");
return rows[0].current_user;
}
The same pattern works in Lambda, with max set to 1 and the pool created outside the handler. For a Lambda fleet large enough to strain max_connections, put RDS Proxy in front and sign tokens for the proxy endpoint instead.
IAM authentication needs 300 to 1000 MiB of extra memory on the instance, which matters on burstable db.t4g.micro and db.t4g.small instances that are already short of memory. Tokens are usually about 1 KB and can be larger with many IAM tags, so tools and drivers that truncate long passwords fail in confusing ways. IAM and Kerberos cannot both be enabled for PostgreSQL, and IAM authentication is not available on RDS on Outposts.
Encore takes infrastructure from code a step further than declaring the database: the Postgres roles and credentials are created for you too. A SQLDatabase declared in a TypeScript or Go service becomes a database on an RDS or Aurora server in your AWS account, and the AWS infrastructure docs describe the role hierarchy Encore sets up on it, a reader, writer and admin role per database, a role per service, and a login role per container. The docs describe that role hierarchy and do not describe IAM database authentication on AWS. The comparison here is with what the manual setup above is for: no shared password in config files, and each workload limited to what it needs.
Run in your terminal to get started locally.
// orders/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("orders");
// orders/orders.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
// On AWS this is a database on the environment's RDS or Aurora server.
// Encore creates the Postgres roles and passes this container its own credentials.
const db = new SQLDatabase("orders", { migrations: "./migrations" });
interface Order {
id: number;
status: string;
totalCents: number;
}
export const create = api(
{ expose: true, method: "POST", path: "/orders" },
async ({ totalCents }: { totalCents: number }): Promise<Order> => {
if (!Number.isInteger(totalCents) || totalCents <= 0) {
throw APIError.invalidArgument("totalCents must be a positive integer");
}
const row = await db.queryRow<{ id: number }>`
INSERT INTO orders (status, total_cents)
VALUES ('pending', ${totalCents})
RETURNING id
`;
return { id: row!.id, status: "pending", totalCents };
},
);
export const get = api(
{ expose: true, method: "GET", path: "/orders/:id" },
async ({ id }: { id: number }): Promise<Order> => {
const row = await db.queryRow<{ id: number; status: string; total_cents: number }>`
SELECT id, status, total_cents FROM orders WHERE id = ${id}
`;
if (!row) throw APIError.notFound("order not found");
return { id: row.id, status: row.status, totalCents: row.total_cents };
},
);
-- orders/migrations/1_create_orders.up.sql
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
status TEXT NOT NULL,
total_cents INTEGER NOT NULL CHECK (total_cents > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
encore run starts Postgres locally and applies the migration. There is no connection string or password anywhere in the code, and the TypeScript database docs cover the query API.
When the app deploys, Encore creates the roles through the master user and gives each Fargate task or Kubernetes deployment its own login role, a member of the service's role, which can only reach the databases that service uses. When services run in their own containers, the orders service above connects with a role that can read and write the orders database and nothing else, and a second service with its own database gets a separate role that cannot see the first one's tables, the same least-privilege result a careful IAM policy per database user gives you.
Credentials are visible to app admins in the Encore dashboard and can be rotated from it, with running services picking up new credentials on the next deploy, as described in managing database users. For people rather than services, encore db shell orders --env=production opens a psql session, read-only unless you pass --write or --admin, and encore db conn-uri orders --env=production prints a temporary connection string, so nobody needs the service credentials for ad-hoc queries, and the managing infrastructure docs cover connecting BI tools and pipelines.
The database password never sits in the repository, which also means an AI coding agent working in the codebase can add tables and queries without being handed a credential it could leak.
Best fit: teams on AWS that want each service to reach only its own Postgres databases, with credentials created and rotated outside their code.
Instead of a stored password, the client signs a short-lived authentication token with its AWS credentials and sends it as the password when it connects over TLS. RDS checks the signature and the caller's rds-db:connect permission for that database user. Tokens are valid for 15 minutes and are only checked at login, so open connections keep working after the token expires.
With the AWS CLI, run aws rds generate-db-auth-token with the instance hostname, port, region and database user name. In Go, call auth.BuildAuthToken from github.com/aws/aws-sdk-go-v2/feature/rds/auth with the endpoint, region, user and credentials; in Node, call getAuthToken on a Signer from @aws-sdk/rds-signer. Signing happens locally, without an API call.
The usual causes are a policy that uses the instance name instead of its resource ID (db-...) in the rds-db:connect ARN, a database user that was not granted rds_iam, a user name whose case does not match, a token signed for a different hostname, port or region, or a token older than 15 minutes.
Encore's documentation describes Postgres roles created on the RDS or Aurora server, a login role with credentials per container, and a dashboard where you can view and rotate those credentials. It does not describe IAM database authentication on AWS.
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.