Back to Terraform

Alibaba Data Services: RDS, PolarDB and Cache Recovery Contracts

November 6, 2026 Wasil Zafar 23 min read

Choose supported database infrastructure and keep schemas, credentials and data recovery separately governed

Table of Contents

  1. Choose the Persistence Contract Before the Product
  2. Verify Engine, Edition and Network Requirements
  3. Handle Accounts and Credentials with Explicit Persistence Boundaries
  4. Version Schema and Data Changes Outside Provisioning
  5. Prove Recovery for One Selected Service

Choose the Persistence Contract Before the Product

Start with the access pattern, not the engine name. Write down the five operations that carry the product, their predicates, and whether they join several entities. A workload that enforces constraints and changes shape under reporting wants a relational engine. A workload where every request names its key and tolerates a rebuild can use a cache, provided the key is not the only copy of something important.

RDS is the instance you size. You choose the engine, version, edition, class, storage type and zone, and you own the schema, the accounts and the restore. The high-availability edition adds a standby, but the unit that fails and resizes remains one database instance. The serverless edition changes the billing shape, not the ownership model.

PolarDB is the cluster you attach compute to. Storage is provisioned and billed as its own resource, and compute nodes attach to it behind a cluster endpoint. Scaling adds or removes nodes, and a clone creates a second cluster from a backup or timestamp rather than rewinding the first. That buys a faster recovery path at the cost of more objects to own.

A cache is a latency contract with a data-loss budget. KVStore covers Redis-compatible and Memcache engines, and it keeps the working set in memory. Persistence shortens a rebuild, the eviction policy decides what disappears under memory pressure, and backups decide whether a mistaken flush is recoverable. Sessions, queues and locks often live only there, making the cache a system of record.

The recovery contract is four numbers and one name. Record the recovery point objective, the recovery time objective, the retention that supports them, and the person who owns cutover. Do that before the first apply, because the product choice follows from those numbers.

The flow below keeps the stopping conditions visible, including the case where the honest answer is a different data model.

