What is RDS rightsizing, and why do CPU averages mislead?
RDS rightsizing means matching three things to the workload you have actually measured: the instance class (vCPU and memory), the instance family (general purpose, memory-optimized, burstable), and the storage configuration (type, size and provisioned throughput). The aim is to stop paying for headroom the database never uses. The constraint is that you must keep enough capacity for the moments when it does.
The usual starting point is the CloudWatch CPUUtilization average, and it is the wrong one. An instance averaging 15% CPU looks oversized. That average can hide several problems:
- Memory pressure. A working set that barely fits in the buffer cache shows little CPU. Shrink the memory and reads spill to storage.
- I/O waits. Sessions blocked on storage are not consuming CPU, so the CPU graph stays flat while queries slow down.
- Locking. Sessions waiting on row locks or latches add latency without adding CPU load.
- Peaks. A five-minute or hourly average flattens a nightly batch or a month-end spike that pins the CPU for twenty minutes.
A better primary signal is database load, which Performance Insights reports as average active sessions (AAS). It counts sessions that are working or waiting, broken down by wait type. You compare it against the instance's vCPU count. That comparison shows both how busy the database is and what it is waiting on.
This work belongs to the backend and platform engineers who own steady production databases or fleet-wide RDS spend. Database instances bill around the clock, so one oversized class repeated across environments is a large, recurring line item and a direct lever for database cost reduction.
Who should use this approach?
This approach suits teams that run provisioned RDS instances with a workload that is reasonably stable from one business cycle to the next. In practice that means:
- Service owners of production databases who know the application's traffic pattern and job schedule. They can tell whether a peak in the data is a real event or an anomaly.
- Platform and infrastructure engineers responsible for many similar instances: per-service databases, staging and test copies, read replicas. A method that works on one instance can be repeated across the fleet.
- Engineers handling cost reviews together with the database owners. The analysis gives them evidence for a change, not just a line on a bill.
You need read access to Performance Insights and CloudWatch for the instance, access to run diagnostic queries against the engine, and the authority to schedule an instance modification. Performance Insights must be enabled on the instance before the observation window starts, since it cannot show history it did not collect.
How does Performance Insights-based rightsizing work?
Performance Insights samples the state of active database sessions every second. Each sample records whether a session is on CPU or waiting, and if waiting, on which wait event, together with the SQL statement, user and host involved. Averaging those samples over time produces the database load metric in average active sessions, which you can slice by wait event, SQL statement, user or host.
The rightsizing method built on that data runs in a fixed order:
- Measure load against capacity. Compare peak AAS with the vCPU count over a representative window. Load well below the vCPU line marks a candidate.
- Classify the load by wait event. Only CPU-dominated load shrinks with a smaller class. I/O, lock and client waits point to different fixes.
- Check memory. Confirm that the working set will still fit in the buffer cache on the target class, and that memory-derived parameters such as
max_connectionswill still suit the application. - Remove waste first. Fix the top SQL statements so you size for the real workload, not for avoidable scans.
- Compare options. Price a smaller class, a different family, burstable classes and storage changes against each other.
- Change, verify, and keep an exit. Rehearse, apply the change with predefined rollback criteria, and compare load and waits against the baseline afterwards.
Each step can stop the process. An instance that fails step 2 or 3 is not a downsizing candidate, however low its CPU average is. The sections below cover each step in detail.
How does Performance Insights show whether an instance is oversized?
Performance Insights measures database load in average active sessions (AAS): the number of sessions running or waiting at any moment, averaged over the interval. The dashboard draws this against a Max vCPU line. Each vCPU can serve one active session at a time, so load sitting well below that line for a representative window means you are paying for cores that never get work. That is the main sign of an oversized instance.
Sketch of the load chart: the x-axis is time over a full business cycle and the y-axis is AAS. A flat horizontal line marks the vCPU count, for example 16. Below it, stacked bands show load by wait category: CPU at the bottom, then I/O, lock and client waits. If peaks reach 4–5 AAS against a line at 16, mostly in the CPU band, that is a candidate to shrink.
The size of the stack tells you whether the instance is too big. Its composition tells you what to change. Slice load by wait event before acting, because only CPU-dominated load scales with instance size.
| Dominant wait category | Likely cause | Rightsizing action |
|---|---|---|
| CPU | Compute demand, or inefficient SQL | Shrink if load stays well under vCPU; otherwise tune queries |
| I/O (e.g. data file reads) | Working set exceeds memory, or storage throughput limits | Fix storage or move to a memory-optimized family; do not shrink |
| Lock / transaction waits | Contention between sessions | Fix queries and transaction scope; more vCPUs will not help |
| Client / network waits | Chatty application or slow clients | Fix the application round trips; instance size is not the constraint |
AAS
16 |================================================ Max vCPU = 16
: unused headroom: paid-for idle cores
5 | n n
4 | l l i i l i
3 | i i i i i i i i i i i i i
2 | c c c c c c c c c c c c c c c c
1 | c c c c c c c c c c c c c c c c
0 +------------------------------------------------> time
c=CPU i=I/O l=lock n=client (one full business cycle)
|
v
+--------------------------+
| Slice load by wait event |
+--------------------------+
|
+-------------+------+------+-------------+
v v v v
+----------+ +----------+ +----------+ +----------+
| CPU | | I/O | | Lock/txn | | Client/ |
| | | | | | | network |
+----------+ +----------+ +----------+ +----------+
v v v v
+----------+ +----------+ +----------+ +----------+
|Shrink if | |Fix | |Fix query | |Fix app |
|well under| |storage or| |and txn | |round |
|vCPU, else| |memory-opt| |scope; no | |trips; not|
|tune SQL | |family; no| |more vCPU | |a size |
| | |shrink | | | |problem |
+----------+ +----------+ +----------+ +----------+
Peak load of about 4-5 AAS, mostly CPU, sits far below a 16 vCPU line. Slicing that load by wait event shows which action applies: shrink, change family or storage, fix queries, or fix application round trips.
When should you rightsize, and how long should you observe first?
Pick the window from the workload's calendar, not from the date you start the project. It must include the heaviest events the instance has to absorb: month-end close, quarterly reporting, nightly batch and ETL runs, the automated backup window, and known traffic spikes such as campaigns or seasonal peaks. For most business systems that means at least one full month, and ideally a quarter boundary. A quiet week can look like 70% headroom and still miss the one job that saturates memory or IOPS every 30 days.
Performance Insights retention limits how far back you can look. The free tier keeps seven days of history, which covers a weekly cycle but not monthly ones. Either enable longer paid retention before you start observing, or accept that Performance Insights will explain what is waiting while another source tells you how high the peaks were.
CloudWatch fills that gap. It keeps hourly data points for roughly 15 months, so you can check the following metrics across a long period:
CPUUtilizationFreeableMemoryReadIOPSandWriteIOPSReadLatencyDatabaseConnections
Request maximums and high percentiles rather than averages. With aws cloudwatch get-metric-statistics, request --statistics Maximum in one call and --extended-statistics p99 in a separate call, since the API does not accept both together, and use a one-hour period over 90 days. Hourly averages flatten a ten-minute batch spike into noise. The p99 and maximum values show the burst the smaller instance would have to survive.
Line the peaks up against your job schedule. If they recur, size for them, not for the median hour.
#!/usr/bin/env bash
set -euo pipefail
DB_ID="orders-prod-db" # placeholder DB instance identifier
REGION="eu-west-1"
PERIOD=3600 # 1 hour; data older than 63 days is only kept at this resolution
METRICS=(CPUUtilization FreeableMemory ReadIOPS WriteIOPS ReadLatency DatabaseConnections)
for metric in "${METRICS[@]}"; do
for chunk in 0 1 2; do
# GNU date: chunk 0 = days 90..60 ago, chunk 2 = days 30..0 ago
start=$(date -u -d "$((90 - chunk * 30)) days ago" +%Y-%m-%dT%H:00:00Z)
end=$(date -u -d "$((60 - chunk * 30)) days ago" +%Y-%m-%dT%H:00:00Z)
common=(--region "$REGION" --namespace AWS/RDS --metric-name "$metric"
--dimensions Name=DBInstanceIdentifier,Value="$DB_ID"
--start-time "$start" --end-time "$end" --period "$PERIOD")
# Maximum: the single worst sample in each hour (minimum for FreeableMemory matters too)
aws cloudwatch get-metric-statistics "${common[@]}" \
--statistics Maximum Minimum \
--query 'Datapoints[].[Timestamp,Maximum,Minimum]' --output text \
> "${metric}_max_${chunk}.tsv"
# p99: sustained high load, less sensitive to one-off outliers
aws cloudwatch get-metric-statistics "${common[@]}" \
--extended-statistics p99 \
--query 'Datapoints[].[Timestamp,ExtendedStatistics.p99]' --output text \
> "${metric}_p99_${chunk}.tsv"
done
# Show the five worst hours so peaks can be matched against the job calendar
echo "== $metric top hourly maxima =="
cat "${metric}"_max_*.tsv | sort -k2 -g -r | head -5
done
Pulls hourly Maximum/Minimum and p99 for six RDS metrics over 90 days, using separate calls because GetMetricStatistics rejects Statistics and ExtendedStatistics together, and 30-day chunks to stay under 1,440 datapoints per call.
When should you avoid rightsizing?
Downsizing is the wrong move, or the wrong time, in several situations:
- You have not observed a full business cycle. A new database, or one whose Performance Insights history only covers a quiet week, has not shown you its worst day yet. Wait until it has.
- Load is dominated by I/O, lock or client waits. A smaller class does not fix any of these, and in the I/O case it makes things worse by shrinking the buffer cache.
- The working set is already near the memory limit. If read IOPS rise every time
FreeableMemorydips, a class with less memory will turn cache hits into storage reads. - Growth or a major change is imminent. A product launch, a migration onto this database, a major engine version upgrade or a schema change can each alter the load profile. Rightsize after the change has settled, not before.
- Headroom is part of the recovery plan. If the instance must absorb a cold-cache failover, a replica catch-up or a backfill job within a fixed recovery time, the spare capacity is doing a job even when it looks idle.
- A reservation makes the change cost-neutral or worse. If an existing reserved instance cannot follow the new class, you keep paying for the reservation and add the cost of the new instance.
- The saving is smaller than the effort. On small instances the price gap between adjacent sizes can be lower than the cost of the analysis, the rehearsal and the change window. Group such instances into a fleet-wide review or leave them alone.
Why is memory often the real constraint on a smaller RDS instance size?
CPU is the visible cost, but memory is what keeps a read-heavy workload CPU-light. PostgreSQL's shared_buffers and MySQL's innodb_buffer_pool_size hold hot pages in RAM. When the working set (the indexes and rows your queries touch repeatedly) fits there, reads never reach storage. A class with half the memory can shrink that cache below the working set. Queries that were served from RAM then become disk reads. CPU stays low, while read IOPS, read latency and, on provisioned-IOPS or I/O-billed storage, the storage line of your bill go up. You have saved on compute and paid it back in storage and p99 latency.
Check the hit ratio before you resize:
- PostgreSQL: compare
blks_hitwithblks_readinpg_stat_database. - MySQL: compare
Innodb_buffer_pool_reads(reads that missed the pool) withInnodb_buffer_pool_read_requestsinSHOW GLOBAL STATUS.
A ratio that is high on the current class says nothing about whether the cache has headroom. The more useful signal is in CloudWatch. Plot FreeableMemory against ReadIOPS and ReadLatency over the same window. If read I/O is flat and low while freeable memory is comfortably above zero, the cache has slack. If read I/O already climbs whenever memory dips, the working set is close to the edge, and a smaller class will push it over.
Check your parameter groups as well. On RDS, the default buffer sizes and max_connections are formulas based on DBInstanceClassMemory, so they shrink automatically when you resize. An application whose connection pools were sized against the old limit can start failing with connection errors right after the change, even though nothing in its own configuration moved.
-- PostgreSQL: buffer cache hit ratio for the current database.
-- Counters are cumulative since the last stats reset, so sample twice
-- and compare deltas if you want the ratio for a recent window.
SELECT datname,
blks_hit,
blks_read,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database
WHERE datname = current_database();
-- PostgreSQL: connection ceiling vs. current usage.
-- On RDS the default max_connections derives from instance memory and drops on resize.
SHOW max_connections;
SELECT count(*) AS current_connections FROM pg_stat_activity;
-- MySQL: InnoDB buffer pool hit ratio.
-- Innodb_buffer_pool_reads counts logical reads that missed the pool and went to storage.
SELECT round(100 * (1 - r.v / nullif(rr.v, 0)), 2) AS buffer_pool_hit_pct
FROM (SELECT CAST(VARIABLE_VALUE AS UNSIGNED) AS v
FROM performance_schema.global_status
WHERE VARIABLE_NAME = 'Innodb_buffer_pool_reads') AS r,
(SELECT CAST(VARIABLE_VALUE AS UNSIGNED) AS v
FROM performance_schema.global_status
WHERE VARIABLE_NAME = 'Innodb_buffer_pool_read_requests') AS rr;
-- MySQL: current pool size and connection limits, both memory-derived by default on RDS.
SHOW GLOBAL VARIABLES LIKE 'innodb_buffer_pool_size';
SHOW GLOBAL VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
Queries that report the buffer cache hit ratio and the memory-derived connection limits on PostgreSQL and MySQL, so you can record both before resizing to a smaller instance class.
Should you tune top SQL before you resize?
Yes, in most cases. Resizing based on current load means sizing around whatever waste that load contains. If a few statements burn most of the CPU or I/O, the instance looks busy for reasons a resize won't fix, and a smaller size inherits the same problem with less headroom.
In Performance Insights, slice database load by SQL and sort by load. Each top statement shows its share of average active sessions and the waits it spends time in. Three patterns are worth looking for:
- Missing indexes. A statement dominated by CPU or I/O waits, where the engine examines far more rows than it returns.
- N+1 queries. A trivial lookup that ranks high because the application calls it thousands of times per request cycle, not because each call is slow. The fix belongs in the application, through batching or a join, not in the database.
- Inefficient scans. Sequential or full table scans on large tables, often caused by a predicate that wraps an indexed column in a function.
In the example below, a query filters orders by customer and status and sorts by creation time. Before the fix, the plan shows a sequential scan that discards most of the rows it reads. After adding a composite index on those three columns, the plan becomes an index scan that reads only the matching rows, already in order. The load from that statement drops out of the top of the list.
Weigh the effort against the savings. On a large instance, one fixed query can free enough capacity to drop a size and keep saving every month. On a small instance, the difference between two adjacent sizes is often less than the cost of the engineering time to find and fix the query, so tune there for latency, not for cost.
-- Top statement from Performance Insights, run with a representative filter value.
-- BUFFERS shows how many pages each plan touches.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_amount, created_at
FROM orders
WHERE customer_id = 4821 AND status = 'pending'
ORDER BY created_at DESC
LIMIT 50;
-- BEFORE (abbreviated plan shape, illustrative):
-- Limit
-- -> Sort (Sort Key: created_at DESC)
-- -> Seq Scan on orders -- may show as Parallel Seq Scan on large tables
-- Filter: ((customer_id = 4821) AND (status = 'pending'::text))
-- Rows Removed by Filter: <nearly every row in the table>
-- The engine reads the whole table, discards almost all of it, then sorts what is left.
-- Fix: equality columns first, then the sort column, so matching rows come back in order.
-- CONCURRENTLY avoids blocking writes on a busy table. It cannot run inside a transaction block.
CREATE INDEX CONCURRENTLY orders_customer_status_created_idx
ON orders (customer_id, status, created_at);
-- Refresh planner statistics so the new index is costed correctly.
ANALYZE orders;
-- AFTER (abbreviated plan shape, illustrative):
-- Limit
-- -> Index Scan Backward using orders_customer_status_created_idx on orders
-- Index Cond: ((customer_id = 4821) AND (status = 'pending'::text))
-- No Sort node and no discarded rows. The scan reads only matching entries and stops after 50.
-- Check Performance Insights again to confirm this statement has dropped down the load list.
A PostgreSQL EXPLAIN plan for a top-load query before and after adding a composite index. The index replaces a sequential scan and sort with an index scan that reads only the matching rows, already in order. The plan output is abbreviated and illustrative, not measured.
What are the alternatives to moving down a size, and what do they cost?
Moving down one size in the same family is only one option, and it is not always the biggest saving.
| Option | What changes | Main risk |
|---|---|---|
| Down a size, same family | Half the vCPU and memory | Buffer cache shrinks; less headroom |
| Memory-optimized to general purpose | Same vCPU, less memory per vCPU | Working set no longer fits in cache |
| Burstable class | Baseline CPU plus credits | Credits run out under steady load; if unlimited mode is on, surplus usage is billed |
| Storage type or provisioned IOPS | Instance unchanged | IOPS ceiling too low for peaks or recovery |
Illustrative estimate (assumed numbers, not a benchmark). Monthly cost = hourly rate × 730 + GB × storage price + provisioned IOPS × IOPS price. Assume $0.50/h for the current instance and $0.25/h one size down. Assume 500 GB of storage with 10,000 provisioned IOPS, priced at $0.125/GB and $0.10/IOPS on the current storage type, or $0.08/GB and $0.02/IOPS on an alternative type.
- Current: 365 + 62.50 + 1,000 = $1,427.50
- Down a size: 182.50 + 62.50 + 1,000 = $1,245
- Storage change only: 365 + 40 + 200 = $605
With these inputs, provisioned IOPS dominate the bill, so changing storage saves far more than resizing the instance.
Check reserved instances before you change anything. Size flexibility within a family applies only to some engines. Moving to a different family or engine can leave a reservation paying for capacity you no longer run.
Keep enough headroom for traffic spikes and for failover. After a failover, the new primary starts with a cold cache, and an instance sized close to its limit may not recover before queries begin timing out.
How do you implement an RDS resize safely and roll back if needed?
Treat the resize itself as a change with a test, a gate and an exit.
- Rehearse on a copy. Restore a recent snapshot to the target class and replay representative traffic. This shows how the smaller instance behaves under your workload before production depends on it.
- Check memory-scaled parameters. Default parameter groups calculate buffer pool size and
max_connectionsfrom instance memory. If you hardcoded those values in a custom group, they will not shrink with the instance and can overcommit RAM. If you rely on the defaults, confirm that the lower connection ceiling still fits your connection pools. - Write rollback criteria before the change. For example: database load stays above vCPU count for 15 minutes, p99 latency rises past an agreed threshold, or I/O or lock waits replace CPU as the dominant wait event. A precise trigger lets you roll back without debating whether the change is working.
- Apply the change. Run
aws rds modify-db-instancewith--db-instance-classand either--apply-immediatelyor--no-apply-immediately. The second option defers the change to the next maintenance window. On Multi-AZ, RDS modifies the standby first and then fails over, so the interruption is usually a brief reconnect rather than a full restart. - Watch the cold cache. Read latency stays elevated until the buffer pool warms. Compare Performance Insights load and top waits against your baseline over at least one full traffic cycle.
Handle read replicas, idle dev and test instances, and over-provisioned IOPS as separate changes. Each has its own risk and is easy to roll back on its own.
Turn these steps into a checklist and keep the pass and fail criteria with it. The next resize cycle then starts from a tested procedure instead of a fresh investigation.
How can this approach save engineering time?
The cost saving is on the bill. The time saving comes from replacing guesswork and investigation with a repeatable procedure:
- One place to diagnose load. Performance Insights shows load, wait events and top SQL on the same timeline. Engineers do not have to correlate slow query logs, CloudWatch graphs and application traces by hand to find out why the database is busy.
- Fewer failed resizes. Checking wait composition and memory before the change filters out instances that would regress. A downsizing that causes an incident costs the investigation, the rollback and a second change window, which usually outweighs the time spent checking first.
- Reusable tooling across the fleet. The CloudWatch export script and the hit-ratio queries run unchanged against any instance of the same engine. Platform teams can apply them to every candidate in a review cycle instead of building a new analysis each time.
- Query fixes that pay twice. Tuning a top statement before resizing lowers the load you size for, and it also removes a recurring cause of latency alerts and on-call pages.
- Decisions without debate. Written rollback criteria and a recorded baseline make the go/no-go call mechanical. Reviews take less time because the evidence is already in the change record.
Illustrative estimate (assumed inputs, not a measurement). Assume a team reviews 20 instances, and an ad hoc investigation takes about one engineer-day per instance because each one starts from scratch. Assume that with the script, queries and checklist in place, the review takes about two hours per instance after the first. Under those assumptions the review drops from roughly 20 engineer-days to roughly five, before counting any incidents avoided by not shrinking the wrong instances. Substitute your own per-instance times; the point is that the effort becomes proportional to the number of instances rather than to the number of surprises.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to rds rightsizing, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.