# rds-backup

Part of **RDS**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Backup and restore database data](../../intent/rds-backup-database/SKILL.md). If you're unsure which path to take, check the routing skill first.

# ApsaraDB RDS Backup and Restore

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|--------|----------|------|
| Backup Database Instance | Synchronous | Create, modify, query, and delete backup sets and backup configurations for RDS instances. |
| Cross-Region Backup and Restore | Synchronous | Manage cross-region backup settings, query cross-region backup files, and restore data across regions. |
| Describe Snapshot Details | Synchronous | Retrieve detailed information about RDS snapshots. |
| Manage Snapshots | Synchronous | Create, describe, or delete snapshots of RDS instances. |
| Create Backup | Synchronous | Create a manual backup of an RDS instance. |
| Delete Backup | Synchronous | Delete backup files or entire backups. |
| Manage Backup Policy | Synchronous | Query and modify backup policies including retention settings. |
| Query Backups | Synchronous | List and describe various types of backups including detached and cross-region backups. |
| Query Backup Tasks | Synchronous | Get information about ongoing or completed backup tasks. |
| Query Binlog Files | Synchronous | Retrieve binary log files for point-in-time recovery. |
| Manage Cross-Region Backup | Synchronous | Configure and query cross-region backup settings and metadata. |
| Restore Data | Synchronous | Restore data across regions or from backups. |

## API Calling Mode

### Authentication
The primary authentication method is bearer token authentication.

- Header format: `Authorization: Bearer <your_api_key>`
- Environment variable: `DASHSCOPE_API_KEY`

### Service Endpoint
The base URL for all RDS Backup and Restore APIs is region-specific.

- Endpoint pattern: `https://rds.aliyuncs.com/`
- Common regions: `cn-hangzhou`, `cn-shanghai`, `cn-beijing`

### Synchronous API Pattern
All RDS Backup and Restore APIs follow a synchronous calling pattern:
1. Send an HTTP request to the service endpoint with required parameters
2. Include authentication in the `Authorization` header
3. Receive an immediate JSON response with results or error details
4. Parse the response to extract relevant information (e.g., backup IDs, task status)

For operations that may take longer to complete (like creating large backups), the API returns a job ID that can be used with query operations to check status.

## Parameter Reference

### Backup Database Instance

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| Action | String | true | null | null | The operation that you want to perform. Set the value to CreateBackup. |
| DBInstanceId | String | true | null | null | The ID of the instance. |
| DBName | String | false | null | null | The names of the databases whose data you want to back up. Separate the names of the databases with commas (,). |
| BackupStrategy | String | false | null | one of: db, instance | The policy that you want to use for the backup file. Valid values: db (database-level backup), instance (instance-level backup). |
| BackupMethod | String | false | Physical | one of: Logical, Physical, Snapshot | The type of backup that you want to perform. Valid values: Logical, Physical, Snapshot. Default value: Physical. |
| BackupType | String | false | Auto | one of: Auto, FullBackup | The backup method. Valid values: Auto (system determines full or incremental), FullBackup (full backup). Default value: Auto. |
| ResourceGroupId | String | false | null | null | The ID of the resource group. |

### Cross-Region Backup and Restore

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| Action | String | true | null | Must be exactly 'DescribeInstanceCrossBackupPolicy' | The value of this required parameter must be DescribeInstanceCrossBackupPolicy. |
| DBInstanceId | String | true | null | null | The instance ID. |
| RegionId | String | true | null | null | The region ID. You can call the DescribeRegions operation to query the region ID. |
| CrossBackupRegion | String | false | null | null | The ID of the destination region where the cross-region backup files of the instance are stored. |
| Retention | Integer | false | null | range 7-1825 | The number of days for which the cross-region backup files of the instance are retained. Valid values: 7 to 1825. |
| BackupEnabled | String | false | null | one of: 0, 1 | Specifies whether to enable the cross-region backup feature on the instance. Valid values: 0 (disables), 1 (enables). |
| LogBackupEnabled | String | false | null | one of: 0, 1 | Specifies whether to enable the cross-region log backup feature on the instance. Valid values: 0 (disables), 1 (enables). |

### Manage Snapshots

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| RegionId | String | true | null | null | The region ID. |
| DiskId | String | false | null | null | The cloud disk ID. |
| Description | String | false | "" | 2-256 characters, cannot start with http:// or https:// | The snapshot description. The description must be 2 to 256 characters in length and cannot start with http:// or https://. |
| RetentionDays | Integer | false | null | 1 to 65536 days | The retention period of the snapshot. Valid values: 1 to 65536. Unit: days. The snapshot is automatically released when its retention period expires. |
| SnapshotId | String | true | null | null | The snapshot ID. |
| Force | Boolean | false | false | one of: true, false | Specifies whether to forcefully delete the snapshot that is used to create cloud disks. Valid values: true (forces deletion; cloud disks created from the snapshot cannot be re-initialized), false (default; does not force deletion). |

### Restore Data

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| RegionId | String | true | null | null | The region ID of the destination instance. You can call the DescribeRegions operation to query the most recent region list. |
| Engine | String | true | null | one of: MySQL, SQLServer, PostgreSQL | The database engine of the destination instance. Valid values: MySQL, SQLServer, PostgreSQL. |
| EngineVersion | String | true | null | Valid values depend on Engine | The major engine version of the destination instance. The value varies based on the Engine parameter. |
| DBInstanceClass | String | true | null | null | The instance type of the destination instance. For more information, see Primary ApsaraDB RDS instance types. |
| DBInstanceStorage | Integer | true | null | range 5-2000 | The storage capacity of the destination instance. Valid values: 5 to 2000 GB. Must be a multiple of 5 GB. |
| RestoreType | String | true | null | one of: BackupSet, BackupTime | The method used to restore data. Valid values: BackupSet (from backup set), BackupTime (to point in time). |
| BackupSetId | String | false | null | null | The ID of the backup set used for restoration. Required if RestoreType is BackupSet. |
| RestoreTime | String | false | null | ISO 8601 UTC format: yyyy-MM-ddTHH:mm:ssZ | The point in time to which you want to restore data. Must be earlier than current time, in ISO 8601 UTC format (yyyy-MM-ddTHH:mm:ssZ). |

## Code Examples

### Create a manual backup - Python - cn-hangzhou

```python
import requests
import json

# Replace with your actual API key
API_KEY = 'your_api_key'

# Endpoint URL
url = 'https://rds.aliyuncs.com/api/v1/CreateBackup'

# Request headers
headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

# Request body
payload = {
    'DBInstanceId': 'rm-uf6wjk5****',
    'BackupMethod': 'Physical',
    'BackupType': 'FullBackup'
}

# Make the request
response = requests.post(url, headers=headers, data=json.dumps(payload))

# Check response
if response.status_code == 200:
    print('Success:', response.json())
else:
    print('Error:', response.status_code, response.text)
```

### Query backup sets - Python - cn-hangzhou

```python
import requests
import json

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

# Set up headers with authentication
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Define the request parameters
params = {
    "DBInstanceId": "rm-uf6wjk5****",
    "StartTime": "2011-06-01T16:00Z",
    "EndTime": "2011-06-15T16:00Z",
    "PageSize": 30,
    "PageNumber": 1
}

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

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

### Create a cross-region disaster recovery instance - Python - cn-hangzhou

```python
import json
import requests

# Set up the API endpoint and headers
url = "https://rds.aliyuncs.com/api/v1/CreateDdrInstance"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

# Define the request body
payload = {
    "RegionId": "cn-hangzhou",
    "Engine": "MySQL",
    "EngineVersion": "5.6",
    "DBInstanceClass": "rds.mysql.s1.small",
    "DBInstanceStorage": 20,
    "SystemDBCharset": "utf8",
    "DBInstanceNetType": "Intranet",
    "DBInstanceDescription": "testdb",
    "SecurityIPList": "127.0.0.1",
    "PayType": "Prepaid",
    "UsedTime": "2",
    "Period": "Year",
    "RestoreType": "BackupSet",
    "BackupSetId": "14****",
    "BackupSetRegion": "cn-beijing"
}

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

# Handle the response
if response.status_code == 200:
    print("Instance created successfully")
    print(response.json())
else:
    print(f"Error: {response.status_code} - {response.text}")
```

### Query snapshot details - Python - cn-hangzhou

```python
import requests

url = "https://rds.aliyuncs.com/api/v1/DescribeRCSnapshots"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "RegionId": "cn-hangzhou",
    "DiskId": "rcd-wz9c8isqly8637zw****",
    "PageSize": 30,
    "PageNumber": 1
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

### Delete backup files - Bash - all regions

```bash
curl -X GET \
  'https://rds.aliyuncs.com/?Action=DeleteBackup&DBInstanceId=rm-uf6wjk5xxxxxxx&BackupId=324909958&<Common request parameters>' \
  -H 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

### Query cross-region backup settings - Python - cn-hangzhou

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

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

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

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

### Query binlog files for point-in-time recovery - Python - all regions

```python
import requests
import json

# Replace with your actual API endpoint and credentials
url = "https://rds.aliyuncs.com/api/v1/DescribeBinlogFiles"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

params = {
    "DBInstanceId": "rm-uf6wjk5****",
    "StartTime": "2011-06-01T15:00:00Z",
    "EndTime": "2011-06-20T15:00:00Z",
    "PageSize": 30,
    "PageNumber": 1
}

response = requests.get(url, headers=headers, params=params)

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

### Check cross-region restore capability - Python - all regions