Choose the Persistence Contract Before the Product
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["List the five operations
that carry the product"] --> B{"Joins, constraints
or reporting shape changes?"} B -->|"yes"| C{"Load is steady and
the size is predictable?"} B -->|"no"| D{"Every operation names
its key?"} C -->|"yes"| E["RDS instance
you size class and storage"] C -->|"no"| F["PolarDB cluster
compute attached to shared storage"] D -->|"yes"| G{"Is the key the only copy
of anything important?"} D -->|"no"| H["Reshape the access pattern
before choosing a store"] G -->|"no"| I["Cache with eviction
and a rebuild path"] G -->|"yes"| J["Stop: add backup or
move it to a database"] E --> K["Write RPO, RTO, retention
and restore target"] F --> K I --> K J --> L["Prove a restore first,
then revisit the design"] H --> A classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,C,D,G primary; class E,F,I secondary; class K ok; class J danger; class H,L warn;

The plan owns the container, and the service owns the contents. The figure separates what an apply can rebuild from what needs a recovery procedure. Read it from the top down whenever someone proposes a change to the engine or the placement.

Three layers of an Alibaba Cloud data service with three different recovery routes Terraform declares the instance, cluster or cache plus its VSwitch, account and endpoint. The service enforces backup policy, deletion protection and parameters. Rows, cluster storage and cache keys sit below every plan and are recovered by cloning to a new endpoint, restoring a backup or accepting loss. Terraform declares the container; the service keeps the data Only the top layer is rebuilt by an apply. The bottom layer needs a restore you have performed. Configuration — declared in Terraform state RDS instance engine, edition, class, storage VSwitch and security group PolarDB cluster cluster, nodes and endpoint storage billed separately KVStore cache engine, class, shards VSwitch and whitelist Service policy — reviewed, not rebuilt Backup policy retention, window, log backup Deletion protection blocks destroy, not drift Parameters and whitelist static values need a restart Data plane — outside every plan Rows and binlog the only copy of the data Cluster storage survives a node replacement Keys and persistence files eviction is a data decision Clone to a new endpoint original keeps serving Restore from backup bounded by the backup window Delete or flush no undo without a retained copy

Each layer has a different owner and a different review. The top layer is reproducible from Git, the middle layer is a policy you can read but not own, and the bottom layer is the only one that needs a restore drill. A VSwitch replacement crosses all three at once.

Only a few decisions remain reversible after rows exist. Changing an engine family, replacing a cluster version, or flushing a cache is a migration project, not a configuration edit. The table compares the contracts you are choosing between.

DecisionRDS instancePolarDB clusterKVStore cache
Unit that scalesinstance class and storagecompute nodes plus provisioned storageinstance class, shards and replicas
Network placementVSwitch, security group and IP whitelistVSwitch, IP whitelist and security groupVSwitch, IP whitelist and security group
Backup controlretention window, log backup, on-demand backupcluster backup policy and level-2 archivebackup window and incremental log
Restore createsa new instance from backup or timestampa new cluster from backup or timestampa new instance from backup or timestamp
Change that destroys dataengine or zone replacement, unprotected deletedatabase version replacement, delete with no retained backupflush, eviction, or delete without a backup
Who owns the schemamigration runnermigration runnerapplication key design and TTL

Verify Engine, Edition and Network Requirements

Availability is regional before it is architectural. An engine and version that exist in one region may be absent in the next, and an edition that exists in a region may be missing from a specific zone. Read the zone and class data sources for the exact combination rather than copying a class from a tutorial.

The edition is part of the recovery contract. RDS separates Basic, high-availability, cluster and enterprise categories, and the cheaper categories change how many nodes stand behind the endpoint. PolarDB separates its normal, basic and archive categories, and the storage type follows the edition. A class string that fits one category does not fit the other.

A VSwitch is a zone decision, not just a subnet. The database must land in a VSwitch in the same VPC and the chosen zone, and changing that placement is usually a new resource rather than an in-place edit. Multi-zone RDS accepts a comma-joined list of VSwitches, PolarDB takes one, and a cache can add a secondary zone for its replica. Treat placement changes as data migrations.

Two access controls guard the same port. A security group admits traffic by group membership, while an IP whitelist admits addresses and CIDR blocks. RDS accepts security group IDs and whitelist entries, PolarDB uses named IP arrays, and the cache has both a whitelist and a security group setting. Reference the application security group, and never leave the default open range in a shared module.

A public endpoint is a separate decision from a working endpoint. RDS allocates its private connection automatically, while its connection resource adds an internet address. PolarDB exposes a primary endpoint whose network type and SSL settings you choose, and the cache has a separate public connection resource. Keep the private path as the default and require a named reason for the public one.

Parameters are versioned and sometimes static. RDS and PolarDB accept parameter blocks, and the cache accepts a configuration map. A static value needs a restart or a maintenance window, while a dynamic value applies live. Engine families and editions also constrain which parameters exist, so an edition change can invalidate settings.

The flow below places the checks in the order a failed connection would expose them, with the failure branch on each step.

Verify Engine, Edition and Network Requirements
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Pick engine, edition
and exact version"] --> B{"Zone offers that
engine and edition?"} B -->|"no"| B1["Change region or zone
before writing the module"] B -->|"yes"| C{"A class exists in
that zone?"} C -->|"no"| C1["Resize or choose a class
the zone actually lists"] C -->|"yes"| D{"VSwitch is in the
same VPC and zone?"} D -->|"no"| D1["New VSwitch
placement is ForceNew"] D -->|"yes"| E{"Security group or whitelist
admits the application?"} E -->|"no"| E1["Connect timeout
the packet was dropped"] E -->|"yes"| F{"Parameter is static?"} F -->|"yes"| F1["Restart or maintenance
window required"] F -->|"no"| G["Apply with a private
endpoint only"] F1 --> G G --> H{"Public endpoint
genuinely required?"} H -->|"yes"| H1["Allocate deliberately
and narrow the whitelist"] H -->|"no"| I["Record the evidence
and move on"] H1 --> I classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,C,D,E,F,H primary; class G,I secondary; class B1,C1,D1,E1,F1 danger; class H1 warn;

The failure branches are deliberately different. A missing zone or class is fixed in the configuration, a VSwitch mismatch is fixed by a migration, a whitelist miss appears as a timeout, and a static parameter produces a pending restart. Naming the failure correctly is most of the repair.

Handle Accounts and Credentials with Explicit Persistence Boundaries

Three identities should exist, with three different lifetimes. The Terraform runner creates infrastructure and should not run application queries. A migration account owns schema changes. A runtime account owns reads and the writes the application actually performs. Collapsing them removes the audit trail that makes a bad deploy diagnosable.

The master account is an administrative fact, not an application credential. RDS and PolarDB expose a privileged account type; all three expose a normal account. Give the application its own normal account, grant only the databases it needs, and keep the privileged account for recovery and account management. The migration identity is separate again, because DDL authority is not runtime authority.

Sensitive is a display flag, not a storage boundary. A password argument marked sensitive is redacted in terminal output, but it is still written to state and to a saved plan. Encrypt the backend, restrict who can read state, and never emit the value as an output. A KMS-encrypted password stores ciphertext rather than plaintext, but the ciphertext is still a reference that can be decrypted by anyone holding the key.

Write-only arguments make a stronger claim, with one integer left behind. The account resources accept a write-only password paired with a version, so the value is sent during apply and is not stored in state or the plan. Terraform still needs the value at apply time, which means your secret source or pipeline supplies it. The version is the only part that persists, and it exists to tell the provider when to resend.

Rotation is a version change, not a new random value. If the password changes but the version does not, the provider has no reason to resend it. If the version changes without a password, the apply fails instead of silently keeping the old one. Change both in the same commit, and treat the version as an auditable rotation counter.

Grants belong to identities, and the runtime identity should be narrow. RDS and PolarDB have account privilege resources that attach a database to an account with a named privilege. The cache account chooses a read-only or read-write role. Grant the runtime account read-only access wherever the workload allows it, and let the migration account hold the write and DDL privileges.

Endpoints are configuration, not secrets. The RDS private connection prefix and port belong to the instance, while the connection resource is the internet address; do not confuse the two when wiring an application. PolarDB exposes a cluster connection string and port, and the cache exposes a private domain plus an optional public connection. Output the host and port, document which network they resolve from, and keep only the password out of logs.

Cache authentication is a setting you must state. The cache's vpc_auth_mode requires a password when open and permits anonymous access when closed. Set it explicitly, test that an unauthenticated client is refused, and keep the cache in a private VSwitch. A cache with no password is not private merely because its address is hard to guess.

Version Schema and Data Changes Outside Provisioning

Terraform creates the database, not the schema. The database resource supplies a name and a character set, and the account resource supplies an identity. Tables, columns, indexes and views belong to a migration tool; the account resource grants database access, not table privileges. A plan that appears to create a database has not created a single row.

The migration runner owns the ledger. One numbered file per change, a ledger table inside the database, and one pipeline allowed to apply it. Flyway, Liquibase and Alembic differ in syntax but agree on the important part: the database records which change ran, not the Terraform state.

A provisioner is not a migration system. Running SQL from a local-exec hook hides an imperative step inside a declarative apply. There is no ledger, the step re-runs on replacement, and a failure can leave graph and schema half-changed. Keep the migration in a job whose result is visible in the database.

Order the release as infrastructure, then schema, then code. Terraform can place the database before the application, but it cannot insert your SQL between them because the migration is not an object in its graph. A pipeline that ships the new code before the migration asks for a column that does not exist yet.

Engine upgrades are schema events. An RDS version upgrade can change optimizer behaviour and reserved words. In the provider schema, a PolarDB database version is a replacement attribute, so a major version change creates a new cluster rather than upgrading the old one in place. A cache engine upgrade can change command support and the persistence format. Test each on a clone before the production window.

Writers apply DDL, readers serve reads. A PolarDB reader endpoint can lag the writer, and DDL sent to a read-only node is rejected. Pin the migration job to the primary endpoint, and let the application use readers for queries that tolerate replication delay.

A cache has no schema, only key versions. Adding a field to a cached object is a new key prefix, a dual-read window, and a TTL that retires the old shape. Invalidation is the migration, and once the old keys expire there is no rollback except a restore. Version the key rather than overwriting values in place.

The figure shows the three-release sequence and the exact point where a code rollback stops being a safe undo.

Expand, migrate and contract across three releases with the rollback window closing at the read switch Release N adds a nullable column and writes both shapes. Release N plus one backfills and switches reads, including a new cache key prefix. Release N plus two drops the old column and lets the old keys expire. A rollback is safe in the first release, unsafe after the read switch, and requires a data restore after the drop. A schema change is a sequence, not an apply Each release stays compatible with the one before it. The rollback window closes when reads switch. Release N — expand Release N+1 — migrate Release N+2 — contract Add a nullable column old code still writes nothing reads it yet ledger gains one row Backfill, then switch reads batch size keeps load bounded both shapes still accepted cache writes key prefix v2 Drop the old shape constraints added last old column is gone old keys expire by TTL Write both shapes reads use the old column one release of overlap Read new, write both overlap absorbs a rollback verify counts before release Read and write new old shape is dead code remove it in a later release Rollback is safe old code ignores the new column Rollback is unsafe old code reads a stale shape No code undo restore data, then redeploy A rename is two releases: add the new name, dual-write, switch reads, then remove the old name.

The rollback window closes at the read switch. Before it, rolling the code back is free because the old shape is still written. After it, the old code reads a column that is no longer authoritative, so the fix is forward or a restore. Write that boundary into the release record, because it is the first fact an incident responder needs.

Prove Recovery for One Selected Service

A backup is a retained copy; a restore is a rehearsed procedure. The backup policy tells you what the service kept. It does not tell you whether your team can turn that copy into a reachable database with the right accounts, whitelist and parameters. Only a timed restore against a scratch target produces that evidence.

An RDS restore is a clone with a new endpoint. Clone the instance at a backup identifier or a point in time; the source keeps serving while the copy is built. The restore timestamp must fall inside the log backup window, and the clone arrives as a new instance that needs its connection, whitelist and account checked before cutover. Deletion protection blocks an accidental destroy on a postpaid instance, and on MySQL the release retention policy decides whether archived backups survive the instance.

A PolarDB restore is a clone of the cluster, not of the endpoint. The cluster resource can be created from a source cluster with a clone data point of latest, backup identifier or timestamp. The new cluster is a separate object with its own endpoint and backup policy, so re-check accounts and whitelist before cutover. Base retention is documented as fixed at seven days; longer retention is a level-2 archive setting, and the deletion policy decides whether backups survive a cluster delete.

A cache restore is bounded by its backup window. The cache instance can be created from a source instance with a backup identifier or timestamp, and the backup window plus incremental log decides how close the copy gets to the failure. The restored cache is a new instance with a new address, so clients must reconnect. A flush or an eviction storm is not a restore until a backup exists.

Some switches have no reverse. Transparent data encryption cannot be turned off after it is enabled on RDS, PolarDB or the cache. A PolarDB backup policy that moves from the normal level to the advanced level cannot move back. Forcing a subscription RDS instance through deletion settles the remaining term and has billing consequences. Record each of these as a one-way door in the release record, beside the person who approved it.

The lab below turns those claims into a trace you can run in a disposable account, including the deletion step most drills skip.

Lab

Prove Recovery for One Selected Service

Execution status: design-only. This trace was written against Terraform 1.17.1 and aliyun/alicloud 2.2.0 on 6 November 2026. It was not run against a live account, so every expected result is documented behaviour, not a measurement. Every identifier is a placeholder you supply.

Prerequisites. A disposable Alibaba Cloud account on the International site, a VPC with two VSwitches in different zones, a RAM role allowed to create the selected database or cache, and a state bucket you can destroy. Choose one service for the drill: RDS MySQL, PolarDB MySQL, or a KVStore Redis instance. Use the smallest class the zone lists, and never point the restore step at a database you intend to keep.

The change under test. One nullable column on an orders table, one known row, and a clone at a timestamp recorded immediately before that row is written. For the cache variant, substitute one key with a fixed name and treat the timestamp as the point before the write.

  1. Baseline the service. Apply the root, confirm a second plan is empty, and record the engine, edition, version, retention days and backup window in one line of the release record.
  2. Write the recovery contract. State the RPO and RTO you are testing, the exact UTC minute before the known write, and the name of the person who owns cutover.
  3. Write one known fact. Insert the order or set the cache key, then query it back from the writer endpoint. A row that cannot be read before the backup cannot prove anything after the restore.
  4. Wait for a usable backup. For RDS, confirm log backup is enabled and the timestamp sits inside the retention window. For PolarDB, confirm a backup set covers the timestamp. For the cache, confirm the backup window has completed since the write.
  5. Clone to a scratch name. Use a restore time for RDS or the cache, or a clone data point for PolarDB. Expect a new endpoint; the original still serves.
  6. Verify the copy, not the count. Query the fixed key or row directly at the chosen timestamp. A row count is an estimate and a stale cache metric is worse; the known fact is the only trustworthy check.
  7. Break the copy. Disable deletion protection or the deletion lock deliberately, destroy the scratch resource, and observe what survives under the configured retention policy. This is the irreversible step, performed only on the disposable copy.
  8. Time it and clean up. Measure from the restore request to the first successful query, write the duration beside the timestamp, destroy the scratch root, and keep the record rather than the credentials.
ObservationPassing resultFailing result means
Restore target existsnew endpoint or cluster name, original untouchedthe restore was treated as an in-place edit
Known fact after restorepresent or absent exactly as the timestamp predictsthe timestamp was after the write or outside the window
Connection after cloneprivate endpoint, expected whitelist, working accountthe clone was assumed ready without a connection check
Delete with retention setonly the copies the policy names survivethe policy was left at its default
Cutoverone reviewed configuration changethe old endpoint is still hard-coded

Cost dimensions. The instance or cluster runs for the hours the drill takes, storage bills per GB-month, and retained backups bill beyond the included allowance. Delete the scratch resource and any retained copy the same day, and keep the timing record instead of the billable object.

Evidence to keep. The service, edition and version, the backup window, the restore timestamp, the measured duration, the one-way doors you touched, and the provider version. A reviewer should be able to reproduce the decision without seeing a live credential or a real account identifier.

Sources. The resource behaviour follows the aliyun/alicloud 2.2.0 provider documentation for RDS, PolarDB and KVStore, and the service limits follow the Alibaba Cloud RDS, PolarDB and Tair documentation. Re-read the argument reference for the pinned release before running the drill, because retention and clone arguments change between provider majors.

Next in the Series

In ACK and Container Registry: Cluster Activation, Roles and Workload Separation, we'll explore Provision Alibaba container infrastructure and stage Kubernetes resources only after the API is ready.