Serverless ApsaraDB RDS for MySQL scales RDS Capacity Units (RCUs) automatically based on load. Most scale-ups complete within seconds. However, when a scale-up requires moving to a different host, it can take 3 to 5 minutes—long enough to disrupt workloads during a known peak window.
To prevent that disruption, pin the minimum and maximum RCU counts to fixed values before the peak window starts, then restore them afterward. This topic shows how to automate that workflow with a scheduled task using Python or Java.
How it works
Two types of scale-ups can occur:
Intra-host scale-up — The instance scales within the same host. Completes within seconds. Covers 99.8% of scenarios.
Inter-host scale-up — The instance moves to a different host. Takes 3 to 5 minutes. Triggered when the current host cannot provide enough resources.
Auto scaling kicks in when CPU utilization or memory usage reaches 60–80%. If an inter-host scale-up starts during a peak hour, the 3-to-5-minute window can cause instability.
The solution: call the ModifyDBInstanceSpec API on a schedule to pin the RCU range to a fixed value before the peak window. When the window ends, a second scheduled call restores the default range.
When to use scheduled RCU adjustment
Use this approach when you know in advance that a specific time window requires stable database capacity—for example:
Predictable peak traffic — Business hours, batch jobs, or scheduled reports that put consistent load on the database.
Preventing inter-host scale-up disruption — Lock the minimum RCUs high enough to avoid triggering a cross-host migration during the peak window.
How to choose your RCU range
When setting MinCapacity for the peak window, consider the following:
Set the minimum high enough to cover expected peak load. A higher minimum RCU means the instance is less likely to trigger an inter-host scale-up during the window.
Start the task 10 minutes early. If an inter-host scale-up is required when you raise the minimum, this lead time lets it complete before the peak starts.
Restore the default afterward. Run a second task at the end of the peak window to reset the RCU range, so the instance can scale down when load drops.
Prerequisites
Before you begin, make sure you have:
A Serverless ApsaraDB RDS for MySQL instance
A RAM user with the permissions required to call
ModifyDBInstanceSpec. See Create a RAM user and grant permissionsEnvironment variables configured for your AccessKey ID and AccessKey secret. See Configure environment variables
Example scenario
Peak hour is 08:00–09:00. The default RCU range is 0.5–8. During the peak hour, the minimum must be 4 to guarantee enough capacity.
Schedule two tasks:
| Time | Action | MinCapacity | MaxCapacity |
|---|---|---|---|
| 07:50 | Raise the minimum | 4 | 8 |
| 09:00 | Restore the default | 0.5 | 8 |
Start at 07:50—10 minutes before the peak—to allow time for an inter-host scale-up to complete before the window opens.
Schedule with Python
This example uses APScheduler with a cron trigger.
Step 1: Install dependencies
Install Python and install the Alibaba Cloud RDS SDK dependencies, then install APScheduler:
pip install apschedulerStep 2: Download the SDK sample code
Go to the ModifyDBInstanceSpec debugging page in OpenAPI Explorer.
On the Parameters tab, set the following values:
Parameter Description Value DBInstanceIdInstance ID rm-bp1t8v93k6e15****PayTypeBilling method ServerlessDirectionSpecification change type ServerlessMaxCapacityMaximum number of RCUs 8.0MinCapacityMinimum number of RCUs 0.5AutoPauseEnable automatic start and stop falseSwitchForceEnable forced scaling trueOn the SDK Sample Code tab, select Python from the Languages dropdown and click Download Project to download the sample package.
Download the SDK V2.0 sample project.
Extract the package on your machine and navigate to the
alibabacloud_sampledirectory.
Step 3: Add scheduled tasks to the sample code
Open sample.py and replace its contents with the following. All examples use a cron trigger via scheduler.add_job(..., 'cron', hour=H, minute=M) to set the execution time.
# -*- coding: utf-8 -*-
import os
import sys
from typing import List, Dict
from alibabacloud_rds20140815.client import Client as Rds20140815Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_rds20140815 import models as rds_20140815_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient
from apscheduler.schedulers.blocking import BlockingScheduler
class Sample:
def __init__(self):
pass
@staticmethod
def create_client() -> Rds20140815Client:
"""
Use your AccessKey ID and AccessKey secret to initialize a client.
@return: Client
@throws Exception
"""
# If the project code is leaked, the AccessKey pair may be leaked and the security of resources within your account may be compromised. The following sample code is provided only for reference.
# For security purposes, we recommend that you use temporary access credentials that are provided by Security Token Service (STS). For more information, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-php-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. ,
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. ,
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoint information, see https://api.aliyun.com/product/Rds.
config.endpoint = f'rds.aliyuncs.com'
return Rds20140815Client(config)
@staticmethod
def modify_db_instance_spec(config: Dict[str, float]) -> None:
"""
Call ModifyDBInstanceSpec to update the RCU range of the serverless instance.
"""
client = Sample.create_client()
serverless_configuration = rds_20140815_models.ModifyDBInstanceSpecRequestServerlessConfiguration(
max_capacity=config['max_capacity'],
min_capacity=config['min_capacity'],
auto_pause=config['auto_pause'],
switch_force=config['switch_force']
)
modify_dbinstance_spec_request = rds_20140815_models.ModifyDBInstanceSpecRequest(
dbinstance_id='rm-bp1t8v93k6e15****',
direction='Serverless',
pay_type='Serverless',
serverless_configuration=serverless_configuration
)
runtime = util_models.RuntimeOptions(
read_timeout=50000,
connect_timeout=50000
)
try:
resp = client.modify_dbinstance_spec_with_options(modify_dbinstance_spec_request, runtime)
ConsoleClient.log(UtilClient.to_jsonstring(resp))
except Exception as error:
print(error.message)
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
def main(args: List[str]) -> None:
scheduler = BlockingScheduler()
# At 07:50, raise the minimum to 4 RCUs to prepare for the 08:00 peak.
config_8am = {
'max_capacity': 8,
'min_capacity': 4,
'auto_pause': False,
'switch_force': True
}
# At 09:00, restore the default range of 0.5–8 RCUs.
config_9am = {
'max_capacity': 8,
'min_capacity': 0.5,
'auto_pause': False,
'switch_force': True
}
# cron trigger: hour=H, minute=M runs the task at H:M every day.
scheduler.add_job(Sample.modify_db_instance_spec, 'cron', hour=7, minute=50, args=[config_8am])
scheduler.add_job(Sample.modify_db_instance_spec, 'cron', hour=9, minute=0, args=[config_9am])
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
Sample.main(sys.argv[1:])Key parameters:
| Parameter | Description | Example |
|---|---|---|
max_capacity | Maximum number of RCUs | 8 |
min_capacity | Minimum number of RCUs | 4 (peak) / 0.5 (default) |
auto_pause | Enable automatic start and stop | False |
switch_force | Enable forced scaling | True |
hour, minute | Cron trigger time (24-hour) | hour=7, minute=50 runs at 07:50 daily |
Schedule with Java
This example uses Spring Schedule. Java 1.8 or later is required.
Step 1: Set up prerequisites
Create a RAM user and grant permissions and configure environment variables.
Step 2: Download the sample package
Download and extract demo.zip to your machine.
Step 3: Configure scheduled tasks in ScheduleTask.java
Open ScheduleTask.java and configure the cron expressions for your schedule. The @Scheduled annotation uses the format "Second Minute Hour Day Month Week". For the full cron expression syntax, see the Spring @Scheduled reference).
The following example sets the RCU range to [4, 8] at 07:50 and restores it to [0.5, 8] at 09:00:
package com.example.demo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduleTask {
// At 07:50 every day, raise the minimum to 4 RCUs before the 08:00 peak.
@Scheduled(cron = "0 50 7 * * ? ")
public void scheduleTask8am() {
ModifySpecParams params = new ModifySpecParams();
params.setRegionId("cn-hangzhou");
params.setDBInstanceId("rm-bp1t8v93k6e15****");
params.setDirection("Serverless");
params.setPayType("Serverless");
params.setAutoPause(false);
params.setSwitchForce(true);
params.setMaxCapacity(8);
params.setMinCapacity(4);
ModifyDBInstanceSpec.modify(params);
}
// At 09:00 every day, restore the default range of 0.5–8 RCUs.
@Scheduled(cron = "0 0 9 * * ? ")
public void scheduleTask9am() {
ModifySpecParams params = new ModifySpecParams();
params.setRegionId("cn-hangzhou");
params.setDBInstanceId("rm-bp1t8v93k6e15****");
params.setDirection("Serverless");
params.setPayType("Serverless");
params.setAutoPause(false);
params.setSwitchForce(true);
params.setMaxCapacity(8);
params.setMinCapacity(0.5);
ModifyDBInstanceSpec.modify(params);
}
}Cron expression quick reference:
| Cron expression | Meaning |
|---|---|
0 50 7 * * ? | Every day at 07:50:00 |
0 0 8 * * ? | Every day at 08:00:00 |
0 0 9 * * ? | Every day at 09:00:00 |
Key parameters:
| Parameter | Description | Example |
|---|---|---|
RegionId | Region ID of the instance | cn-hangzhou |
DBInstanceId | Instance ID | rm-bp1t8v93k6e15**** |
PayType | Billing method | Serverless |
Direction | Specification change type | Serverless |
MaxCapacity | Maximum number of RCUs | 8.0 |
MinCapacity | Minimum number of RCUs | 0.5 (default) / 4 (peak) |
AutoPause | Enable automatic start and stop | false |
SwitchForce | Enable forced scaling | true |
What's next
ModifyDBInstanceSpec API reference