# rds-billing

Part of **RDS**

# ApsaraDB RDS Billing and Cost Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Query Pricing | Synchronous | Queries the price of an ApsaraDB RDS instance based on specified parameters such as database engine, instance type, storage capacity, and billing method. |
| Manage Renewal | Synchronous | Manually renews an ApsaraDB RDS instance and manages auto-renewal settings. |
| Change Billing Method | Synchronous | Switches between subscription and pay-as-you-go billing models for ApsaraDB RDS instances. |
| Claim Coupon | Synchronous | Claims a coupon for ApsaraDB RDS using activity ID, promotion ID, and region ID. |

## API Calling Pattern

### Authentication
The primary authentication method is Bearer Token authentication.

- Include the header: `Authorization: Bearer <your_api_key>`
- Set the environment variable: `DASHSCOPE_API_KEY`
- While other authentication methods may exist, Bearer Token is recommended for simplicity and consistency across Alibaba Cloud services.

### Service Endpoint (Endpoint)
The APIs use region-specific endpoints with the following pattern:

`https://rds.{region}.aliyuncs.com`

Common regions include:
- `cn-hangzhou`
- `cn-shanghai`
- `cn-beijing`

For international sites, use `https://rds.alibabacloud.com/` as the base endpoint.

### Synchronous API Pattern
All billing and cost management APIs in this domain follow a synchronous calling pattern:

1. Construct a POST or GET request with required parameters
2. Include authentication headers
3. Send the request to the appropriate regional endpoint
4. Receive an immediate JSON response with results or error details
5. Parse the response to extract relevant information (e.g., pricing details, order IDs, renewal status)

No polling or streaming is required as all operations complete immediately.

## Parameter Reference

### Query Pricing

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| ClientToken | string | false | null | max 64 characters, ASCII only | The client token that is used to ensure the idempotence of the request. |
| CommodityCode | string | false | rds | one of: bards, rds, rords, rds_rordspre_public_cn, bards_intl, rds_intl, rords_intl, rds_rordspre_public_intl | The commodity code of the instance. |
| RegionId | string | false | null | null | The region ID. You can call the DescribeRegions operation to query the most recent region list. |
| Engine | string | true | null | one of: MySQL, SQLServer, PostgreSQL, MariaDB | The database engine of the instance. |
| EngineVersion | string | true | null | MySQL: 5.5, 5.6, 5.7, 8.0; SQLServer: 08r2_ent_ha, 2008r2, 2012, 2016, 2017, 2019, 2022; PostgreSQL: 10.0, 11.0, 12.0, 13.0, 14.0, 15.0; MariaDB: 10.3 | The database engine version of the instance. |
| DBInstanceClass | string | true | null | null | The instance type of the instance. |
| DBInstanceStorage | integer | true | null | step size 5 GB | The storage capacity of the instance. Unit: GB. |
| PayType | string | false | null | one of: Prepaid, Postpaid | The billing method of the instance. |
| ZoneId | string | false | null | null | The zone ID of the primary instance. |
| UsedTime | integer | false | 1 | range 1-100 (Year), 1-999 (Month) | The subscription duration of the instance. |
| TimeType | string | false | null | one of: Year, Month | The billing cycle of the subscription instance. |
| Quantity | integer | true | null | range 0-30 | The number of instances that you want to purchase. |
| InstanceUsedType | integer | false | null | one of: 0, 3 | The role of the instance. |
| OrderType | string | false | null | one of: BUY, RENEW, UPGRADE, DOWNGRADE | The order type. |
| DBInstanceStorageType | string | false | null | one of: general_essd, local_ssd, cloud_ssd, cloud_essd, cloud_essd2, cloud_essd3 | The storage type of the new instance. |
| DBInstanceId | string | false | null | null | The ID of the instance for which you want to change the specifications or the instance that you want to renew. |

### Manage Renewal

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| ClientToken | string | false | null | max 64 characters, ASCII only | The client token that is used to ensure the idempotence of the request. |
| DBInstanceId | string | true | null | null | The instance ID. |
| Period | integer | true | null | 1-9, 12, 24, 36, 48, 60 | The duration of the subscription renewal. Unit: month. |
| AutoPay | string | false | False | True, False | Specifies whether to enable automatic payment during the renewal. |
| AutoRenew | string | false | false | true, false | Specifies whether to enable auto-renewal for the instance. |
| AutoUseCoupon | boolean | false | false | true, false | Specifies whether to use a coupon. |
| PromotionCode | string | false | null | null | The coupon code. |

### Change Billing Method

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| DBInstanceId | string | true | null | null | The instance ID. |
| UsedTime | integer | false | null | range 1-5 if Period=Year, range 1-11 if Period=Month | The subscription duration of the instance. |
| PayType | string | true | null | must be 'Prepaid' | The billing method of the instance. |
| Period | string | true | null | one of: 'Year', 'Month' | The renewal cycle of the instance. |
| ClientToken | string | false | null | max length 64 characters, only ASCII characters | The client token that is used to ensure the idempotence of the request. |
| BusinessInfo | string | false | null | null | The additional business information about the instance. |
| AutoRenew | string | false | null | one of: true, false | Specifies whether to enable the auto-renewal feature for the instance. |
| AutoUseCoupon | boolean | false | false | one of: true, false | Specifies whether to use vouchers to offset fees. |

