Explain it simply
Explain it simply
In AWS Fundamentals you launched an RDS instance: one database server with its own disk. Aurora keeps the familiar MySQL and PostgreSQL engines but changes what sits underneath. Instead of each server owning a disk, every server in an Aurora cluster shares one storage volume that AWS spreads across three Availability Zones.
Think of a library. Classic RDS gives every librarian a private copy of the books. Aurora keeps one well-guarded collection in the middle and lets several librarians read from it, while only one of them is allowed to write. RDS Proxy is the front desk: visitors queue there instead of crowding every librarian at the same moment.
Problem → Why → Solution
The problem: connections explode when traffic spikes
Picture an order API built on Lambda and a single RDS PostgreSQL instance. On a normal day 20 concurrent functions each open a database connection and everything is fine. Then a marketing email goes out, concurrency jumps to 800, and every new execution environment opens its own connection during its cold start.
PostgreSQL's max_connections is sized from instance memory, so once the limit is reached new connections fail with 'too many clients'. Lambda retries make it worse, and the database spends memory and CPU managing connections instead of running queries. At the same time the reporting team runs heavy queries against the same instance and slows checkout down.
import os
def lambda_handler(event, context):
import psycopg # bundled in the deployment package
# BAD: a brand-new TCP + TLS + auth handshake on EVERY invocation,
# and nothing closes it. 800 concurrent environments = 800+ sessions
# hitting the database directly, plus a plaintext password in env vars.
conn = psycopg.connect(
host=os.environ["DB_HOST"],
user="app_user",
password=os.environ["DB_PASSWORD"],
)
with conn.cursor() as cur:
cur.execute("SELECT status FROM orders WHERE id = %s", (event["id"],))
return {"status": cur.fetchone()[0]}Connections are expensive, and Lambda multiplies them
Every relational connection costs a process or thread plus memory on the database server, and opening one needs a TCP, TLS and authentication handshake. Lambda scales by adding execution environments, and each one holds its own connection, so the database sees connection count rise with concurrency rather than with the real query load.
Core concept: shared storage and pooled connections
- Cluster volume
- The single, shared storage volume of an Aurora cluster. AWS keeps six copies of every piece of data across three Availability Zones, and every instance in the cluster reads from this same volume.
Aurora splits the database into two layers. The compute layer is one writer instance plus up to 15 Aurora Replicas running the MySQL- or PostgreSQL-compatible engine. The storage layer is the cluster volume: data is cut into small segments and each segment is stored six times, two copies in each of three AZs.
A write succeeds once four of the six copies acknowledge it, and a read needs three. That quorum lets Aurora keep writing after losing a whole AZ, and keep reading even when an AZ plus one more copy are gone. Because the writer ships only redo log records to storage instead of full data pages, there is far less write traffic than in a classic engine that mirrors its disk.
Replicas do not copy data; they read the same volume. A new replica is therefore ready in minutes regardless of database size, and replica lag is usually under 100 milliseconds. On failover, Aurora promotes a replica to writer, chosen by promotion tier, and repoints the cluster endpoint at it. There is no data to catch up because the storage is shared.
Without a replica, Aurora must create a brand-new writer instance, which takes much longer. That is why production clusters keep at least one replica in a different AZ.
| Endpoint | What it is for |
|---|---|
| Cluster (writer) endpoint | Always points at the current writer and follows failover. Use for writes and read-after-write |
| Reader endpoint | Spreads new connections (not individual queries) across the replicas |
| Custom endpoint | A group you choose, e.g. larger replicas reserved for analytics |
| Instance endpoint | One specific instance; does not follow failover, so avoid it in apps |
RDS Proxy sits between the application and the database. It keeps a pool of database connections open and lends one to a client for the length of a transaction, so thousands of client connections can share a few dozen database connections. It fetches the database credentials from Secrets Manager, can require IAM authentication from clients, and during a failover it keeps client connections open while it reconnects to the new writer.
AURORA CLUSTER BEHIND RDS PROXY
-------------------------------
Lambda x 800 ECS tasks Reporting job
| | |
v v v
+-----------------------------+ (reader endpoint)
| RDS Proxy (pool of ~40 | |
| DB connections, IAM auth) | |
+-----------------------------+ |
| cluster endpoint |
v v
+----------+ +------------+ +------------+
| Writer | | Replica 1 | | Replica 2 |
| AZ-a | | AZ-b tier0 | | AZ-c tier1 |
+----------+ +------------+ +------------+
| redo log | reads | reads
v v v
+-----------------------------------------------------+
| Cluster volume: 6 copies (2 per AZ, AZ-a/b/c) |
| write quorum 4 of 6, read quorum 3 of 6 |
+-----------------------------------------------------+- App connects to RDS Proxy
- Proxy lends a pooled connection
- Writer logs redo to 6 copies / 3 AZs
- Replicas read the same cluster volume
- Failover promotes a replica
Instances are just swappable compute. The real data lives in the cluster volume, which is why adding replicas and failing over are fast.
Pattern: an Aurora Serverless v2 cluster behind RDS Proxy
# 1. Aurora PostgreSQL cluster; RDS keeps the admin password in Secrets Manager
aws rds create-db-cluster \
--db-cluster-identifier orders \
--engine aurora-postgresql \
--master-username app_admin \
--manage-master-user-password \
--serverless-v2-scaling-configuration MinCapacity=0.5,MaxCapacity=16 \
--db-subnet-group-name orders-db-subnets \
--vpc-security-group-ids sg-0db1a2b3c4d5e6f70 \
--storage-encrypted \
--enable-iam-database-authentication
# 2. A writer and one reader (add --availability-zone to pin each to its own AZ)
for name in orders-writer orders-reader-1; do
aws rds create-db-instance \
--db-instance-identifier "$name" \
--db-cluster-identifier orders \
--engine aurora-postgresql \
--db-instance-class db.serverless
done
# 3. RDS Proxy logs in with the app user's secret; clients need IAM auth + TLS
aws rds create-db-proxy \
--db-proxy-name orders-proxy \
--engine-family POSTGRESQL \
--auth AuthScheme=SECRETS,SecretArn=$APP_USER_SECRET_ARN,IAMAuth=REQUIRED \
--role-arn arn:aws:iam::111122223333:role/orders-proxy-secrets \
--vpc-subnet-ids subnet-0a1b2c3d4e5f67890 subnet-0f9e8d7c6b5a43210 \
--vpc-security-group-ids sg-0db1a2b3c4d5e6f70 \
--require-tls
aws rds register-db-proxy-targets \
--db-proxy-name orders-proxy \
--db-cluster-identifiers ordersThe db.serverless instance class is Serverless v2: capacity floats between MinCapacity and MaxCapacity (in ACUs). The proxy's IAM role needs permission to read the app user's secret (secretsmanager:GetSecretValue, plus kms:Decrypt on the secret's KMS key). IAMAuth=REQUIRED means clients connect with a 15-minute IAM token instead of a password. After registering the target, use the proxy endpoint as the database host in your application.
A Lambda function that reuses one proxied connection
This example shows a Lambda function connecting to RDS Proxy with IAM authentication. Two things matter: the boto3 client and the connection are kept outside the handler so warm invocations reuse them, and instead of a password in an environment variable the function builds a token with generate_db_auth_token.
To keep the lesson runnable without a database, the spot where real code calls psycopg.connect just stores the connection parameters. The token is signed locally with SigV4, so no network call to AWS is made.
import os
from urllib.parse import parse_qs, urlsplit
import boto3
PROXY_HOST = os.environ.get(
"PROXY_HOST", "orders-proxy.proxy-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com"
)
PORT = 5432
DB_USER = "app_user"
# Created once per execution environment, reused by every warm invocation.
rds = boto3.client("rds", region_name="us-east-1")
_connection = None
connections_opened = 0
def get_connection():
"""Open (or reuse) one connection to RDS Proxy using an IAM auth token."""
global _connection, connections_opened
if _connection is None:
token = rds.generate_db_auth_token(
DBHostname=PROXY_HOST, Port=PORT, DBUsername=DB_USER
)
# Real code: psycopg.connect(host=..., password=token, sslmode="require")
_connection = {"host": PROXY_HOST, "port": PORT, "user": DB_USER,
"password": token, "sslmode": "require"}
connections_opened += 1
return _connection
def lambda_handler(event, context):
conn = get_connection()
return {"order_id": event["order_id"], "via": conn["host"].split(".")[0]}
if __name__ == "__main__":
for order_id in (101, 102, 103):
print(lambda_handler({"order_id": order_id}, None))
print("connections opened:", connections_opened)
token = _connection["password"]
parts = urlsplit("https://" + token)
query = parse_qs(parts.query)
print("token targets:", parts.netloc)
print("action:", query["Action"][0], "| user:", query["DBUser"][0])
print("token valid for:", query["X-Amz-Expires"][0], "seconds")
print("TLS required:", _connection["sslmode"])Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- Module-level client
rds = boto3.client("rds", region_name="us-east-1")Created outside the handler, so it runs once per execution environment. Warm invocations reuse the client.
- Lazy, cached connection
if _connection is None:The connection is opened the first time it is needed and cached in a global. The output proves three invocations opened only one connection.
- IAM auth token
rds.generate_db_auth_token(DBHostname=PROXY_HOST, Port=PORT, ...)A token signed with the function role's IAM credentials. It is valid for 15 minutes (900 seconds) and replaces the password. The role needs the rds-db:connect permission.
- TLS required
"sslmode": "require"IAM authentication requires a TLS connection, and the proxy was created with --require-tls, so it rejects plaintext connections.
{'order_id': 101, 'via': 'orders-proxy'}
{'order_id': 102, 'via': 'orders-proxy'}
{'order_id': 103, 'via': 'orders-proxy'}
connections opened: 1
token targets: orders-proxy.proxy-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com:5432
action: connect | user: app_user
token valid for: 900 seconds
TLS required: require- Lambda borrows a proxy connection
- Writer fails; replica is promoted
- Proxy holds client connections open
- Proxy reconnects to the new writer
- Transactions continue on new writer
Transaction was mid-flight at failover
Client gets an error and must retry
New transaction after promotion
Runs on the new writer, no DNS wait
Aurora Serverless v2 and Global Database
Serverless v2 measures capacity in Aurora Capacity Units (ACUs); one ACU is roughly 2 GiB of memory with matching CPU and networking. It scales in small increments between the minimum and maximum you set, and it can be mixed with provisioned instances in the same cluster. It suits spiky, unpredictable workloads and dev/test environments.
For steady high load, provisioned instances (ideally with reserved pricing) are usually cheaper. Some newer engine versions also support a minimum of 0 ACUs with auto-pause, but the first connection after a pause waits while the instance resumes; check the docs for whether your engine version supports it.
Aurora Global Database protects against losing a whole Region. The primary Region has the writer and secondary Regions run read-only clusters. Replication happens in the storage layer, not the database engine, so lag is typically under a second, and secondary Regions can also serve fast local reads.
There are two moves. A switchover is planned while both Regions are healthy: Aurora waits until the secondary is in sync before switching, so no data is lost. A failover is the emergency path when the primary Region is down; the last few unreplicated writes can be lost, which is why you must explicitly pass --allow-data-loss.
AURORA GLOBAL DATABASE
----------------------
us-east-1 (primary) eu-west-1 (secondary)
+----------------------+ +----------------------+
| writer + replicas | | replicas (read-only) |
+----------------------+ +----------------------+
| cluster volume | --------> | cluster volume |
| 6 copies / 3 AZs | storage | 6 copies / 3 AZs |
+----------------------+ replica +----------------------+
lag ~ <1s
switchover-global-cluster : planned, waits for sync, no loss
failover-global-cluster : emergency, --allow-data-lossRead replicas vs Multi-AZ: different problems
On classic RDS (not Aurora) these two are often confused. Multi-AZ is for availability: it replicates synchronously to a standby in another AZ and fails over automatically when the primary dies. A read replica is for scale: it is asynchronous, so it can lag, and it offloads read traffic, but promoting it is a manual action.
| Question | Multi-AZ (instance) | Read replica |
|---|---|---|
| Solves | AZ or instance failure | Too much read load |
| Replication | Synchronous | Asynchronous (can lag) |
| Can you query it? | No (standby is not readable) | Yes (read-only) |
| Failover | Automatic | Manual promotion |
RDS also offers a Multi-AZ DB cluster deployment whose two standbys are readable. In Aurora the distinction disappears: because storage is shared, an Aurora Replica is both a read-scaling node and a failover target.
In production
How teams use it in production
A typical production setup is an Aurora PostgreSQL cluster with a writer and two replicas in different AZs. One replica is tier 0 (preferred for failover), the other tier 1, and both are sized like the writer, because promoting an undersized replica causes an instant performance incident right after failover.
The application uses the cluster endpoint for writes and the reader endpoint for reads that tolerate slight staleness. Lambda functions and other connection-heavy clients go through RDS Proxy. Heavy analytics queries are sent through a custom endpoint to a dedicated replica so they never compete with checkout.
- Failover drills: run aws rds failover-db-cluster during business hours on a schedule and measure how many seconds of errors the application shows.
- Monitoring: CloudWatch alarms on DatabaseConnections, AuroraReplicaLag and the proxy's ClientConnections versus DatabaseConnections.
- DR: use Global Database only when the RPO/RTO requirement is Region-level, and rehearse a switchover at least once a year.
Common mistakes
Common mistakes
Reading your own write from the reader endpoint
A user updates their profile and the page immediately reads it back through the reader endpoint. Even a few milliseconds of replica lag can show the old data. Send requests that need read-after-write consistency to the cluster endpoint.
Assuming RDS Proxy fixes everything (pinning)
Statements that change session state (for example SET on a session variable, or creating a temporary table) force the proxy to pin that client to one database connection, so it can no longer multiplex. With lots of pinning, the connection storm comes back even with a proxy in place. Watch the DatabaseConnectionsCurrentlySessionPinned metric and move session settings into the connection string or the proxy's initialization query.
Hard-coding an instance endpoint
An instance endpoint does not follow failover; when the writer moves, the app keeps writing to the old instance, which is now read-only, and errors pile up. Use the cluster endpoint and make sure DNS is not cached for long (for example a JVM DNS TTL of a few seconds), or go through RDS Proxy.
Best practices
Best practices
- Keep at least one writer-sized replica in another AZ in every production cluster.
- Use RDS Proxy when Lambda talks to a relational database, and open the connection outside the handler.
- Keep database passwords in Secrets Manager and let applications connect with IAM auth tokens.
- Add retry logic with exponential backoff for connection and failover errors.
💰 Cost & Cleanup
Aurora charges per instance-hour (ACU-hour for Serverless v2), per GB-month of storage, for backup storage beyond the retention period, and for I/O requests on the Aurora Standard configuration (Aurora I/O-Optimized has no I/O charges but higher instance and storage prices). RDS Proxy is billed hourly based on the capacity (vCPUs or ACUs) of the database behind it. Aurora and RDS Proxy are not part of the classic free tier. Delete the proxy, instances and cluster right after the lab: even a 0.5 ACU Serverless v2 minimum costs money when it runs around the clock.
Clean up when you are done
aws rds delete-db-proxy --db-proxy-name orders-proxy
for name in orders-writer orders-reader-1; do
aws rds delete-db-instance --db-instance-identifier "$name" --skip-final-snapshot
done
aws rds wait db-instance-deleted --db-instance-identifier orders-writer
aws rds delete-db-cluster \
--db-cluster-identifier orders \
--skip-final-snapshotMini challenge
Add a reporting replica with a custom endpoint
The reporting team's heavy queries are slowing checkout down. Add a dedicated replica for them, and make sure that replica is never the preferred choice when Aurora picks a new writer.
- Add an instance named orders-reporting to the orders cluster with promotion tier 15
- Create a READER custom endpoint named analytics that contains only orders-reporting
- Check the resulting endpoint address with describe-db-cluster-endpoints
Expected: You get an endpoint shaped like analytics.cluster-custom-... that routes only to orders-reporting. On failover, Aurora prefers to promote orders-reader-1 (tier 1).
Show hint
Promotion tier 0 is the highest failover priority and 15 the lowest. A custom endpoint picks its instances with --static-members.
Show solution
aws rds create-db-instance \
--db-instance-identifier orders-reporting \
--db-cluster-identifier orders \
--engine aurora-postgresql \
--db-instance-class db.serverless \
--promotion-tier 15
aws rds wait db-instance-available --db-instance-identifier orders-reporting
aws rds create-db-cluster-endpoint \
--db-cluster-identifier orders \
--db-cluster-endpoint-identifier analytics \
--endpoint-type READER \
--static-members orders-reporting
aws rds describe-db-cluster-endpoints \
--db-cluster-identifier orders \
--query "DBClusterEndpoints[].[EndpointType,Endpoint]" \
--output tableQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Aurora separates compute from storage; the cluster volume keeps six copies across three AZs (write quorum 4, read quorum 3).
- Replicas share storage, so they are quick to add and double as failover targets; use the cluster endpoint for writes and the reader endpoint for reads.
- RDS Proxy solves Lambda connection storms with connection pooling, IAM auth and Secrets Manager integration.
- On classic RDS, Multi-AZ is for availability and read replicas are for read scaling.
- Serverless v2 fits unpredictable load; Global Database is for Region-level disaster recovery.
What is Amazon Aurora? — AWS Documentation
Amazon RDS Proxy — AWS Documentation
Using Amazon Aurora Global Database — AWS Documentation