top of page
12 minutes ago
15 min read

Azure Workshopz | Beyond Cloud with Chriz

Build a globally distributed database. Generate real workloads. Change the write region. Measure recovery. Validate data.

Level: AdvancedCloud: Microsoft AzureTools: Azure CLI, Azure Cloud Shell (Bash), Python SDKDatabase: Azure Cosmos DB for NoSQLRegions: West Europe and North EuropeFocus: Replication, Failover, Session Consistency, Availability, Data Integrity, TroubleshootingCost: Medium–High

Introduction

What happens when the primary region of your Azure Cosmos DB account changes while your application is actively processing transactions?

Will your application continue working?

Will requests fail during the transition?

Can the SDK automatically discover the new writable region?

And how can you prove that previously acknowledged data is still available?

In this Azure Enterprise Resilience Mega Lab, we will build a complete multi-region Azure Cosmos DB environment and test its behavior under realistic application traffic.

Unlike a basic database deployment tutorial, this workshop is designed around one continuous operational scenario.

We'll deploy the infrastructure, generate synthetic customer orders, start a continuous read/write workload, initiate a planned failover, investigate the results, verify data integrity, and restore the original regional configuration.

We will also deliberately introduce application-level authentication and partition-key errors to distinguish configuration failures from regional availability problems.

The objective is simple:

Understand how a real application behaves when the database's primary write region changes.

What We're Building

Our environment consists of:

  • One globally distributed Azure Cosmos DB account.

  • Two Azure regions.

  • One primary write region.

  • One secondary read region.

  • A NoSQL database containing customer orders.

  • A container with 400 RU/s provisioned throughput.

  • A Python application using the Azure Cosmos DB SDK.

  • Continuous synthetic read/write operations.

  • CSV-based latency and availability measurements.

  • Planned failover and failback operations.

  • Data-integrity verification.

We'll use the same infrastructure throughout the entire workshop.

Our Enterprise Scenario

Imagine you're operating an online ordering platform.

Customer orders are stored in Azure Cosmos DB.

The database is distributed across two Azure regions:

Component

Configuration

Primary region

West Europe

Secondary region

North Europe

Database

EnterpriseOrders

Container

Orders

Partition key

/customerId

Consistency

Session

Write configuration

Single-write

Throughput

400 RU/s

Client

Azure Cosmos DB Python SDK

The application continuously inserts and retrieves customer orders.

During normal operation, West Europe handles writes.

We'll initiate a planned write-region change to North Europe while the application continues submitting requests.

After the change, we'll examine whether the client experienced errors, increased latency, or gaps between successful operations.

Then we'll verify data integrity and restore West Europe as the primary write region.

THE MEGA LAB — ONE COMPLETE END-TO-END EXERCISE

Step 1 — Prepare Azure Cloud Shell

Open:

Select Bash.

Verify Azure CLI:

az version

Check your active subscription:

az account show \
  --query "{Name:name,SubscriptionId:id}" \
  --output table

Select the subscription if necessary:

az account set \
  --subscription "<YOUR-SUBSCRIPTION-ID>"

Verify Python:

python3 --version

You should have Azure CLI, Python 3, and permission to create Azure Cosmos DB resources.

Step 2 — Configure All Workshop Variables

We'll configure the environment once.

All following commands reuse these values.

# Azure regions
export PRIMARY_REGION="westeurope"
export SECONDARY_REGION="northeurope"

# Unique identifier
export SUFFIX=$(openssl rand -hex 4)

# Azure resources
export RG="rg-cosmos-resilience-$SUFFIX"
export COSMOS="cosmosres$SUFFIX"

# Database
export DATABASE="EnterpriseOrders"
export CONTAINER="Orders"

# Throughput
export THROUGHPUT=400

# Working directory
export LAB_DIR="$HOME/cosmos-resilience-$SUFFIX"

mkdir -p "$LAB_DIR"
cd "$LAB_DIR"

# Environment
echo "Resource Group: $RG"
echo "Cosmos DB:       $COSMOS"
echo "Primary:         $PRIMARY_REGION"
echo "Secondary:       $SECONDARY_REGION"

