Choose Relational or Document Data by the Access Contract
Start with the five access paths, not the engine shortlist. Write down each query, its predicate, and how many rows it must return. A screen that joins an order to its lines and filters by date is a relational contract. A lookup by tenant and item id that returns one document is a key-value contract. The engine follows the contract, and choosing the engine first turns every later query into a workaround.
Azure SQL Database is the managed SQL Server engine. It keeps T-SQL, stored procedures, constraints, triggers and the transaction semantics an existing SQL Server application expects. A logical server is the namespace and the administration boundary; a database is the unit of scale and backup, and an elastic pool shares capacity across several databases with spiky load.
PostgreSQL Flexible Server is the community engine, managed. It is not a SQL Server dialect and does not accept T-SQL. Extensions, JSONB, partial indexes and Postgres transaction rules are the contract. Porting between the two is a query rewrite and a data-model review, not a connection-string change.
Cosmos DB trades joins for a partition key. Items are JSON documents in a container, and the partition key decides which physical partition owns an item. A point read that names both the partition key and the id is the cheapest operation in the service. A query that omits the partition key fans out to every partition, and the cost arrives as request units rather than as a slow index.
The resource tree mirrors the service, and the blast radius differs. SQL is server then database, PostgreSQL is server then database, and Cosmos is account then database then container. Deleting the parent in any of them deletes the children, which is why the unit you name in Terraform is the unit you must protect in the plan.
The flow below follows the first three questions a team should answer, including the branch where the honest answer is to reshape the query rather than buy a bigger engine.
%%{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','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#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','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["List the five access paths
and their predicates"] --> B{"Joins, constraints or
ad-hoc SQL?"}
B -->|"yes"| C{"Existing SQL Server
application?"}
B -->|"no"| D{"Every read names a
partition key and id?"}
C -->|"yes"| E["Azure SQL Database
T-SQL and compatibility level"]
C -->|"no"| F["PostgreSQL Flexible Server
extensions and JSONB"]
D -->|"yes"| G["Cosmos DB container
partition key is the design"]
D -->|"no"| H["Stop: a cross-partition
scan is not an access path"]
E --> I["Record the exit cost
before the first apply"]
F --> I
G --> I
H --> J["Reshape the query or
keep a relational store"]
J --> 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 primary;
class E,F,G secondary;
class I ok;
class H danger;
class J warn;
Terraform declares the container; the service keeps the data. All three providers expose backup, availability and throughput as resource arguments. None of them expose rows, transactions or documents. That boundary is the subject of the rest of this article: the plan can create, resize and protect a database, and it cannot read one.
Read the figure from the top down. The top band is the only layer reproducible from Git. The middle band is policy you can review but not own. The bottom band is the layer that needs a restore you have actually performed.
The comparison is about exit cost, not feature counts. Any of the three can store an order. The question is which change you are willing to perform under pressure: a server rename, a zone move or a partition-key change.
| Decision | Azure SQL Database | PostgreSQL Flexible Server | Cosmos DB (SQL API) |
|---|---|---|---|
| Access contract | joins, constraints and ad-hoc SQL | relational SQL plus extensions | key and item, or a bounded query |
| Unit that scales | database or elastic pool | server SKU and storage | throughput per container or database |
| Network path | private endpoint in privatelink.database.windows.net | delegated subnet and private DNS zone | private endpoint in privatelink.documents.azure.com |
| Backup model | point-in-time plus long-term retention | 7 to 35 days, geo-redundant optional | periodic, or continuous for 7 or 30 days |
| Change that destroys data | server replacement or database drop | server replacement or zone change | partition-key change or account delete |
| Who owns the schema | migration runner | migration runner | application code, key and indexing policy |
Choose once, then record why. A short decision record with the access paths, the chosen engine and the change that would force a migration saves the next team from re-litigating the choice at the worst moment.
Verify Engine, Region and Capacity Configuration
Three names are DNS labels, so a rename is a new service. The SQL server name becomes the host under database.windows.net, and the Cosmos account name becomes the host under documents.azure.com. Both are globally unique and fixed for the life of the resource.
PostgreSQL follows the same rule. The server name is the host under the postgres suffix, so a rename is a new server with an empty data directory, not a DNS update. Treat every one of these names as an immutable identifier rather than a label you can tidy later.
Engine version means something different in each service. Azure SQL reports the T-SQL engine as 12.0, while the setting you actually choose per database is its compatibility level. PostgreSQL pins a major version and applies minors on the service's schedule. Cosmos DB has no engine version at all: the account kind and the API choice are the compatibility contract.
Capacity is three different currencies. Azure SQL bills DTU or vCore with storage and IOPS inside the SKU; PostgreSQL bills vCores, storage and, on some tiers, IOPS; Cosmos bills request units per second. Comparing a vCore price to an RU price without the query mix is meaningless, so size against a measured workload and leave headroom for the peak.
Check that the SKU exists in the region before the plan, not after. vCore quota is per subscription and per region, zone redundancy is per SKU and per region, and Cosmos throughput has account-level limits. A configuration that is valid in one region can fail in another at apply time with a quota or capacity error the graph cannot predict.
The flow below is the same check sequence for all three services, with the branches that stop an apply.
%%{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','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#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','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Candidate engine, version,
region and SKU"] --> B{"Version offered in
the target region?"}
B -->|"no"| B1["Apply fails on an
unavailable version"]
B -->|"yes"| C{"Zone redundancy offered
for that SKU and region?"}
C -->|"no"| C1["Single zone, or a
different SKU or region"]
C -->|"yes"| D{"vCore or RU quota
available in the subscription?"}
D -->|"no"| D1["Request quota before
the apply, not during"]
D -->|"yes"| E{"Plan marks the change
as replacement?"}
E -->|"no"| F["In-place resize
same endpoint and data"]
E -->|"yes"| G["New endpoint
and an empty database"]
G --> H{"Restore target
ready for the cutover?"}
H -->|"no"| H1["Stop: replacement is
a data decision"]
H -->|"yes"| I["Apply, then rewire
the connection"]
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 primary;
class F,I secondary;
class C1,D1 warn;
class B1,G,H1 danger;
Read replacement markers as data decisions. A changed location, a changed server name or a changed PostgreSQL zone produces a new resource with a new endpoint and an empty database. An in-place SKU change is a resize; a replacement is a migration. The plan tells you which one you are about to do, so read the annotation rather than the size of the diff.
Two arguments deserve a second look because they look cosmetic. The PostgreSQL zone and the Cosmos account kind are creation-time choices that the plan renders as a small one-line change. Both replace the resource, and the Cosmos change can also change the API the application speaks.
Connect Private DNS and Application Identity to the Database
Control-plane permission is not data-plane permission. A role that can create the server through Azure Resource Manager grants no ability to open a connection. The database has its own authentication and its own role model, and a successful private endpoint apply says nothing about whether the application identity can read a table.
Private access is a chain of four objects. A private endpoint or delegated subnet, a private DNS zone, a link from that zone to the application VNet, and a record that resolves the service name to a private address. Break any link and the name resolves to the public address, where the firewall refuses the packet. That is a timeout, not a permission error.
The path differs by service, and the zone name must match. Azure SQL and Cosmos DB use private endpoints, so the endpoint writes into a privatelink zone. PostgreSQL Flexible Server supports VNet integration through a delegated subnet, and the zone name it expects is not the private-link name. A correctly linked zone with the wrong name resolves nothing, which is the most common silent failure in the chain.
Resolve the name from where the workload runs. Test from a host in the application subnet, not from a laptop on the corporate network. A private address is the pass condition. A public address means the zone link or the record is wrong, and the fix belongs in Terraform rather than in a hosts file.
Give the application an identity, not a password. A managed identity requests a short-lived token from Entra ID, and each engine accepts it on its own protocol: Azure SQL as an access token, PostgreSQL in the password field of the connection, Cosmos DB as a bearer token for the data plane. The token expires; the role assignment does not.
Turn off the password path once the identity works. Azure SQL supports Entra-only authentication, PostgreSQL can disable password authentication while keeping Entra authentication, and Cosmos DB can disable local key authentication. That switch is the difference between an identity a workload must use and one it merely may use.
The admin credential still exists, and it still lands in state. Every one of these services accepts an administrator password at creation. A write-only argument keeps it out of state but not out of the creation contract. Prefer the identity path, keep the admin login for break-glass, and store its secret outside Terraform.
Creation and runtime roles belong to different principals. A deployment identity needs rights to create the server, the database and the role assignment. The workload identity needs only the data-plane role at the narrowest scope, one database or one container, and neither identity should be able to grant the other.
Version Schema and Data Migrations with the Application
Terraform creates an empty container. A PostgreSQL database resource creates a database with no tables. An Azure SQL database resource creates a database with no user schema beyond the system catalog. A Cosmos container is the exception that proves the rule: its partition key, indexing policy and TTL are resource arguments, so part of the shape is infrastructure, while every item field is not.
The migration runner owns the schema, and it keeps its own ledger. Numbered, forward-only files, a ledger table inside the database, and exactly one pipeline allowed to apply them. Flyway, Liquibase, Alembic and a hand-written runner disagree on syntax and agree on the invariant: the database, not Terraform state, records which change ran.
Order the release as infrastructure, then migration, then code. Terraform can order the database before the application, but it cannot place your SQL between them, because the migration is not a node in its graph. Shipping code and migration in one step leaves a window where the new query runs against the old column.
A provisioner is not a migration system. A local-exec hook that runs SQL hides an imperative step inside a declarative apply. There is no ledger, the step re-runs when the resource is replaced, and a failure leaves the graph and the schema half-changed together. Keep migrations in a job whose success is recorded in the database.
Expand, migrate, contract, and never rename in one release. Add a nullable column, deploy code that writes both shapes, backfill in batches, switch reads, then drop the old column in a later release. A rename is two releases for the same reason: old code keeps running while the new version rolls out, and it must still find the old name.
Cosmos changes are key and index changes. Adding a container or a composite index is additive. Changing the partition key path replaces the container and its data. An indexing policy edit applies in place but triggers a reindex, so a release that changes both the policy and the query needs its own verification window.
A rollback is a code action only inside the compatibility window. Before reads switch, old code ignores the new column and a rollback is free. After the switch, old code reads a value that is no longer authoritative, so the fix is forward or a restore. Write that boundary into the release record.
The figure is the release plan rather than the apply plan: each column ships on its own and stays compatible with the one before it.
The middle release is the boundary. Before the read switch, rolling code back is free. After it, the old code reads a column that is no longer authoritative, so the fix is forward or a restore. Put that fact in the release record, because it is the first thing an incident responder needs.
Prove Backup Recovery and Review Destruction
A backup is a copy; a restore is a procedure. Retention tells you what the service kept, not whether your team can turn it into a working database. The only evidence is a restore performed against a scratch target, timed, queried and written down.
Each service restores into a new resource. Azure SQL point-in-time restore creates a new database on the server, PostgreSQL restores into a new server, and Cosmos DB restores into a new account. None of them rewinds the original, so every recovery ends with a connection-string change and a cutover decision.
Retention is a pyramid, not a single number. Azure SQL keeps point-in-time backups for 1 to 35 days and can layer long-term retention on top for years. PostgreSQL Flexible Server keeps 7 to 35 days, with geo-redundant copies as an option. Cosmos DB offers periodic backups or continuous backup at a 7-day or 30-day tier.
Deletion needs a control that backup does not provide. A CanNotDelete management lock or a prevent_destroy lifecycle rule stops a control-plane delete before it happens, which is what you want for a database nobody should drop by accident. Neither one is a backup: a lock does not stop a delete statement, and the identity that can remove a lock can destroy the resource.
Some changes have no undo. Changing the Cosmos partition key, moving a server to another region, and deleting a Cosmos account are new-resource operations with no in-place path. A deleted account takes its backup history with it, and a dropped table is gone when the last backup containing it expires.
Protect with two controls and test the third. A lock, a retention window and a restore drill cover different failures. The lock stops a mistake in the portal, the window covers a bad write, and the drill proves the window is usable. Only the third one produces evidence you can show a reviewer.
The lab below turns those claims into a trace you can run in a disposable subscription, including the deletion step most drills skip.
Prove Backup Recovery and Review Destruction
Execution status: design-only. This trace was written against Terraform 1.17.1 and hashicorp/azurerm 5.13.0 on 6 November 2026. It was not run against a live subscription, so every expected result below is documented behavior rather than a measurement.
Prerequisites. A disposable subscription, a VNet with a delegated subnet for PostgreSQL and a subnet for private endpoints, a state account you can destroy, and an identity allowed to create SQL, PostgreSQL and Cosmos resources. Use the smallest SKU each service offers, and never point the restore step at a database you intend to keep.
The change under test. One nullable column on an orders table in PostgreSQL, plus continuous backup on a Cosmos account. The drill restores both to a timestamp before a known write, deletes the copies, and records what disappeared.
- Baseline the root. Apply, then run plan again and expect no changes. Record the PostgreSQL retention days and the Cosmos backup tier before writing anything.
- Write one known fact. Insert an order with a fixed id and note the UTC time of the insert. That timestamp is the restore target, not the time on your laptop.
- Expand the schema. Add the nullable column through the migration job, confirm the ledger row, and deploy code that writes both shapes. An ALTER run from a laptop proves nothing about the pipeline.
- Restore PostgreSQL. Request a point-in-time restore to the recorded time, expect a new server and endpoint, and query the fixed order. The original must still be serving.
- Restore Cosmos. Request a restore to the same timestamp, expect a new account, and read the item by partition key and id. Do not trust a count, which is an estimate.
- Delete the scratch copy. Remove the restored PostgreSQL server and confirm it is gone from the server list. Note whether the service still offers to restore the deleted server, because that window belongs to service retention, not to Terraform state.
- Time the recovery. Measure from the restore request to the first successful query, and write the duration beside the timestamp.
- Review the destroy plan. Run a plan with the destroy flag and read every resource marked for deletion before approving it.
| Observation | Passing result | Failing result means |
|---|---|---|
| Restore target | new server or account, original untouched | the restore was treated as an in-place edit |
| Known row after restore | absent at the chosen time | the timestamp was after the write |
| Migration ledger | one row per applied file | the schema changed outside the pipeline |
| Delete of the copy | server gone and its retention window recorded | a lock or a prevent_destroy rule blocked the drill |
| Destroy plan | every data resource listed before approval | the plan was approved from the summary line |
Cost dimensions. The smallest PostgreSQL SKU, the Cosmos account and both restored copies bill for the hours the drill takes, and storage plus backup storage bill beyond the included allowance. Delete both copies the same day.
Sources. The retention behavior follows the Azure SQL automated backups documentation, the PostgreSQL window follows the flexible server backup documentation, and the Cosmos tiers follow the Cosmos DB backup documentation.
Next in the Series
In Azure Applications: Functions, App Service, APIs and Event Wiring, we'll explore Coordinate infrastructure, managed identities and separately versioned application deployment.