AzureIntermediate

Azure Database Solutions: Choosing the Right Database Service

10 min read

TL;DR

A comprehensive guide to Azure database services, covering SQL Database, Cosmos DB, migration strategies, performance optimization, and high availability configurations.

Azure Database Solutions: Choosing the Right Database Service

Executive Summary

Azure offers several managed database services that look interchangeable in the portal and behave very differently in production. This guide explains how to choose between Azure SQL Database, Azure Cosmos DB, and the managed MySQL and PostgreSQL services based on data model, consistency requirements, and distribution needs. It covers provisioning, partition and index design, migration paths, and high availability configuration, so you can commit to a service with a clear view of what it does well and where it will constrain you later.

Why This Matters

A database choice is one of the hardest decisions to reverse. The data model, consistency guarantees, and query patterns are baked into application code, and migrating a live system under load is a project measured in months, not a weekend task. Choosing a relational engine for access patterns that are really key-value lookups produces expensive workarounds; choosing a globally distributed NoSQL store for workloads that need joins and multi-row transactions produces worse ones. The cost of getting this wrong is paid in latency, in request-unit or DTU bills that grow with every unindexed query, and eventually in a migration you did not budget for.

Core Concepts

The Service Landscape

ServiceData modelChoose it for
Azure SQL DatabaseRelationalTransactional workloads, complex queries, existing SQL Server skills
Azure Cosmos DBMulti-model NoSQLGlobal distribution, predictable single-digit-millisecond reads and writes, flexible schema
Azure Database for MySQL / PostgreSQLRelational (open source engines)Lifting existing MySQL or PostgreSQL applications without replatforming
Azure Cache for RedisIn-memory key-valueCaching, session state, leaderboards, rate limiting

The first question is always the data model and access pattern, not the brand. If your queries are relational — joins, ad hoc reporting, multi-row transactions — start with a relational engine. If your access pattern is dominated by point reads and writes on a known key, with users in more than one region, Cosmos DB earns its place.

Azure SQL Database

Azure SQL Database is a managed SQL Server engine with built-in high availability, automatic backups, and two purchasing models: DTU-based tiers for simple, predictable workloads and vCore-based tiers when you need independent control of compute and storage, or Azure Hybrid Benefit for existing licences.

-- Create a new database
CREATE DATABASE MyAppDB
(
    EDITION = 'Standard',
    SERVICE_OBJECTIVE = 'S1',
    MAXSIZE = 250GB
)

The equivalent declarative definition makes the important properties explicit — collation, zone redundancy, and read scale-out:

{
    "name": "MyAppDB",
    "location": "[resourceGroup().location]",
    "sku": {
        "name": "Standard",
        "tier": "Standard",
        "capacity": 10
    },
    "properties": {
        "collation": "SQL_Latin1_General_CP1_CI_AS",
        "maxSizeBytes": "268435456000",
        "zoneRedundant": true,
        "readScale": "Enabled"
    }
}

Performance work in SQL Database is mostly index discipline and query hygiene. Query Store is the tool that makes this tractable: it records query plans and runtime statistics so you can find regressions after deployments instead of guessing.

-- Create indexes for performance
CREATE NONCLUSTERED INDEX IX_OrderDate
ON Sales.Orders (OrderDate)
INCLUDE (CustomerID, TotalAmount);

-- Update statistics
UPDATE STATISTICS Sales.Orders
WITH FULLSCAN;

-- Configure Query Store
ALTER DATABASE MyAppDB
SET QUERY_STORE = ON
(
    OPERATION_MODE = READ_WRITE,
    CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30),
    DATA_FLUSH_INTERVAL_SECONDS = 900,
    MAX_STORAGE_SIZE_MB = 1000
);

Security is defence in depth: Microsoft Entra authentication instead of SQL logins where possible, contained users scoped to the database, and row-level security for multi-tenant schemas so one tenant's data cannot leak through a missing WHERE clause.