Create the resource group:

az group create \
  --name "$RG" \
  --location "$PRIMARY_REGION" \
  --tags Environment=Workshop \
         Project=Cosmos-Resilience-MegaLab

Verify:

az group show \
  --name "$RG" \
  --query "{Name:name,State:properties.provisioningState}" \
  --output table

Expected result: The resource group exists.

Step 3 — Deploy the Multi-Region Cosmos DB Environment

We will create one Cosmos DB account distributed across West Europe and North Europe.

The account uses:

  • Session consistency.

  • One writable region.

  • A secondary readable region.

  • Service-managed automatic failover enabled.

  • Public network access for the Cloud Shell lab client.

az cosmosdb create \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --locations \
    regionName=westeurope \
    failoverPriority=0 \
    isZoneRedundant=False \
  --locations \
    regionName=northeurope \
    failoverPriority=1 \
    isZoneRedundant=False \
  --kind GlobalDocumentDB \
  --default-consistency-level Session \
  --enable-automatic-failover true \
  --enable-multiple-write-locations false \
  --public-network-access ENABLED

This is a long-running Azure deployment.

Continue only when it completes successfully.

Verify the database account:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "{
    Name:name,
    State:provisioningState,
    AutomaticFailover:enableAutomaticFailover,
    MultiWrite:enableMultipleWriteLocations,
    Consistency:consistencyPolicy.defaultConsistencyLevel
  }" \
  --output json

Inspect the regional configuration:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "locations[].{
    Region:locationName,
    Priority:failoverPriority
  }" \
  --output table

Expected:

Region         Priority
-------------  --------
West Europe    0
North Europe   1

Priority 0 indicates the primary write region in our single-write configuration.

Checkpoint: Both regions must be provisioned before continuing.

Step 4 — Create the Enterprise Database

We'll create a database for synthetic customer orders.

az cosmosdb sql database create \
  --resource-group "$RG" \
  --account-name "$COSMOS" \
  --name "$DATABASE"

Create the container:

az cosmosdb sql container create \
  --resource-group "$RG" \
  --account-name "$COSMOS" \
  --database-name "$DATABASE" \
  --name "$CONTAINER" \
  --partition-key-path "/customerId" \
  --throughput "$THROUGHPUT"

Verify the container:

az cosmosdb sql container show \
  --resource-group "$RG" \
  --account-name "$COSMOS" \
  --database-name "$DATABASE" \
  --name "$CONTAINER" \
  --output json

Inspect throughput:

az cosmosdb sql container throughput show \
  --resource-group "$RG" \
  --account-name "$COSMOS" \
  --database-name "$DATABASE" \
  --name "$CONTAINER" \
  --output json

Some account configurations have a higher minimum throughput requirement. If Azure rejects 400 RU/s, use the reported minimum and account for the higher cost.

Step 5 — Prepare the Application Client

Now that the database infrastructure is deployed, we need a real application workload.

Azure CLI manages our Azure resources.

Python will perform the actual document operations using the official Azure Cosmos DB SDK.

Create a Python virtual environment:

python3 -m venv .venv

Install the SDK:

./.venv/bin/python -m pip install \
  --upgrade azure-cosmos

Set the Python executable:

export PYTHON="$LAB_DIR/.venv/bin/python"

Retrieve the database endpoint:

export COSMOS_ENDPOINT=$(az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query documentEndpoint \
  --output tsv)

Retrieve a temporary access key:

export COSMOS_KEY=$(az cosmosdb keys list \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query primaryMasterKey \
  --output tsv)

Configure application variables:

export COSMOS_DATABASE="$DATABASE"
export COSMOS_CONTAINER="$CONTAINER"

echo "Endpoint: $COSMOS_ENDPOINT"

Security note: The account key is used only for this disposable workshop. Do not display it or publish it. Production applications should use Microsoft Entra authentication and appropriate Cosmos DB data-plane RBAC where supported.

Step 6 — Create One Complete Resilience Test Application

We'll create a single Python script to perform our entire operational exercise.

The application will:

  • Generate 100 synthetic customer orders.

  • Calculate deterministic data checksums.

  • Read and verify business records.

  • Create continuously numbered probe documents.

  • Read each probe after writing it.

  • Log successful and unsuccessful operations.

  • Measure request latency.

  • Analyze the monitoring CSV.

  • Re-read acknowledged writes after failover.

  • Simulate an invalid database key.

  • Simulate an incorrect partition key.

Create the file:

cat > cosmos-resilience.py <<'PY'
import argparse
import base64
import csv
import hashlib
import math
import os
import statistics
import time
import uuid

from datetime import datetime, timezone

from azure.cosmos import CosmosClient


ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]
DATABASE = os.environ["COSMOS_DATABASE"]
CONTAINER = os.environ["COSMOS_CONTAINER"]


def now():
    return datetime.now(timezone.utc).isoformat()


def connect(key=None):
    client = CosmosClient(
        ENDPOINT,
        credential=key if key is not None else KEY,
        preferred_locations=[
            "West Europe",
            "North Europe"
        ],
        enable_endpoint_discovery=True
    )

    return client.get_database_client(
        DATABASE
    ).get_container_client(CONTAINER)


def expected_order(number):
    order_id = f"order-{number:03d}"
    customer_id = f"customer-{number % 5:02d}"
    amount = (number + 1) * 13

    payload = f"{order_id}|{customer_id}|{amount}"

    checksum = hashlib.sha256(
        payload.encode()
    ).hexdigest()

    return {
        "id": order_id,
        "customerId": customer_id,
        "type": "customer-order",
        "amount": amount,
        "status": "Created",
        "checksum": checksum
    }


def seed():
    container = connect()

    for number in range(100):
        container.upsert_item(
            expected_order(number)
        )

    print("100 customer orders created.")


def verify():
    container = connect()

    valid = 0
    errors = 0

    for number in range(100):
        expected = expected_order(number)

        try:
            actual = container.read_item(
                item=expected["id"],
                partition_key=expected["customerId"]
            )

            if all(
                actual.get(k) == v
                for k, v in expected.items()
            ):
                valid += 1
            else:
                errors += 1

        except Exception as exc:
            errors += 1
            print(
                f"Read failed for {expected['id']}: "
                f"{type(exc).__name__}"
            )

    print(f"Valid records: {valid}")
    print(f"Mismatched/unreadable: {errors}")

    if errors:
        raise SystemExit("DATA VERIFICATION FAILED")

    print("DATA INTEGRITY: PASS")


def monitor(filename, stop_file):
    container = connect()

    run_id = uuid.uuid4().hex[:8]
    sequence = 0

    with open(filename, "w", newline="") as f:
        fields = [
            "timestamp",
            "document_id",
            "write",
            "read",
            "latency_ms",
            "error"
        ]

        writer = csv.DictWriter(
            f, fieldnames=fields
        )
        writer.writeheader()

        while not os.path.exists(stop_file):
            sequence += 1

            document_id = (
                f"probe-{run_id}-{sequence:06d}"
            )

            item = {
                "id": document_id,
                "customerId": "probe",
                "type": "availability-probe",
                "sequence": sequence,
                "createdUtc": now()
            }

            write = "FAIL"
            read = "SKIPPED"
            error = ""

            started = time.monotonic()

            try:
                container.upsert_item(item)
                write = "OK"

                result = container.read_item(
                    item=document_id,
                    partition_key="probe"
                )

                if result.get("sequence") == sequence:
                    read = "OK"
                else:
                    read = "MISMATCH"

            except Exception as exc:
                if write == "OK":
                    read = "FAIL"

                status = getattr(
                    exc, "status_code", "unknown"
                )

                error = (
                    f"{type(exc).__name__}:{status}"
                )

            latency = round(
                (time.monotonic() - started) * 1000,
                1
            )

            writer.writerow({
                "timestamp": now(),
                "document_id": document_id,
                "write": write,
                "read": read,
                "latency_ms": latency,
                "error": error
            })

            f.flush()

            print(
                f"{now()} "
                f"WRITE={write} "
                f"READ={read} "
                f"LATENCY={latency}ms "
                f"{error}",
                flush=True
            )

            time.sleep(
                max(0, 2 - latency / 1000)
            )


