Serverless ApsaraDB RDS for MySQL scales RDS Capacity Units (RCUs) automatically based on workload. Most scale-ups complete within seconds, but inter-host scale-ups — triggered when the current host runs out of capacity — can take 3 to 5 minutes. To guarantee stability during a known peak window, schedule RCU adjustments in advance rather than relying on reactive auto scaling.
How it works
The instance scales up automatically when CPU utilization or memory usage reaches 60%–80%. Two types of scale-ups are possible:
| Scale-up type | Duration | When it occurs |
|---|---|---|
| Intra-host | Seconds | Host has spare capacity (99.8% of cases) |
| Inter-host | 3–5 minutes | Host cannot provide sufficient resources |
Because an inter-host scale-up takes several minutes, starting it reactively — after CPU or memory pressure builds — can leave your instance under-resourced during that window. Scheduling a minimum RCU increase before the peak period starts ensures the instance is already at capacity when traffic arrives.
Solution
Call ModifyDBInstanceSpec on a schedule to raise the minimum and maximum RCUs before your peak period and restore the default configuration afterward.
Recommended approach: Set both MinCapacity and MaxCapacity to the same value during the peak period. This prevents any automatic scale-up from being triggered mid-window, eliminating the risk of an inter-host scale-up while your workload is at its highest.
Sample code in Python
This example uses APScheduler with a BlockingScheduler and cron triggers.
Set up
Install APScheduler:
pip install apschedulerDownload the SDK sample code from OpenAPI Explorer:
Go to the ModifyDBInstanceSpec page in OpenAPI Explorer.
On the Parameters tab, set the following values:
Parameter Value DBInstanceId rm-bp1t8v93k6e15**** PayType Serverless Direction Serverless MaxCapacity 8.0 MinCapacity 0.5 AutoPause false SwitchForce true On the SDK Sample Code tab, select Python for Languages and click Download Project.
Download the SDK V2.0 sample project.
Extract the package and go to the
_alibabacloud_sample_directory.
Configure the scheduled task
Add the APScheduler scheduler to sample.py. The example below sets the RCU range to [4, 8] at 07:50 and restores it to [0.5, 8] at 09:00 every day:
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
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 more information about endpoints, visit https://api.aliyun.com/product/Rds.
config.endpoint = f'rds.aliyuncs.com'
return Rds20140815Client(config)
# Call an API operation to modify the configuration of the serverless RDS instance.
@staticmethod
def modify_db_instance_spec(config: Dict[str, float]) -> None:
"""
Modify DB instance spec - the core task function
"""
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:
# Handle exceptions with caution in your actual business scenario. Do not ignore exceptions in your project. In this example, error messages are printed to the screen.
print(error.message)
print(error.data.get("Recommend"))
UtilClient.assert_as_string(error.message)
@staticmethod
def main(args: List[str]) -> None:
"""
:rtype: object
"""
# Initialize the scheduler.
scheduler = BlockingScheduler()
# RCU range [4, 8] for the 08:00-09:00 peak window.
config_8am = {
'max_capacity': 8,
'min_capacity': 4,
'auto_pause': False,
'switch_force': True
}
# Default RCU range [0.5, 8] after the peak window ends.
config_9am = {
'max_capacity': 8,
'min_capacity': 0.5,
'auto_pause': False,
'switch_force': True
}
# At 07:50, apply the peak configuration (10 minutes before the window opens).
scheduler.add_job(Sample.modify_db_instance_spec, 'cron', hour=7, minute=50, args=[config_8am])
# At 09:00, restore the default configuration.
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:])The scheduler.add_job calls use a cron trigger. For example, 'cron', hour=7, minute=50 fires at 07:50:00 every day. Adjust the hour and minute values to match your peak window.
Sample code in Java
This example uses Spring Schedule.
Java 1.8 or later is required.
Set up
Create a RAM user and grant permissions and configure environment variables.
Download and extract demo.zip.
Configure the scheduled task
Edit ScheduleTask.java to define your schedule using the cron expression format "Second Minute Hour Day Month Week". For details on the cron expression syntax, see the Spring @Scheduled Javadoc).
The example below sets the RCU range to [4, 8] at 07:50 and restores it to [0.5, 8] at 09:00 every day:
package com.example.demo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduleTask {
// At 07:50:00 — apply peak configuration (10 minutes before the window opens).
@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:00 — restore the default configuration.
@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);
}
}Replace the placeholder values with your own:
| 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 |
| AutoPause | Whether to enable automatic start and stop | false |
| SwitchForce | Whether to enable forced scaling | true |
Example: reserve 4–8 RCUs during a peak hour
To guarantee 4–8 RCUs from 08:00 to 09:00 every day:
At 07:50, raise
MinCapacityto 4 (and keepMaxCapacityat 8). The 10-minute lead time allows any inter-host scale-up to complete before the peak window opens.At 09:00, restore the default configuration:
MinCapacity0.5,MaxCapacity8.
The following sections show how to implement this schedule in Python and Java.
Prerequisites
Before you begin, ensure that you have:
Configured environment variables (
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET)