All Products
Search
Document Center

ApsaraDB RDS:Schedule the configuration of RCUs for a serverless instance

Last Updated:Mar 30, 2026

Serverless ApsaraDB RDS for MySQL automatically scales RDS Capacity Units (RCUs) based on CPU utilization and memory usage. In 99.8% of cases, scale-ups complete within seconds (intra-host). However, when the current host cannot supply enough resources, an inter-host scale-up is required — this takes 3 to 5 minutes and may affect your workloads. To prevent this from affecting a known busy window, use a scheduled task to raise the RCU minimum before traffic peaks.

How it works

Auto scaling triggers a scale-up when CPU utilization or memory usage reaches 60%–80%. Two types of scale-ups are possible:

Scale-up type Duration Connection impact Frequency
Intra-host Seconds None 99.8% of cases
Inter-host 3–5 minutes May affect your workloads When host cannot supply enough resources

Setting MinCapacity and MaxCapacity to the same value pins the instance at a fixed capacity for a time window, eliminating scale-up risk during that period.

The scheduled task calls the ModifyDBInstanceSpec API to raise MinCapacity before a busy period starts, then restores the original values when it ends.

Use cases

  • Protect a known peak window: Reserve a fixed RCU range during a predictable busy period (for example, a batch job or business-hours peak) to eliminate inter-host scale-up risk.

Example scenario

Reserve 4–8 RCUs during a peak hour from 08:00 to 09:00. Because an inter-host scale-up can take up to 5 minutes, raise the minimum 10 minutes early — at 07:50. Restore the default range (0.5–8 RCUs) at 09:00.

image

The two scheduled jobs use the following parameters:

Time MinCapacity MaxCapacity Effect
07:50 4 8 Raises the minimum 10 min before peak; triggers inter-host scale-up if needed
09:00 0.5 8 Restores the default range after the peak window

Prerequisites

Before you begin, ensure that you have:

Schedule the task in Python

This example uses APScheduler with a BlockingScheduler and cron triggers.

Set up

  1. Install Python and install the Alibaba Cloud SDK dependencies.

  2. Install APScheduler:

    pip install apscheduler
  3. Download the SDK sample project for ModifyDBInstanceSpec:

    1. Open the ModifyDBInstanceSpec page in OpenAPI Explorer.

    2. 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
    3. On the SDK Sample Code tab, select Python from the Languages dropdown and click Download Project. > Note: Download the SDK V2.0 sample project.

    4. Decompress the package and open the _alibabacloud_sample_ directory.

Configure the scheduled task

Add the content of the APScheduler scheduled task to the sample.py file and use a cron trigger to configure the execution time. The cron trigger hour=7, minute=50 fires at 07:50 every day; hour=9, minute=0 fires at 09:00.

# -*- 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, use temporary access credentials 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 the ModifyDBInstanceSpec API to update the serverless RDS instance configuration.
    @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:
        # Initialize the scheduler.
        scheduler = BlockingScheduler()

        # RCU range for 08:00-09:00 peak: min=4, max=8.
        # Scheduled at 07:50 to allow inter-host scale-up to complete before peak starts.
        config_8am = {
            'max_capacity': 8,
            'min_capacity': 4,
            'auto_pause': False,
            'switch_force': True
        }

        # Default RCU range restored after peak: min=0.5, max=8.
        config_9am = {
            'max_capacity': 8,
            'min_capacity': 0.5,
            'auto_pause': False,
            'switch_force': True
        }

        # Create scheduled tasks using cron triggers.
        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:])

Replace rm-bp1t8v93k6e15**** with your actual instance ID. The hour and minute values in scheduler.add_job follow 24-hour time; adjust them to match your peak window.

Schedule the task in Java

This example uses Spring Schedule. Java 1.8 or later is required.

Set up

  1. Complete the RAM user and environment variable prerequisites.

  2. Download the demo.zip sample package and decompress it to your local machine.

Configure the scheduled task

Open ScheduleTask.java and update the cron expressions and parameters to match your peak window. The cron format is "Second Minute Hour Day Month Week". For example, @Scheduled(cron = "0 0 8 * * ? ") fires at 08:00:00 every day.

The following code sets the RCU range to [4, 8] at 07:50 and restores [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 {

    @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);
    }

    @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);
    }
}

Adjust the following parameters to match your environment and requirements:

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

For cron expression syntax, see the Spring @Scheduled annotation reference).

What's next