def report(filename):
    with open(filename, newline="") as f:
        rows = list(csv.DictReader(f))

    if not rows:
        print("No monitoring data.")
        return

    def success(row):
        return (
            row["write"] == "OK"
            and row["read"] == "OK"
        )

    passed = [
        row for row in rows if success(row)
    ]

    failed = [
        row for row in rows if not success(row)
    ]

    values = sorted(
        float(row["latency_ms"])
        for row in passed
    )

    print("===== RESILIENCE REPORT =====")
    print(f"Total probes: {len(rows)}")
    print(f"Successful probes: {len(passed)}")
    print(f"Failed/incomplete: {len(failed)}")

    print(
        "Success rate: "
        f"{len(passed) / len(rows) * 100:.2f}%"
    )

    if values:
        p95 = math.ceil(len(values) * 0.95) - 1

        print(
            f"Average latency: "
            f"{statistics.mean(values):.1f}ms"
        )

        print(
            f"P95 latency: {values[p95]:.1f}ms"
        )

    times = [
        datetime.fromisoformat(row["timestamp"])
        for row in passed
    ]

    if len(times) >= 2:
        gaps = [
            (b - a).total_seconds()
            for a, b in zip(times, times[1:])
        ]

        print(
            "Longest gap between successful probes: "
            f"{max(gaps):.2f}s"
        )

    if failed:
        print("Client-visible failures observed.")
    else:
        print("No client-visible failures observed.")

    print(
        "Results are client observations, "
        "not a guaranteed service RTO."
    )


def verify_acknowledged(filename):
    container = connect()

    with open(filename, newline="") as f:
        rows = list(csv.DictReader(f))

    acknowledged = [
        row for row in rows
        if row["write"] == "OK"
    ]

    valid = 0
    unreadable = 0

    for row in acknowledged:
        try:
            container.read_item(
                item=row["document_id"],
                partition_key="probe"
            )
            valid += 1

        except Exception:
            unreadable += 1

    print(f"Acknowledged: {len(acknowledged)}")
    print(f"Readable: {valid}")
    print(f"Missing/unreadable: {unreadable}")

    if unreadable:
        raise SystemExit(
            "ACKNOWLEDGED WRITE CHECK FAILED"
        )

    print("ACKNOWLEDGED WRITE CHECK: PASS")


def bad_key():
    wrong_key = base64.b64encode(
        b"invalid-lab-credential" * 4
    ).decode()

    try:
        container = connect(key=wrong_key)

        container.read_item(
            item="order-000",
            partition_key="customer-00"
        )

        print("Unexpected authentication success.")

    except Exception as exc:
        print(
            "Authentication failure: "
            f"{type(exc).__name__}: "
            f"{getattr(exc, 'status_code', 'unknown')}"
        )


def bad_partition():
    container = connect()

    try:
        container.read_item(
            item="order-000",
            partition_key="incorrect-customer"
        )

        print("Unexpected lookup success.")

    except Exception as exc:
        print(
            "Partition lookup failure: "
            f"{type(exc).__name__}: "
            f"{getattr(exc, 'status_code', 'unknown')}"
        )


parser = argparse.ArgumentParser()

parser.add_argument("action", choices=[
    "seed",
    "verify",
    "monitor",
    "report",
    "verify-acked",
    "bad-key",
    "bad-partition"
])

parser.add_argument(
    "--file",
    default="probes.csv"
)

parser.add_argument(
    "--stop-file",
    default="stop-monitor.flag"
)

args = parser.parse_args()

if args.action == "seed":
    seed()

elif args.action == "verify":
    verify()

elif args.action == "monitor":
    monitor(args.file, args.stop_file)

elif args.action == "report":
    report(args.file)

elif args.action == "verify-acked":
    verify_acknowledged(args.file)

elif args.action == "bad-key":
    bad_key()

elif args.action == "bad-partition":
    bad_partition()
PY

Verify that the script is syntactically valid:

"$PYTHON" -m py_compile cosmos-resilience.py

