Sub topic 12
Monitoring and Performance Insights
This chapter assumes you have a running RDS instance such as demo-pg from the provisioning chapter, and that you know the basics of CloudWatch metrics and alarms. It covers the four sources of monitoring data RDS provides, how to read database load in Performance Insights, and which alarms to set first.
The four sources of monitoring data
RDS exposes several layers of telemetry. Each answers a different question.
| Source | What it shows | Granularity | Extra cost |
|---|---|---|---|
| CloudWatch metrics | Hypervisor-level CPU, memory, storage, IOPS, connections, replica lag | 1 minute | None for the standard RDS metrics |
| Enhanced Monitoring | OS-level metrics from an agent on the instance: per-process CPU, memory, file system | 1 to 60 seconds | CloudWatch Logs ingestion and storage |
| Performance Insights | Database load broken down by SQL, wait event, user, host, database | 1 second sampling | Free for 7 days of retention, paid for longer |
| Engine logs and events | Slow query, error and upgrade logs, plus RDS events such as failover | Per event | CloudWatch Logs charges if exported |
Standard CloudWatch metrics
RDS publishes metrics to the AWS/RDS namespace with the dimension DBInstanceIdentifier. These are the ones to know first:
CPUUtilization: percentage of CPU in use, as seen from outside the instance.FreeableMemory: memory available to the OS, in bytes. On Linux this includes reclaimable cache, so a low value alone is not always a problem. Watch it together withSwapUsage.FreeStorageSpace: bytes left on the data volume. Running out puts the instance into astorage-fullstate and stops writes.DatabaseConnections: current client connections. Compare it with the engine'smax_connections, which comes from the parameter group.ReadIOPS,WriteIOPS,ReadLatency,WriteLatency: storage activity and response time in seconds.DiskQueueDepth: I/O requests waiting for the volume. A persistently high value means storage cannot keep up.BurstBalance: remaining I/O credits on gp2 volumes. It does not apply to gp3.ReplicaLag: seconds a read replica is behind its source.
You can read a metric from Python with boto3. The following prints the maximum CPU per five-minute period over the last hour.
from datetime import datetime, timedelta, timezone
import boto3
cloudwatch = boto3.client("cloudwatch")
now = datetime.now(timezone.utc)
response = cloudwatch.get_metric_statistics(
Namespace="AWS/RDS",
MetricName="CPUUtilization",
Dimensions=[{"Name": "DBInstanceIdentifier", "Value": "demo-pg"}],
StartTime=now - timedelta(hours=1),
EndTime=now,
Period=300,
Statistics=["Average", "Maximum"],
)
for point in sorted(response["Datapoints"], key=lambda p: p["Timestamp"]):
print(point["Timestamp"].isoformat(), round(point["Average"], 1), round(point["Maximum"], 1))Alarms worth creating first
Create alarms before an incident, not during one. A low-storage alarm is the highest-value starting point because the failure is abrupt and easy to prevent. The threshold below is 2 GiB expressed in bytes, which suits the 20 GiB demo volume. Scale it to your volume size.
aws cloudwatch put-metric-alarm \
--alarm-name demo-pg-low-storage \
--namespace AWS/RDS \
--metric-name FreeStorageSpace \
--dimensions Name=DBInstanceIdentifier,Value=demo-pg \
--statistic Minimum \
--period 300 \
--evaluation-periods 3 \
--threshold 2147483648 \
--comparison-operator LessThanThreshold \
--treat-missing-data breaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:db-alerts--treat-missing-data breaching makes the alarm fire if the instance stops reporting, which is usually what you want for a database. Replace the SNS topic ARN with your own. Other reasonable first alarms are sustained CPUUtilization above 80%, DatabaseConnections near 80% of max_connections, ReplicaLag above your tolerance, and DiskQueueDepth above a small multiple of your provisioned IOPS divided by 1000 for several periods.
Enhanced Monitoring
Enhanced Monitoring runs an agent on the instance and sends OS-level metrics to CloudWatch Logs, in the RDSOSMetrics log group. It needs an IAM role that RDS can assume (service principal monitoring.rds.amazonaws.com) with the AmazonRDSEnhancedMonitoringRole managed policy. The interval can be 1, 5, 10, 15, 30 or 60 seconds. Shorter intervals produce more log data and cost more.
The same modify-db-instance call can also turn on Performance Insights and log exports. Replace the role ARN with the ARN of your monitoring role.
aws rds modify-db-instance \
--db-instance-identifier demo-pg \
--monitoring-interval 15 \
--monitoring-role-arn arn:aws:iam::111122223333:role/rds-monitoring-role \
--enable-performance-insights \
--performance-insights-retention-period 7 \
--cloudwatch-logs-export-configuration '{"EnableLogTypes":["postgresql","upgrade"]}' \
--apply-immediatelyEnhanced Monitoring is most useful when the instance looks healthy from outside but is slow. In that case you can see whether a single process holds the CPU, whether the instance is swapping, or whether the OS is waiting on I/O.
Performance Insights
Performance Insights answers the question standard metrics cannot: which queries are loading the database, and what are they waiting on.
Database load and average active sessions
The central metric is database load, measured in average active sessions (AAS). Every second, Performance Insights samples each session that is actively running or waiting inside the engine. AAS is the average number of such sessions over a time window. One session busy for the whole minute gives an AAS of 1.
The dashboard draws a line at the instance's vCPU count, called Max vCPU. The line gives the reading its meaning:
- AAS well below Max vCPU: the database has spare capacity.
- AAS near Max vCPU, and the load is mostly the CPU wait type: the instance is CPU bound. Tune the heaviest queries or move to a larger class.
- AAS above Max vCPU with load made of I/O or lock waits: sessions are queuing on something other than CPU. A bigger instance class will not fix a lock problem.
Slicing the load
You can group load by these dimensions:
- Waits: what sessions were waiting for, such as CPU,
IO:DataFileReadorLock:transactionidon PostgreSQL. Wait names differ by engine. - SQL: the normalized statements contributing the most load. Literals are replaced by placeholders, so one query pattern appears as one row.
- Hosts, users and databases: which client, role or database generates the load.
A practical workflow starts with the waits view to classify the problem. Then switch to the SQL view for the same time range and open the top statement. Fix that statement first, because load is usually concentrated in a few queries.
Querying Performance Insights from code
Performance Insights has its own API, exposed in boto3 as the pi client. It identifies an instance by its DbiResourceId (of the form db-ABC...), not by the instance name.
from datetime import datetime, timedelta, timezone
import boto3
rds = boto3.client("rds")
pi = boto3.client("pi")
instance = rds.describe_db_instances(DBInstanceIdentifier="demo-pg")["DBInstances"][0]
resource_id = instance["DbiResourceId"]
now = datetime.now(timezone.utc)
response = pi.get_resource_metrics(
ServiceType="RDS",
Identifier=resource_id,
StartTime=now - timedelta(hours=1),
EndTime=now,
PeriodInSeconds=300,
MetricQueries=[
{"Metric": "db.load.avg", "GroupBy": {"Group": "db.wait_event", "Limit": 5}}
],
)
for series in response["MetricList"]:
dimensions = series["Key"].get("Dimensions", {})
name = dimensions.get("db.wait_event.name", "total")
values = [p["Value"] for p in series["DataPoints"] if "Value" in p]
if values:
print(f"{name}: peak AAS {max(values):.2f}")The caller needs pi:GetResourceMetrics on the instance's Performance Insights resource ARN. This permission is separate from the rds:* actions.
Retention and availability
The default retention is 7 days at no charge. Longer retention, up to 24 months, is a paid option. Not every engine version and instance class supports Performance Insights, and AWS has been folding this functionality into CloudWatch Database Insights. Check the current console and pricing page for your Region before you design around a particular retention period.
Logs and events
Standard metrics and Performance Insights do not record error messages or individual slow statements. Export engine logs to CloudWatch Logs with --cloudwatch-logs-export-configuration, as in the earlier command. This pairs with the parameter group chapter: setting log_min_duration_statement to 500 only produces output that you can search if the PostgreSQL log is exported. Set a retention period on the resulting log groups, since CloudWatch Logs keeps data indefinitely by default.
RDS also emits events for failover, backup, maintenance and configuration changes. Create an RDS event subscription that sends them to an SNS topic, so you learn about a failover from a notification and not from a user report.
Common mistakes
- Judging memory from
FreeableMemoryalone, when the OS cache is counted as available. - Alarming on average CPU with a long period, which hides short saturation spikes. Use the Maximum statistic as well.
- Enabling a 1-second Enhanced Monitoring interval on every instance, then discovering the log charges.
- Looking at AAS without comparing it to the vCPU count.
- Setting a storage alarm threshold in gigabytes.
FreeStorageSpaceis reported in bytes.
Exercise
A db.t4g.medium instance has 2 vCPUs. Performance Insights shows an average database load of 6 AAS during a slowdown, and most of the load is in Lock:transactionid waits. CPUUtilization is only 20%. Should you move to a larger instance class? What do you do instead?
Show answer
No. Load is three times Max vCPU, but CPU is mostly idle, so the sessions are queuing on locks, not on compute. A larger class adds vCPUs that would also sit idle. Use the SQL view for the same time range to find the statements holding or waiting on the locks, then shorten those transactions, fix the access order, or add an index so each transaction finishes faster.
Exercise
Why does the low-storage alarm in this chapter use a threshold of 2147483648, and why does it use --treat-missing-data breaching?
Show answer
FreeStorageSpace is reported in bytes, and 2147483648 bytes is 2 GiB. Treating missing data as breaching makes the alarm fire when the instance stops publishing metrics, such as during an outage, instead of staying silently in the OK state.