-- Create contained database user
CREATE USER AppUser
WITH PASSWORD = 'ComplexPassword123!';

-- Grant permissions
GRANT SELECT, INSERT, UPDATE, DELETE
ON SCHEMA::dbo
TO AppUser;

-- Enable Row-Level Security
CREATE SECURITY POLICY FilterPolicy
ADD FILTER PREDICATE dbo.fn_securitypredicate(TenantId)
ON dbo.Orders;

Azure Cosmos DB

Cosmos DB is a globally distributed, multi-model database. Two decisions dominate every Cosmos design: the partition key and the consistency level.

The partition key determines how data is spread across physical partitions and which queries are cheap. A query that includes the partition key targets one partition; a query without it fans out to all of them and costs accordingly. Choose a key with high cardinality that appears in your most frequent queries.

const { CosmosClient } = require("@azure/cosmos");
const client = new CosmosClient(connectionString);

async function createContainer() {
    const { database } = await client.databases.createIfNotExists({ id: "MyAppDB" });
    const { container } = await database.containers.createIfNotExists({
        id: "Items",
        partitionKey: {
            paths: ["/category"]
        },
        indexingPolicy: {
            indexingMode: "consistent",
            automatic: true,
            includedPaths: [
                {
                    path: "/*"
                }
            ],
            excludedPaths: [
                {
                    path: "/description/?"
                }
            ]
        }
    });
    return container;
}

Throughput is provisioned in Request Units per second (RU/s), and every operation — reads, writes, queries — has an RU cost. Indexing everything is the default, and trimming the indexing policy for large, rarely queried properties is a direct cost saving.

const containerOptions = {
    throughput: 400,
    partitionKey: { paths: ["/id"] },
    indexingPolicy: {
        indexingMode: "consistent",
        automatic: true,
        includedPaths: [
            {
                path: "/*",
                indexes: [
                    {
                        kind: "Range",
                        dataType: "Number",
                        precision: -1
                    },
                    {
                        kind: "Range",
                        dataType: "String",
                        precision: -1
                    }
                ]
            }
        ]
    }
};

Consistency is tunable across five levels. Stronger consistency costs latency and availability; weaker consistency costs application complexity.

LevelGuaranteeCost profile
StrongLinearizable readsHighest latency; unavailable during regional failover
Bounded StalenessReads lag writes by a bounded amountMedium latency
SessionRead-your-writes within a sessionLow latency; the default for most applications
Consistent PrefixReads never see out-of-order writesLow latency
EventualNo ordering guaranteeLowest latency and cost

Multi-region accounts with automatic failover are configured declaratively:

{
    "name": "[variables('accountName')]",
    "type": "Microsoft.DocumentDB/databaseAccounts",
    "apiVersion": "2021-04-15",
    "location": "[parameters('location')]",
    "kind": "GlobalDocumentDB",
    "properties": {
        "consistencyPolicy": {
            "defaultConsistencyLevel": "Session"
        },
        "locations": [
            {
                "locationName": "East US",
                "failoverPriority": 0
            },
            {
                "locationName": "West US",
                "failoverPriority": 1
            }
        ],
        "enableMultipleWriteLocations": true,
        "enableAutomaticFailover": true
    }
}

Credentials belong in Key Vault, never in configuration files:

const cosmosKey = await getSecretFromKeyVault("cosmos-key");
const client = new CosmosClient({
    endpoint: process.env.COSMOS_ENDPOINT,
    key: cosmosKey,
    connectionPolicy: {
        enableEndpointDiscovery: true,
        preferredLocations: ["East US", "West US"]
    }
});

Migration

Azure Database Migration Service (DMS) is the standard path for moving on-premises or other-cloud databases into Azure, with offline migrations for planned downtime and online migrations that replicate changes continuously until cutover.

# Azure Database Migration Service setup
$migrationService = New-AzDataMigration `
    -ResourceGroupName "MyResourceGroup" `
    -Name "MyMigrationService" `
    -Location "East US" `
    -Sku "Premium_4vCores"