You now have one application for the entire mega lab.

Step 7 — Generate and Verify 100 Customer Orders

Create the test data:

"$PYTHON" cosmos-resilience.py seed

Expected:

100 customer orders created.

Verify every record:

"$PYTHON" cosmos-resilience.py verify

Expected:

Valid records: 100
Mismatched/unreadable: 0
DATA INTEGRITY: PASS

The orders contain deterministic checksums.

This allows us to detect unexpected data modifications after failover.

Checkpoint: The data must be valid before initiating any regional change.

Step 8 — Establish the Working Baseline

Before changing the write region, inspect the current routing and database metrics.

Check the writable region:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "writeLocations[].locationName" \
  --output table

Expected:

West Europe

Retrieve the account ID:

export COSMOS_ID=$(az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query id \
  --output tsv)

Inspect request metrics:

az monitor metrics list \
  --resource "$COSMOS_ID" \
  --metric "TotalRequests" \
  --interval PT1M \
  --aggregation Total \
  --output json

Inspect request unit consumption:

az monitor metrics list \
  --resource "$COSMOS_ID" \
  --metric "TotalRequestUnits" \
  --interval PT1M \
  --aggregation Total \
  --output json

Our database is ready.

We can now begin the actual resilience exercise.

Step 9 — Run the Complete Regional Failover Exercise

This is the central part of the mega lab.

We will automate the following sequence:

  1. Start continuous database traffic.

  2. Collect baseline measurements.

  3. Record the failover start timestamp.

  4. Promote the secondary region.

  5. Continue recording application traffic.

  6. Verify the new write region.

  7. Stop the monitoring process.

  8. Generate the recovery report.

  9. Validate acknowledged writes.

We'll create one reusable Bash function so we can use the same process for failover and failback.

Create the transition function

Copy the complete block into Azure Cloud Shell:

run_transition() {

  local LABEL="$1"
  local NEW_PRIMARY="$2"
  local NEW_SECONDARY="$3"

  local CSV_FILE="${LABEL}-probes.csv"
  local LOG_FILE="${LABEL}-monitor.log"
  local STOP_FILE="${LABEL}-stop.flag"

  rm -f "$STOP_FILE"

  echo "================================"
  echo "STARTING REGIONAL TRANSITION"
  echo "================================"
  echo "Scenario: $LABEL"
  echo "New primary: $NEW_PRIMARY"
  echo "Previous primary: $NEW_SECONDARY"

  # Start continuous application traffic
  "$PYTHON" cosmos-resilience.py monitor \
    --file "$CSV_FILE" \
    --stop-file "$STOP_FILE" \
    > "$LOG_FILE" 2>&1 &

  local MONITOR_PID=$!

  echo "Monitor PID: $MONITOR_PID"

  # Collect a baseline before the role change
  sleep 45

  if ! kill -0 "$MONITOR_PID" 2>/dev/null; then
    echo "Monitoring process exited unexpectedly."
    cat "$LOG_FILE"
    return 1
  fi

  date -u +"%Y-%m-%dT%H:%M:%SZ" \
    | tee "${LABEL}-start.txt"

  # Perform the planned write-region transition
  if ! az cosmosdb failover-priority-change \
    --resource-group "$RG" \
    --name "$COSMOS" \
    --failover-policies \
      "${NEW_PRIMARY}=0" \
      "${NEW_SECONDARY}=1"; then

    echo "Regional transition command failed."

    touch "$STOP_FILE"
    wait "$MONITOR_PID" || true

    return 1
  fi

  date -u +"%Y-%m-%dT%H:%M:%SZ" \
    | tee "${LABEL}-end.txt"

  # Continue observing after the transition
  sleep 90

  # Stop the monitoring loop
  touch "$STOP_FILE"

  wait "$MONITOR_PID" || return 1

  echo "================================"
  echo "CURRENT WRITE REGION"
  echo "================================"

  az cosmosdb show \
    --resource-group "$RG" \
    --name "$COSMOS" \
    --query "writeLocations[].locationName" \
    --output table

  echo "================================"
  echo "APPLICATION RESILIENCE REPORT"
  echo "================================"

  "$PYTHON" cosmos-resilience.py report \
    --file "$CSV_FILE"

  echo "================================"
  echo "ACKNOWLEDGED WRITE VALIDATION"
  echo "================================"

  "$PYTHON" cosmos-resilience.py verify-acked \
    --file "$CSV_FILE"
}