### Claim Coupon

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| ActivityId | integer | true | null | null | The activity ID. |
| PromotionId | integer | true | null | null | The promotion ID. |
| RegionId | string | true | null | null | The region ID. |

## Code Examples

### Query Instance Price - Python - All Regions

```python
import json
import requests

# Set up the API endpoint
url = "https://rds.aliyuncs.com/"

# Set up the request headers
headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Bearer YOUR_API_KEY"
}

# Set up the request parameters
params = {
    "Action": "DescribePrice",
    "Version": "2014-08-15",
    "RegionId": "cn-hangzhou",
    "Engine": "MySQL",
    "EngineVersion": "8.0",
    "DBInstanceClass": "mysql.x2.medium.xc",
    "DBInstanceStorage": 20,
    "PayType": "Prepaid",
    "Quantity": 1,
    "ClientToken": "ETnLKlblzczshOTUbOCz****"
}

# Make the API request
response = requests.post(url, data=params, headers=headers)

# Parse the response
if response.status_code == 200:
    result = response.json()
    print(json.dumps(result, indent=2))
else:
    print(f"Error: {response.status_code} - {response.text}")
```

### Query Auto-Renewal Status - Python - All Regions

```python
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkrds.request.v20140815.DescribeInstanceAutoRenewalAttributeRequest import DescribeInstanceAutoRenewalAttributeRequest

# Initialize client
client = AcsClient('<your-access-key-id>', '<your-access-key-secret>', 'cn-hangzhou')

# Create request
request = DescribeInstanceAutoRenewalAttributeRequest()
request.set_DBInstanceId('rm-bp****')
request.set_RegionId('cn-hangzhou')
request.set_PageSize(30)
request.set_PageNumber(1)

# Send request
response = client.do_action_with_exception(request)
print(json.loads(response))
```

### Modify Auto-Renewal Settings - Python - All Regions

```python
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkrds.request.v20140815.ModifyInstanceAutoRenewalAttributeRequest import ModifyInstanceAutoRenewalAttributeRequest

# Initialize client
client = AcsClient('<your-access-key-id>', '<your-access-key-secret>', 'cn-hangzhou')

# Create request
request = ModifyInstanceAutoRenewalAttributeRequest()
request.set_DBInstanceId('rm-bp****')
request.set_AutoRenew('True')
request.set_Duration('2')
request.set_ClientToken('ETnLKlblzczshOTUbOCz****')

# Send request
response = client.do_action_with_exception(request)
print(response.decode('utf-8'))
```

### Modify Auto-Renewal Settings - curl - All Regions

```bash
curl -X POST https://rds.aliyuncs.com/ \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Authorization: Bearer <your-access-token>' \
  -d 'Action=ModifyInstanceAutoRenewalAttribute' \
  -d 'RegionId=cn-hangzhou' \
  -d 'DBInstanceId=rm-bp****' \
  -d 'AutoRenew=True' \
  -d 'Duration=2' \
  -d 'ClientToken=ETnLKlblzczshOTUbOCz****' \
  -d 'Version=2014-08-15'
```

### Query Auto-Renewal Status - bash - All Regions

```bash
curl -X GET 'https://rds.aliyuncs.com/?Action=DescribeInstanceAutoRenewalAttribute&DBInstanceId=rm-bp****&RegionId=cn-hangzhou&PageSize=30&PageNumber=1&SignatureMethod=HMAC-SHA1&SignatureVersion=1.0&AccessKeyId=your-access-key-id&Timestamp=2024-04-05T12:00:00Z&Signature=your-signature'
```

## Response Format

```json
{
  "OrderParams": "{\"autoPay\":false}",
  "PriceInfo": {
    "ActivityInfo": {
      "CheckErrMsg": "Error description",
      "ErrorCode": " 123456",
      "Success": "Success"
    },
    "Coupons": {
      "Coupon": [
        {
          "CouponNo": "123456",
          "Description": "test",
          "IsSelected": "true",
          "Name": "test"
        }
      ]
    },
    "Currency": "CNY",
    "DiscountPrice": 0,
    "OrderLines": "Order Information",
    "OriginalPrice": 10508,
    "RuleIds": {
      "RuleId": [
        "100119****"
      ]
    },
    "TradeMaxRCUAmount": 0,
    "TradeMinRCUAmount": 0,
    "TradePrice": 10508
  },
  "RequestId": "CA0ADDDC-0BEB-4381-A3ED-73B4C79B8CC6",
  "Rules": {
    "Rule": [
      {
        "Description": "Activity Description",
        "Name": "Rule1",
        "RuleId": 0
      }
    ]
  },
  "ServerlessPrice": {
    "RCUDiscountMaxAmount": 0,
    "RCUDiscountMinAmount": 0,
    "RCUOriginalMaxAmount": 0,
    "RCUOriginalMinAmount": 0,
    "StorageOriginalAmount": 0,
    "TotalOriginalMaxAmount": 0,
    "TotalOriginalMinAmount": 0,
    "TradeMaxRCUAmount": 0,
    "TradeMinRCUAmount": 0,
    "storageDiscountAmount": 0
  },
  "ShowDiscount": true,
  "TradeMaxRCUAmount": 0,
  "TradeMinRCUAmount": 0
}
```

