Sub topic 10
Scaling reads with read replicas
This chapter assumes you have already created a DB instance (see the earlier chapters on provisioning and backups), that you can use the AWS CLI and boto3, and that you know what replication lag means in general terms. By the end you should be able to create a replica, route read traffic to it, watch its lag, and promote it when needed.
What a read replica is
A read replica is a separate DB instance that holds a copy of a source instance's data and accepts only read queries. RDS builds it from a snapshot of the source. It then keeps it current with the database engine's own replication mechanism:
- RDS for PostgreSQL uses physical streaming replication of the write-ahead log.
- RDS for MySQL and MariaDB replay the source's binary log.
Replication is asynchronous. The source commits a transaction without waiting for any replica to apply it. This has two consequences:
- Writes on the source stay fast, no matter how many replicas exist.
- A replica can be behind the source, so a read from it may return older data than a read from the source.
Each replica has its own endpoint, its own security groups, its own parameter group, and its own bill. It is a full instance, not a cache.
placeholderThe diagram below shows the typical traffic pattern.
Replicas are not Multi-AZ
Learners often confuse the two features because both create a second copy of the data. They solve different problems.
| Aspect | Multi-AZ (instance deployment) | Read replica |
|---|---|---|
| Main purpose | Availability and durability | Read scaling, reporting, migration |
| Replication | Synchronous | Asynchronous |
| Standby serves queries | No | Yes, read-only |
| Failover | Automatic | Manual promotion |
| Own endpoint | No, the source endpoint stays the same | Yes |
| Cross-Region | No | Yes |
You can combine them. A Multi-AZ source protects writes against an Availability Zone failure, and replicas absorb read load. A replica can also be Multi-AZ itself if you want it to survive a failure.
Multi-AZ DB clusters are a different deployment option. Their standbys are readable, but they follow different rules from the replicas in this chapter.
Prerequisites on the source
Before you can create a replica, check these points:
- Automated backups must be on. For RDS for MySQL, MariaDB, and PostgreSQL, the source needs a backup retention period greater than 0. Replication depends on the log retention that backups enable. The
demo-pginstance from earlier uses 7 days, so it qualifies. - The engine and edition must support replicas. MySQL, MariaDB, and PostgreSQL support them broadly. Oracle and SQL Server support them with edition and licensing conditions, so check the current documentation for your version.
- Replica limits apply. The limit is up to 15 replicas per source for MySQL, MariaDB, and PostgreSQL, and fewer for some other engines. Check the current quota before you design around a number.
Creating a replica
The command needs only the new identifier and the source:
aws rds create-db-instance-read-replica \
--db-instance-identifier demo-pg-replica \
--source-db-instance-identifier demo-pgRun it as shown and the replica inherits most settings from the source. You can override some at creation. Useful overrides are:
--db-instance-class, to size the replica differently from the source.--no-publicly-accessibleor--publicly-accessible, so you state network exposure explicitly instead of relying on inheritance.--vpc-security-group-ids, to give the replica its own security group rules.--db-parameter-group-name, to give the replica its own parameter group.
Creation takes time because RDS copies the data first. Wait for the replica with a waiter and read its endpoint, as you did for the source:
import boto3
rds = boto3.client("rds")
rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier="demo-pg-replica")
replica = rds.describe_db_instances(DBInstanceIdentifier="demo-pg-replica")["DBInstances"][0]
print(replica["Endpoint"]["Address"], replica["Endpoint"]["Port"])
print("source:", replica["ReadReplicaSourceDBInstanceIdentifier"])Sizing the replica
A replica must apply every change the source makes, in addition to serving its own queries. Use an instance class at least as large as the source for write-heavy workloads. A smaller replica falls behind and the lag keeps growing. Storage should also be at least as large as the source's.
Parameter groups on replicas
A replica uses its own parameter group. For PostgreSQL, some parameters on the replica must be at least as large as on the source, max_connections being the common example. If they are not, replication can stop. Keep the two groups aligned for any parameter that affects replay. Settings meant only for read workloads, such as a different work_mem, can differ.
Encryption and cross-Region replicas
A replica of an encrypted source is encrypted. For a cross-Region replica you must supply a KMS key that exists in the destination Region, and the source is referenced by ARN:
aws rds create-db-instance-read-replica \
--region us-west-2 \
--db-instance-identifier demo-pg-replica-west \
--source-db-instance-identifier arn:aws:rds:us-east-1:111122223333:db:demo-pg \
--kms-key-id alias/rds-west \
--no-publicly-accessibleCross-Region replicas serve users close to another Region and support disaster recovery plans. They add data transfer charges and usually higher lag.
Routing reads to the replica
RDS does not balance traffic across replicas. The source endpoint always goes to the source, and each replica endpoint goes only to that replica. Your application has to decide where each query goes. Common approaches:
- Use two connection pools in the application, one for writes and one for reads, with a helper that picks the pool.
- Use a database driver or framework feature that supports read/write splitting.
- Put several replicas behind a DNS record or load balancer you manage, such as a weighted Route 53 record set.
Keep these rules in your routing logic:
- Send all writes to the source.
- Send queries that must see your own just-written data to the source, or wait until the replica has caught up.
- Send reports, search pages, and other tolerant reads to replicas.
A simple connection helper in Python shows the idea. It assumes you have psycopg2 installed and that you pass the endpoints in as environment variables:
import os
import psycopg2
def connect(readonly: bool):
host = os.environ["DB_REPLICA_HOST"] if readonly else os.environ["DB_PRIMARY_HOST"]
return psycopg2.connect(
host=host,
dbname=os.environ["DB_NAME"],
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
sslmode="verify-full",
sslrootcert="global-bundle.pem",
)
with connect(readonly=True) as conn, conn.cursor() as cur:
cur.execute("SELECT count(*) FROM orders")
print(cur.fetchone()[0])The credentials still come from the source's managed secret. A replica carries the same users as the source, because it receives them through replication, and you cannot create users on a replica.
Replica lag
Lag is the delay between a commit on the source and its visibility on the replica. Monitor it with the CloudWatch metric ReplicaLag (seconds, namespace AWS/RDS, dimension DBInstanceIdentifier). The following reads the maximum lag over the last ten minutes:
from datetime import datetime, timedelta, timezone
import boto3
cw = boto3.client("cloudwatch")
now = datetime.now(timezone.utc)
stats = cw.get_metric_statistics(
Namespace="AWS/RDS",
MetricName="ReplicaLag",
Dimensions=[{"Name": "DBInstanceIdentifier", "Value": "demo-pg-replica"}],
StartTime=now - timedelta(minutes=10),
EndTime=now,
Period=60,
Statistics=["Maximum"],
)
for point in sorted(stats["Datapoints"], key=lambda p: p["Timestamp"]):
print(point["Timestamp"], point["Maximum"])Typical causes of rising lag:
- A heavy write burst or a large batch on the source.
- A replica that is too small, or that has long-running queries competing for the same resources.
- Network distance, mostly for cross-Region replicas.
- On PostgreSQL, queries on the replica that conflict with replay. The engine may delay replay or cancel the query. Settings such as
max_standby_streaming_delayandhot_standby_feedbacktrade off lag against cancelled queries.
Create a CloudWatch alarm on ReplicaLag with a threshold that matches how stale your application can tolerate. If the replica's replication stops entirely, the instance's status changes and RDS emits events. Subscribe to those events as well.
Promoting a replica
You can turn a replica into a standalone instance:
aws rds promote-read-replica --db-instance-identifier demo-pg-replicaPromotion stops replication permanently. The promoted instance becomes a normal writable instance with its own endpoint, and you cannot reattach it to the old source. Uses include:
- Disaster recovery. Promote a replica after the source or its Region fails, then point the application at the new endpoint.
- Migration or splitting. Create a replica, let it catch up, then promote it to get a copy for a new environment.
- Major version upgrade testing. Create a replica, promote it, and upgrade the promoted copy to rehearse the upgrade.
After promotion you must reconfigure backup retention if needed and update application connection settings yourself. Anything committed on the source but not yet applied on the replica is lost to the promoted copy, which is the cost of asynchronous replication.
If you delete a source instance that still has same-Region replicas, RDS promotes them to standalone instances. Remember them in your cleanup checklist, since they keep billing. Delete replicas first, then the source.
Cost
Each replica is billed like any instance: instance hours, storage, and I/O if applicable, plus cross-Region data transfer. Replicas do not share the source's storage, and a replica's backups follow its own retention settings. Add replicas only when a measured read bottleneck justifies them. If CPU on the source is high because of a few slow queries, tune those queries first, using the monitoring tools from the earlier chapter.
Exercise
Your source instance orders-db is Multi-AZ, and a reporting job running on a read replica sometimes shows orders that are a few seconds old. A teammate proposes switching the job to the Multi-AZ standby to get fresher data. What is wrong with that idea, and what should you check instead?
Show answer
In an instance-style Multi-AZ deployment the standby accepts no connections and has no endpoint of its own, so the job cannot read from it. Staleness on a read replica comes from asynchronous replication lag. Check the ReplicaLag CloudWatch metric for the replica, then look for causes such as an undersized replica, write bursts on the source, or long-running queries on the replica. If the job needs fresh data, either tolerate the lag, resize the replica, or run that query on the source.
Exercise
You run aws rds promote-read-replica on demo-pg-replica and later want it to follow demo-pg again. Is that possible, and how would you get a replica again?
Show answer
No. Promotion permanently ends replication, and the promoted instance cannot be reattached to its old source. To get a replica again, create a new one with create-db-instance-read-replica from the source, which rebuilds it from a fresh copy of the data.