The monitoring process runs in the same Cloud Shell session as the Azure CLI operations. Keep that session connected throughout the test.

Execute the planned failover

Now run:

run_transition \
  "failover-to-north" \
  "northeurope" \
  "westeurope"

This executes the whole sequence.

The database's primary write location changes from West Europe to North Europe.

While the change occurs, our Python client continues issuing read/write operations.

What should happen?

You may observe successful requests throughout the failover, transient request failures, increased latency, or a combination of these behaviors.

The SDK can retry supported transient operations and update its regional endpoint information.

The exact behavior depends on the service, networking, SDK version, and request timing.

Expected final configuration

Primary write region: North Europe
Secondary region:     West Europe

Example report

The following illustrates the format, not actual measurements:

===== RESILIENCE REPORT =====

Total probes: 210
Successful probes: 205
Failed/incomplete: 5

Success rate: 97.62%

Average latency: 115.8ms
P95 latency: 286.4ms

Longest gap between successful probes: 14.2s

Client-visible failures observed.

Your actual result may contain zero failed operations.

That is still a valid outcome.

Do not report simulated downtime or recovery numbers as actual measurements.

Step 10 — Diagnose the Failover Results

We now have a dataset containing actual client observations.

Inspect the raw monitoring output:

tail -n 40 failover-to-north-monitor.log

Inspect the CSV:

head -n 10 failover-to-north-probes.csv

Find operations that were unsuccessful:

awk -F, '
NR == 1 || $3 != "OK" || $4 != "OK"
' failover-to-north-probes.csv

Look for patterns such as:

WRITE=OK READ=OK
WRITE=FAIL READ=SKIPPED
WRITE=OK READ=FAIL
WRITE=OK READ=OK

Also review any recorded HTTP status codes.

Examples of Cosmos DB responses worth investigating include:

Status

Meaning

401

Authentication failure

403

Forbidden or access restriction

404

Resource or document not found

408

Request timeout

429

Request rate too large

503

Service unavailable

Not every transient failure during the exercise will appear as a failed probe. Some are retried internally by the SDK.

Inspect Azure Monitor

az monitor metrics list \
  --resource "$COSMOS_ID" \
  --metric "TotalRequests" \
  --interval PT1M \
  --aggregation Total \
  --output json

Use supported metric dimensions and regional filtering to investigate where requests were processed.

Remember that Azure Monitor service metrics and the application CSV measure different things.

Azure Monitor shows service-side activity.

Our test client measures the behavior observed by one running application.

Step 11 — Verify the Data After Failover

Now let's verify the most important part of the exercise.

Can we still retrieve the original customer orders?

Run:

"$PYTHON" cosmos-resilience.py verify

Expected:

Valid records: 100
Mismatched/unreadable: 0
DATA INTEGRITY: PASS

Now verify the probe writes acknowledged by the client:

"$PYTHON" cosmos-resilience.py verify-acked \
  --file failover-to-north-probes.csv

Expected:

ACKNOWLEDGED WRITE CHECK: PASS

This is stronger than simply observing that the database account is available.

We have now checked business records and successfully acknowledged test writes.

Important: This validates the data accessible during this planned failover test. It does not establish a guaranteed zero-data-loss RPO for unexpected regional outages.

Step 12 — BREAK: Simulate Application Authentication Failure

Our database is healthy in North Europe.

Now we'll simulate an application using an incorrect credential.

Run:

"$PYTHON" cosmos-resilience.py bad-key

Expected behavior:

Authentication failure:
CosmosHttpResponseError: 401

The exact exception can vary.

Diagnose

The database is running.

The write region is available.

The failure is caused by an invalid account key.

This is not a reason to initiate regional failover.

Repair

Our normal application configuration still contains the valid account key.