**Key Fields**:
- `PriceInfo.OriginalPrice` — The original price before any discounts
- `PriceInfo.TradePrice` — The final price after applying discounts
- `PriceInfo.DiscountPrice` — The amount discounted from the original price
- `PriceInfo.Currency` — The currency used for pricing (e.g., CNY)
- `PriceInfo.Coupons` — Available coupons that can be applied
- `PriceInfo.ActivityInfo.Success` — Indicates if the pricing query was successful
- `PriceInfo.RuleIds.RuleId` — IDs of applicable pricing rules
- `ServerlessPrice.RCUOriginalMaxAmount` — Maximum original RCU amount for serverless instances
- `ServerlessPrice.RCUOriginalMinAmount` — Minimum original RCU amount for serverless instances
- `ServerlessPrice.TotalOriginalMaxAmount` — Maximum total original amount for serverless instances
- `ServerlessPrice.TotalOriginalMinAmount` — Minimum total original amount for serverless instances
- `ServerlessPrice.TradeMaxRCUAmount` — Maximum trade RCU amount for serverless instances
- `ServerlessPrice.TradeMinRCUAmount` — Minimum trade RCU amount for serverless instances
- `RequestId` — Unique identifier for the API request

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|-------------------|
| 400 | Bad Request. Indicates invalid input parameters. Check the parameters and retry. | Verify all required parameters are provided with correct values and formats. |
| 403 | Forbidden. Indicates insufficient permissions or account restrictions. Verify user permissions or contact customer service. | Check your account permissions and ensure you have the necessary access rights. |
| 404 | Not Found. Indicates requested resource or configuration not available. Verify the request parameters. | Confirm the instance ID and other resource identifiers are correct. |
| 500 | Internal Server Error. Indicates internal system failure. Retry later or contact support. | Wait a few minutes and retry the request. If the issue persists, contact Alibaba Cloud support. |

## Environment Requirements

- Set the environment variable: `export DASHSCOPE_API_KEY=your_api_key`
- For Python SDK usage, install the required packages: `pip install aliyun-python-sdk-core aliyun-python-sdk-rds`
- For direct HTTP requests, ensure you have a tool like `curl` or a library like `requests` in Python

## FAQ

Q: How do I authenticate my API requests to the RDS Billing APIs?
A: Use Bearer Token authentication by including the header `Authorization: Bearer <your_api_key>` in your requests. Set your API key in the `DASHSCOPE_API_KEY` environment variable.

Q: Can I get pricing information for both subscription and pay-as-you-go instances?
A: Yes, the DescribePrice API supports both billing methods. Set the `PayType` parameter to "Prepaid" for subscription or "Postpaid" for pay-as-you-go.

Q: What happens if I try to renew an instance that's already set to auto-renew?
A: The RenewInstance API will still process your manual renewal request regardless of the auto-renewal setting. The auto-renewal configuration remains unchanged unless you explicitly modify it using ModifyInstanceAutoRenewalAttribute.

Q: Are there any limitations when changing billing methods?
A: Yes, there are several limitations: read-only instances don't support billing method changes, there must be a 15-minute interval between conversion operations, and your account must have sufficient balance and proper payment methods configured.

Q: How do I apply a coupon to my order?
A: First, claim a coupon using CreateYouhuiForOrder with the required activity ID, promotion ID, and region ID. Then, when making a purchase or renewal request, include the `AutoUseCoupon=true` parameter to automatically apply available coupons.

## Pricing & Billing

### Billing Model
Most operations follow a per-request billing model, while some pricing-related queries may be free. Instance operations (renewals, billing changes) incur charges based on the instance specifications and duration.

### Price Reference

| Tier/Specification | Input Price | Output Price | Other Fees |
|--------------------|-------------|--------------|------------|
| mysql.x2.medium.xc | 0.002 / | 0.002 / |
| Standard | 0.002 /tokens | 0.002 /tokens |
| Postpaid | 0.002 / | |
| Prepaid | 0.001 / | |
| default | 0.002 / | 0.002 / |

### Free Tier
- Monthly free quota of 1 million tokens for certain operations
- Some query operations may be free of charge

### Usage Limits
- Rate limits of 100 QPS for most operations
- Some operations limited to 10 requests per second

### Billing Notes
- Prices are calculated based on selected instance type, storage, and billing method
- Discounts and coupons may apply to reduce costs
- Subscription charges are billed upfront based on the selected term
- Pay-as-you-go charges are billed hourly based on actual usage
- Fees are generated for successful API calls that modify resources