Azure
AzureIntermediate

Azure Database Solutions: Choosing the Right Database Service

5 min read
azuredatabasesqlcosmos-dbperformance

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: A Complete Implementation Guide

Azure offers a comprehensive suite of database services to meet various application needs. This guide helps you choose and implement the right database solution for your requirements.

$1

Azure's main database offerings:

Service Use Case Key Features
Azure SQL Database Relational data Managed SQL Server, scalability
Cosmos DB NoSQL workloads Global distribution, multi-model
MySQL/PostgreSQL Open source Managed services, compatibility
Cache for Redis Caching High performance, scalability

$1

$1

``sql

-- Create a new database

CREATE DATABASE MyAppDB

(

EDITION = 'Standard',

SERVICE_OBJECTIVE = 'S1',

MAXSIZE = 250GB

)

`

$1

`json

{

"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"

}

}

`

$1

$1

`javascript

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;

}

`

$1

`json

{

"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

}

}

`

$1

$1

Migration Type Source Target
Offline SQL Server Azure SQL
Online PostgreSQL Azure PostgreSQL
Hybrid MongoDB Cosmos DB
Bulk Oracle Azure SQL

$1

`powershell

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"

`

$1

$1

`sql

-- 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

);

`

$1

`javascript

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

}

]

}

]

}

};

`

$1

$1

`sql

-- Configure Always On availability

ALTER AVAILABILITY GROUP [AG_MyAppDB]

MODIFY REPLICA ON 'SecondaryNode'

WITH (AVAILABILITY_MODE = SYNCHRONOUS_COMMIT);

-- Add database to availability group

ALTER AVAILABILITY GROUP [AG_MyAppDB]

ADD DATABASE MyAppDB;

`

$1

Level Guarantee Performance
Strong Linearizable Highest latency
Bounded Staleness Consistent prefix Medium latency
Session Monotonic reads Low latency
Eventual Out of order Lowest latency

$1

$1

`sql

-- 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;

`

$1

`javascript

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"]

}

});

`

$1

$1

`powershell

Enable diagnostic settings

Set-AzDiagnosticSetting

-ResourceId $database.Id

-WorkspaceId $workspaceId

-Enabled $true

-Category @("QueryStoreRuntimeStatistics", "Errors")

Set up alerts

New-AzMetricAlertRule

-Name "HighDTU"

-Location "East US"

-ResourceGroup "MyResourceGroup"

-TargetResourceId $database.Id

-MetricName "dtu_consumption_percent"

-Operator GreaterThan

-Threshold 90

-WindowSize "00:05:00"

-TimeAggregationOperator Average

```

$1

1. Database Selection

- Consider workload type

- Evaluate scaling needs

- Assess global distribution

- Review cost implications

2. Performance

- Implement proper indexing

- Use appropriate partitioning

- Monitor query performance

- Regular maintenance

3. Security

- Enable encryption

- Implement proper authentication

- Regular security audits

- Monitor access patterns

4. High Availability

- Configure geo-replication

- Implement failover groups

- Regular backup testing

- Monitor replication lag

$1

Common issues and solutions:

1. Performance Issues

- Check query plans

- Review index usage

- Monitor resource utilization

- Analyze wait statistics

2. Connectivity Problems

- Verify network settings

- Check firewall rules

- Review connection strings

- Monitor timeouts

3. Replication Issues

- Check replication status

- Monitor lag time

- Verify network connectivity

- Review error logs

$1

After implementing your database solution:

1. Set up monitoring and alerting

2. Implement backup strategies

3. Configure disaster recovery

4. Document maintenance procedures

5. Train database administrators

Remember to regularly review and update your database implementation to maintain optimal performance and reliability.

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.