# Create migration project
$migrationProject = New-AzDataMigrationProject `
    -ResourceGroupName "MyResourceGroup" `
    -ServiceName "MyMigrationService" `
    -ProjectName "MyMigrationProject" `
    -Location "East US" `
    -SourceType "SQL" `
    -TargetType "SQLDB"

Treat schema conversion as a separate workstream from data movement. Engine differences — data types, identity columns, stored procedure dialects — should surface during assessment, not during the cutover weekend.

Monitoring

Enable diagnostic settings so database logs and metrics land in Log Analytics, and alert on the resource metric that maps to your purchasing model — DTU or vCore consumption for SQL Database, normalised RU consumption for Cosmos DB.

# Enable diagnostic settings
Set-AzDiagnosticSetting `
    -ResourceId $database.Id `
    -WorkspaceId $workspaceId `
    -Enabled $true `
    -Category @("QueryStoreRuntimeStatistics", "Errors")

Decision Framework

SituationRecommendation
Existing SQL Server application moving to AzureAzure SQL Database (or SQL Managed Instance if you need instance-level features)
Complex reporting, joins, multi-row transactionsAzure SQL Database or Azure Database for PostgreSQL
Global user base, point reads/writes by key, low-latency requirement in every regionAzure Cosmos DB with session consistency
Existing MySQL or PostgreSQL application, minimal changes wantedAzure Database for MySQL / PostgreSQL Flexible Server
Hot data read far more often than writtenAdd Azure Cache for Redis in front of the system of record
Workload needs both relational integrity and global scaleKeep the relational store as system of record; replicate read models into Cosmos DB rather than forcing one engine to do both

Implementation Checklist

  • [ ] Access patterns documented before choosing the service — top queries by frequency and latency sensitivity
  • [ ] For Cosmos DB: partition key validated against the top queries; cross-partition queries identified and priced
  • [ ] For SQL Database: purchasing model (DTU vs vCore) chosen deliberately; Query Store enabled
  • [ ] Authentication uses Microsoft Entra identities or contained users; no shared admin credentials in application config
  • [ ] Secrets stored in Key Vault and referenced, not embedded
  • [ ] Backups configured and a restore actually tested to a point in time
  • [ ] Failover behaviour tested in a non-production environment before go-live
  • [ ] Diagnostic settings route logs and metrics to Log Analytics; alerts set on saturation metrics
  • [ ] Migration rehearsed with production-like data volumes, including schema conversion findings resolved
  • Trade-offs

    Managed services remove patching, backup plumbing, and much of the high availability work, but they also remove control. You cannot tune the underlying storage engine, install arbitrary extensions on the server, or reach the host. Cosmos DB trades relational flexibility for scale and availability: no joins, no multi-item transactions across partitions without application-level compensation, and an RU pricing model that punishes inefficient queries continuously rather than occasionally. SQL Database keeps the relational model but ties you to one region for writes unless you build read replicas and accept their replication lag.

    When Not to Use

  • Cosmos DB is the wrong choice when the workload is fundamentally relational reporting — ad hoc joins across many entities will be slow and expensive; use a relational engine or a dedicated analytics store instead.
  • Azure SQL Database is the wrong choice when you need instance-level SQL Server features such as SQL Agent jobs across databases or linked servers; use Azure SQL Managed Instance, or SQL Server on Azure VMs if you need full control of the host.
  • A managed service at all is the wrong choice when a hard regulatory or latency requirement forces the database onto infrastructure you operate yourself; in that case run the engine on VMs and accept the operational cost explicitly rather than discovering the constraint mid-project.
  • Conclusion

    Choose the database by access pattern and consistency requirement, not by familiarity. Relational workloads belong on SQL Database or the managed open-source engines; globally distributed key-based workloads belong on Cosmos DB with a carefully chosen partition key and the weakest consistency level your application can tolerate. Whichever you pick, test backup restore and failover before production — those are the properties you cannot retrofit under incident pressure.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.