```python
import requests

url = "https://rds.aliyuncs.com/"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "Action": "CheckCreateDdrDBInstance",
    "RegionId": "cn-hangzhou",
    "Engine": "MySQL",
    "EngineVersion": "5.6",
    "DBInstanceClass": "rds.mysql.s1.small",
    "DBInstanceStorage": 20,
    "RestoreType": "0",
    "BackupSetId": "14358"
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

## Response Format

```json
{
  "RequestId": "2C125605-266F-41CA-8AC5-3A643D4F42C5",
  "BackupJobId": "5073731"
}
```

**Key Fields**:
- `RequestId` — Unique identifier for the API request
- `BackupJobId` — Identifier for the backup job that was created
- `DBInstanceId` — The ID of the RDS instance being operated on
- `Items` — Contains lists of backup sets, snapshots, or other resources
- `TotalRecordCount` — Total number of records matching the query criteria

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|---------------|--------------------|-----------------------------|
| 400 | Invalid parameter error. Check the input parameters such as Action, BackupId, and DBInstanceId. | Verify all required parameters are included and formatted correctly according to the API specification. |
| 400 | The specified backup retention period is invalid. The backup cycle must be greater than 1 day or less than or equal to 30 days. | Ensure the backup retention period is within the valid range (7-730 days for most operations). |
| 400 | Snapshot backup does not support cross region storage at present. Please turn off cross region backup before switching to snapshot backup mode. | Disable cross-region backup before enabling snapshot backup mode. |
| 403 | operation not permitted. The error message returned because the current operation is not supported. | Check if the operation is supported for your instance type, engine version, and current state. |
| 403 | Current DB instance state does not support this operation. | Ensure the RDS instance is in a running state before performing backup operations. |
| 404 | Specified instance does not exist or is not accessible. | Verify the DBInstanceId is correct and the instance exists in the specified region. |
| 404 | Specified backup set ID does not exist. | Confirm the backup set ID is valid and belongs to the specified instance. |
| 500 | Internal server error. Try again later or contact support. | Retry the request after a short delay. If the error persists, contact Alibaba Cloud support. |

### Rate Limits & Retry
- The number of backup files that are created per day for an instance cannot exceed 20.
- Most query operations have a limit of 100 QPS (queries per second).
- For failed requests with 5xx errors, implement exponential backoff retry logic with a maximum of 3 retries.
- For 429 Too Many Requests errors (not explicitly documented but possible), wait for the Retry-After header duration before retrying.

## Requirements

- Environment variable setup: `export DASHSCOPE_API_KEY=your_key`
- For Python SDK usage, install the Alibaba Cloud SDK: `pip install aliyun-python-sdk-core aliyun-python-sdk-rds`

## FAQ

Q: How do I enable cross-region backup for my RDS instance?
A: Use the ModifyInstanceCrossBackupPolicy API with BackupEnabled set to "1" and specify the CrossBackupRegion parameter with your desired destination region. You can query available regions using the DescribeAvailableCrossRegion API first.

Q: What's the difference between physical and logical backups in RDS?
A: Physical backups copy the actual database files and are faster to create and restore. Logical backups export the database as SQL statements and are more portable but slower. The choice depends on your recovery time objectives and whether you need to restore to different database versions.

Q: Can I restore individual databases or tables from a backup?
A: Yes, for supported RDS MySQL instances, you can restore individual databases or tables by specifying the TableMeta parameter in the RestoreDdrTable API. The backup must be in xbstream format and the feature must be activated for your instance.

Q: How long are backup files retained by default?
A: Data backup files are retained for 7 days by default, but this can be configured between 7-730 days using the BackupRetentionPeriod parameter in backup policies. Cross-region backups have a separate retention period configurable between 7-1825 days.

Q: What happens if I try to create more than 20 backups per day for an instance?
A: The API will return an error indicating the daily backup limit has been exceeded. This limit exists to prevent excessive resource consumption and ensure system stability.

## Pricing & Billing

### Billing Model
Most RDS Backup and Restore APIs are billed per request, with some operations having free tiers.

### Price Reference

| Model/Specification | Input Price | Output Price | Other Fees |
|-----------|---------|---------|---------|
| default | 0.001 / | 0.001 / |
| standard | 0.002 / | 0.002 / |
| cross_region_backup_query | 0.001 / | |
| rds.mysql.s1.small | 0.002 / | 0.002 / |

### Free Tier
- Query backup settings: Free calls with no quota limits
- Query backup tasks: 1000 free calls per month
- Query detached backups: 100 free calls per month
- DescribeRCSnapshots: 100 free calls per month

### Usage Limits
- CreateBackup: Maximum 20 backup files per instance per day
- DeleteBackup: Maximum 100 backup set IDs per request
- Most query operations: 100 QPS rate limit
- Cross-region operations: 10 requests per second maximum

### Billing Notes
- API calls are billed per request regardless of success or failure
- Cross-region data transfer may incur additional network fees
- Backup storage costs are separate from API call costs
- Some operations like CreateDdrInstance are billed based on the created instance's hourly rate rather than per API call