All Products
Search
Document Center

ApsaraDB RDS:Configure scheduled tasks to adjust the number of RCUs for a serverless RDS instance

更新時間:Aug 13, 2024

In most cases, the RDS Capacity Unit (RCU) scaling for a serverless ApsaraDB RDS for MySQL instance can be complete within seconds. In some cases, the RCU scaling may require 3 to 5 minutes to complete due to inter-host scale-ups. If you have strict requirements on stability within a specific period of time, you can configure scheduled tasks to adjust the number of RCUs for your serverless RDS instance. This topic describes how to configure scheduled tasks to adjust the number of RCUs.

Scenarios

  • The system performs auto scaling on a serverless RDS instance based on the CPU utilization and memory usage. If the CPU utilization or memory usage falls into the range of 60% to 80%, automatic scale-ups are triggered. If you have high requirements on stability of the CPU or memory resources within a specific period of time, you must adjust the minimum number of RCUs in advance.

  • Intra-host scale-ups and inter-host scale-ups are supported. Intra-host scale-ups can be complete within seconds, and inter-host scale-ups can be complete within 3 to 5 minutes. In 99.8% of scenarios, intra-host scale-ups can meet your business requirements. If the host on which the serverless RDS instance resides cannot provide sufficient resources, you must scale up the RCUs across hosts. An inter-host scale-up requires a long period of time to complete, which may affect your workloads. We recommend that you set the maximum number and minimum number of RCUs to the same value for specific periods of time to prevent the impacts caused by the automatic scale-up failure.

Solutions

Create a scheduled task to call the ModifyDBInstanceSpec operation to modify the maximum number and minimum number of RCUs within a specific period of time. After the period of time elapses, the modification is rolled back.

Examples

If you want to increase the minimum number of RCUs for a specific period of time, we recommend that you create a scheduled task to increase the minimum number of RCUs 10 minutes before the period of time. If an inter-host scale-up is required, this allows the inter-host scale-up to complete and ensures the instance stability within the period of time.

For example, if you want to reserve 4 to 8 RCUs during the peak hour from 08:00 to 09:00, you can increase the minimum number of RCUs to 4 at 07:50 and restore the configuration to the default configuration of 0.5 to 8 RCUs at 09:00.

image

Sample code in Python

This section provides an example on how to use APScheduler to configure a scheduled task. For more information, see User guide.

  1. Complete the following operations:

    1. Create a RAM user and grant permissions to the RAM user.

    2. Install Python.

    3. Configure environment variables.

    4. Install dependencies.

  2. Open the CLI and run the following command to install APScheduler:

    pip install apscheduler
  3. Download the sample code.

    1. Go to the Debugging page of ModifyDBInstanceSpec in OpenAPI Explorer.

    2. On the Parameters tab, configure the following parameters.

    3. Parameter

      Description

      Value

      DBInstanceId

      The instance ID.

      rm-bp1t8v93k6e15****

      PayType

      The billing method of the instance.

      Serverless

      Direction

      The specification change type of the instance.

      Serverless

      MaxCapacity

      The maximum number of RCUs.

      8.0

      MinCapacity

      The minimum number of RCUs.

      0.5

      AutoPause

      Specifies whether to enable the automatic start and stop feature for the serverless RDS instance.

      false

      SwitchForce

      Specifies whether to enable the forced scaling feature for the serverless RDS instance.

      true

    4. On the SDK Sample Code tab, select Python for Languages and click Download Project to download the sample code package.

    5. Note

      We recommend that you download the sample project of SDK V2.0.

    6. Decompress the package on your on-premises device and go to the alibabacloud_sample directory.

  4. Modify the code to 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 of the scheduled task. For example, the scheduler.add_job(my_scheduled_job, 'cron', hour=8, minute=0) setting indicates that the task is automatically executed at 08:00:00 every day. The following sample code shows how to set the RCU scaling range to [4, 8] at 07:50 every day and restore the RCU scaling range to [0.5, 8] at 09:00 every day:

    sample.py

    # -*- 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()
    
            # Configure the parameters of the serverless RDS instance to meet the requirements for 8:00.
            config_8am = {
                'max_capacity': 8,
                'min_capacity': 4,
                'auto_pause': False,
                'switch_force': True
            }
    
            # Configure the parameters of the serverless RDS instance to meet the requirements for 9:00.
            config_9am = {
                'max_capacity': 8,
                'min_capacity': 0.5,
                'auto_pause': False,
                'switch_force': True
            }
    
            # Create a scheduled task.
            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:])
    
    

Sample code in Java

This section provides an example on how to use Spring Schedule to configure a scheduled task.

Note

In this example, you must install Java 1.8 or later.

  1. Complete the following operations:

    1. Create a RAM user and grant permissions to the RAM user.

    2. Configure environment variables.

  2. Download the sample package and decompress the package to your on-premises device.

    For more information about the sample package, see demo.zip.

  3. Modify the content of ScheduleTask.java and configure the scheduled task based on your business requirements.

    Configure a CRON expression to specify the execution time of the scheduled task. cron = "Second Minute Hour Day Month Week" is a CRON expression. For more information, see Cron.

    For example, @Scheduled(cron = "0 0 8 * * ? ") represents 08:00:00 every day. The following sample code shows how to set the RCU scaling range to [4, 8] at 07:50 every day and restore the RCU scaling range to [0.5, 8] at 09:00 every day:

    ScheduleTask.java

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

    The following table describes some parameters. You can change the values of the parameters based on your business requirements.

    Parameter

    Description

    Example

    RegionId

    The region ID of the instance.

    cn-hangzhou

    DBInstanceId

    The instance ID.

    rm-bp1t8v93k6e15****

    PayType

    The billing method of the instance.

    Serverless

    Direction

    The specification change type of the instance.

    Serverless

    MaxCapacity

    The maximum number of RCUs.

    8.0

    MinCapacity

    The minimum number of RCUs.

    0.5

    AutoPause

    Specifies whether to enable the automatic start and stop feature for the serverless RDS instance.

    false

    SwitchForce

    Specifies whether to enable the forced scaling feature for the serverless RDS instance.

    true