Verify access:

"$PYTHON" cosmos-resilience.py verify

Expected:

DATA INTEGRITY: PASS

We have demonstrated an application authentication incident and recovery without touching the database's regional configuration.

Step 13 — BREAK: Simulate a Wrong Partition Key

Next, we'll simulate a common Azure Cosmos DB application problem.

The client queries a document using the wrong partition key.

Run:

"$PYTHON" cosmos-resilience.py bad-partition

Expected:

Partition lookup failure:
CosmosResourceNotFoundError: 404

The order still exists.

But the point read does not use the correct partition-key value.

Diagnose

Our synthetic data uses:

Document ID: order-000

Partition Key Path: /customerId

Partition Key Value: customer-00

A point read requires the correct document ID and partition key.

Repair

Verify with the original application logic:

"$PYTHON" cosmos-resilience.py verify

Expected:

DATA INTEGRITY: PASS

Key lesson: A 404 is not proof of a regional data-loss incident.

Step 14 — Perform the Planned Failback

Our account currently writes to North Europe.

We will now restore the original configuration, using the same monitoring and reporting workflow.

Run:

run_transition \
  "failback-to-west" \
  "westeurope" \
  "northeurope"

This will:

  • Start new continuous read/write traffic.

  • Record baseline measurements.

  • Change the primary write region back to West Europe.

  • Continue measuring after the transition.

  • Verify the new write region.

  • Generate a second resilience report.

  • Validate acknowledged writes.

After successful completion, the primary region should be West Europe again.

Verify:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "writeLocations[].locationName" \
  --output table

Expected:

West Europe

Verify data after failback

"$PYTHON" cosmos-resilience.py verify

Verify both batches of acknowledged probe writes:

"$PYTHON" cosmos-resilience.py verify-acked \
  --file failover-to-north-probes.csv
"$PYTHON" cosmos-resilience.py verify-acked \
  --file failback-to-west-probes.csv

Both should pass.

Step 15 — Compare Failover and Failback

We have completed two planned write-region transitions.

Let's compare the client-observed behavior.

Run:

"$PYTHON" cosmos-resilience.py report \
  --file failover-to-north-probes.csv

Then:

"$PYTHON" cosmos-resilience.py report \
  --file failback-to-west-probes.csv

Record your results:

Measurement

Failover to North

Failback to West

Total probes

Record result

Record result

Successful probes

Record result

Record result

Failed probes

Record result

Record result

Success rate

Record %

Record %

Average latency

Record ms

Record ms

P95 latency

Record ms

Record ms

Longest successful-probe gap

Record seconds

Record seconds

Acknowledged writes validated

Record count

Record count

Final write region correct

Yes/No

Yes/No

You can also compare the management-operation timestamps.

echo "FAILOVER"
cat failover-to-north-start.txt
cat failover-to-north-end.txt

echo "FAILBACK"
cat failback-to-west-start.txt
cat failback-to-west-end.txt

These timestamps measure the Azure CLI management operation, not necessarily the exact interval of application unavailability.

What did we learn?

The two transitions may produce different results.

For example, they may have different latency characteristics or different numbers of unsuccessful requests.

This can depend on transient service conditions, client region, network latency, SDK caching, and when requests occur relative to the transition.

The relevant lesson is that resilience must be measured rather than assumed.

Step 16 — Final Enterprise Validation

Before cleaning up the environment, verify the full configuration.

Check account health:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "{
    Name:name,
    State:provisioningState,
    Consistency:consistencyPolicy.defaultConsistencyLevel,
    AutomaticFailover:enableAutomaticFailover,
    MultiWrite:enableMultipleWriteLocations
  }" \
  --output json

Check regional configuration:

az cosmosdb show \
  --resource-group "$RG" \
  --name "$COSMOS" \
  --query "locations[].{
    Region:locationName,
    Priority:failoverPriority
  }" \
  --output table

Verify original data:

"$PYTHON" cosmos-resilience.py verify

Check the container:

az cosmosdb sql container show \
  --resource-group "$RG" \
  --account-name "$COSMOS" \
  --database-name "$DATABASE" \
  --name "$CONTAINER" \
  --output json

Final state

Component

Expected state

Cosmos DB account

Succeeded

Primary region

West Europe

Secondary region

North Europe

Single-write configuration

Enabled

Automatic failover

Enabled

Consistency

Session

Database

Available

Container

Available

Original 100 orders

Valid

First transition

Measured

Second transition

Measured

Acknowledged probe writes

Readable

Authentication test

Completed

Partition-key test

Completed

Step 17 — Clean Up the Environment

This lab uses billable Cosmos DB resources in two regions.

Delete them after finishing.

Review the resources:

az resource list \
  --resource-group "$RG" \
  --output table

Delete the resource group:

az group delete \
  --name "$RG" \
  --yes

Verify deletion:

az group exists \
  --name "$RG"

Expected:

false

Clear the temporary credentials:

unset COSMOS_KEY
unset COSMOS_ENDPOINT

Remove the local working files when you no longer need them:

cd "$HOME"

rm -rf "$LAB_DIR"

Preserve the measurement CSVs first if you want to publish real failover statistics.

Cleanup complete.

Workshop Review

We have completed one integrated enterprise resilience scenario.

Technology

What we demonstrated

Azure Cosmos DB for NoSQL

Globally distributed database

Multi-region replication

Replication across two regions

Single-write configuration

Primary and secondary regions

Service-managed failover

Regional failover configuration

Planned failover

Promotion of another write region

Session consistency

Read-your-writes behavior within sessions

Python SDK

Region-aware application access

Synthetic workloads

Continuous read/write traffic

CSV measurements

Client success, failure, and latency

Data checksums

Verifying stored business data

Azure Monitor

Database platform metrics

Authentication troubleshooting

Invalid credential simulation

Partition-key troubleshooting

Incorrect point-read simulation

Planned failback

Restoring original write region

Azure CLI

Deployment and lifecycle management

The most important lessons

1. Two regions do not automatically mean an application has been resilience-tested.

You must verify how applications behave during regional transitions.

2. Planned failover is not the same as an unplanned region outage.

The measured results of this lab should not be represented as a formal disaster-recovery guarantee.

3. SDK behavior is critical.

Endpoint discovery, retries, preferred regions, and session handling affect application resilience.

4. Successful writes must be verified.

Checking actual acknowledged records is more useful than checking resource provisioning alone.

5. Not every database error indicates a regional problem.

Authentication failures, incorrect partition keys, and request throttling require different troubleshooting approaches.

6. Real measurements matter.

Record actual error counts, latency, availability, and recovery observations rather than relying on assumed values.

Final Challenge

After completing the workshop, consider these questions:

  1. What happens when the primary write region changes?

  2. How does the Cosmos DB SDK discover the new writable region?

  3. What does Session consistency guarantee?

  4. Why might some applications observe no failed requests during planned failover?

  5. How do application-observed interruptions differ from service-level RTO?

  6. What is the difference between planned failover and an unexpected regional outage?

  7. What can acknowledged-write verification demonstrate?

  8. Why does a 401 error not indicate a regional outage?

  9. Why can an incorrect partition key produce a 404?

  10. How would you extend this workshop to test multiple-write-region Cosmos DB accounts?

Conclusion

Azure Cosmos DB makes globally distributed applications possible, but multi-region infrastructure alone does not prove operational resilience.

In this mega lab, we deployed a real two-region Cosmos DB environment, generated business records, continuously tested reads and writes, performed a planned failover, measured client behavior, and verified data integrity.

We then investigated application failures, restored normal operation, and completed a planned failback.

The critical takeaway is that database resilience is a combination of regional infrastructure, replication, consistency, SDK behavior, and application-level recovery logic.

A successful failover test should produce evidence that you can analyze, repeat, and compare.

Deploy. Replicate. Break. Failover. Diagnose. Recover. Verify.

Official Microsoft Documentation

Azure Workshopz | Beyond Cloud with Chriz

Hands-on Azure workshops focused on resilience, cloud operations, troubleshooting, and disaster recovery.

 
 
 

Comments


bottom of page