Skip to main content

Okustera Zero-Downtime Database Migration & Upgrades

An enterprise-grade, production-tested showcase of Zero-Downtime Database Upgrades and Major Engine Migrations on the Okustera Cloud Platform.

This quickstart demonstrates how an ACID-compliant transactional microservice (Order Ledger & Billing Service) processes live customer orders without dropping a single write transaction or returning HTTP 5xx errors while the underlying Managed PostgreSQL cluster undergoes:

  1. Minor In-Place Rolling Upgrade: PostgreSQL 16.2 → 16.5 with automated standby-first patching and sub-second leader switchover.
  2. Major Engine Migration: PostgreSQL 16.5 → 17.0 using Blue-Green dual clustering, live delta synchronization (CDC), and atomic endpoint cutover.

1. System Architecture​


2. Project Structure​

database-migration-demo/
├── README.md # Architecture runbook & benchmarks
├── terraform/ # Declarative Infrastructure as Code
│ ├── main.tf # Okustera & Kubernetes provider declarations
│ ├── variables.tf # Engine versions, replicas, & cluster parameters
│ ├── database.tf # Managed PostgreSQL primary (v16) & Blue-Green (v17) resources
│ ├── workload.tf # Application deployment, secret, & service definitions
│ └── outputs.tf # Active versions, endpoints, & migration mode
├── app/ # Order Ledger Microservice (FastAPI + asyncpg)
│ ├── main.py # Transactional REST API (/orders, /metrics, /healthz)
│ ├── database.py # Resilient connection pool with exponential query retries
│ ├── models.py # SQLAlchemy ORM models (orders, ledger_audits)
│ ├── Dockerfile # Application container definition
│ └── requirements.txt # Python runtime dependencies
└── scripts/ # Simulation, Automation, & Verification
├── traffic_generator.py # Concurrent traffic generator & real-time latency auditor
├── verify_integrity.py # Baseline capture & post-upgrade checksum validator
├── run_minor_upgrade.sh # Automated in-place rolling upgrade runner (16.2 -> 16.5)
└── run_major_upgrade.sh # Automated Blue-Green live cutover runner (16.5 -> 17.0)

3. Resilience Engineering: Absorbing Switchover Failovers​

During database switchovers (such as promoting a synchronized standby to primary or performing an atomic Blue-Green endpoint cutover), active connections to the outgoing primary receive transient connection resets or admin_shutdown signals.

The order-ledger-app shields callers using an exponential-backoff retry interceptor (app/database.py):

async def execute_with_retry(
operation,
*args,
max_retries: int = 12,
initial_delay: float = 0.15,
max_delay: float = 1.5,
**kwargs,
):
"""
Catches transient TCP drops, read-only transitions, and 'admin_shutdown'
signals emitted during leader promotions and Blue-Green endpoint cutovers.
"""
delay = initial_delay
for attempt in range(1, max_retries + 1):
try:
return await operation(*args, **kwargs)
except (
ConnectionResetError,
BrokenPipeError,
OSError,
OperationalError,
DBAPIError,
asyncpg.exceptions.PostgresError,
asyncpg.exceptions.InterfaceError,
):
if attempt == max_retries:
raise
# Dispose pooled connections so the next attempt opens a fresh socket
await engine_rw.dispose()
await engine_ro.dispose()
await asyncio.sleep(delay)
delay = min(delay * 1.5, max_delay)
  • Client Impact: Incoming HTTP write and read requests pause briefly (~120–380 ms) while the pool disposes stale sockets and reconnects to the promoted leader or Green cluster.
  • HTTP Result: Zero 500 errors returned to end users; 100% transaction success rate.

4. Declarative Terraform Configuration​

Database Resource Declaration (terraform/database.tf)​

# Primary High-Availability Managed PostgreSQL Cluster (PostgreSQL 16.2)
resource "okustera_database_postgresql" "order_db" {
name = "order-ledger-db"
namespace = var.namespace
instances = 3
version = var.postgres_version # 16.2 -> 16.5 for minor rolling upgrade
storage_size = "10Gi"
database_name = "order_ledger"
username = var.db_username
password = var.db_password
}

# Target Green Cluster (PostgreSQL 17.0) for Blue-Green Cutover
resource "okustera_database_postgresql" "order_db_v17" {
count = var.enable_major_migration ? 1 : 0
name = "order-ledger-db-v17"
namespace = var.namespace
instances = 3
version = var.postgres_major_target_version
storage_size = "10Gi"
database_name = "order_ledger"
username = var.db_username
password = var.db_password
}

5. Operational Runbooks​

Managed DBaaS Upgrade Interfaces

In Okustera Managed DBaaS, upgrades and migrations are triggered declaratively through Terraform, the DBaaS REST API, or the Cloud Portal. Before starting an upgrade, Okustera automatically verifies cluster quorum, zero replication lag, storage headroom, and snapshot readiness, with built-in rollback protection if any health check fails.

Scenario 1: Minor In-Place Rolling Upgrade (16.2 → 16.5)​

Minor version updates share identical on-disk storage layouts. Standby replicas are patched and verified sequentially. Once streaming replication converges (lag = 0), a graceful switchover promotes a patched standby to primary, and the former primary rejoins as a synchronized replica.

Step 1: Capture Pre-Upgrade Baseline Metrics​

python3 scripts/verify_integrity.py \
--url https://orders.example.com \
--save-baseline /tmp/pre_upgrade_baseline.json

Step 2: Start Continuous Load & Trigger Upgrade​

In one terminal, start continuous background write/read traffic:

python3 scripts/traffic_generator.py \
--url https://orders.example.com \
--duration 45 --writers 6 --readers 15

While traffic is running, trigger the upgrade via Terraform or the DBaaS REST API:

Option A: Declarative Terraform (Recommended)

# Direct Terraform apply:
terraform apply -var="postgres_version=16.5"

# Or via the automated traffic audit runner:
./scripts/run_minor_upgrade.sh https://orders.example.com --terraform

Option B: DBaaS REST API

curl -X POST \
-H "Authorization: Bearer <YOUR_API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"target_version": "16.5", "auto_rollback": true}' \
https://portal.okustera.com/api/v1/dbaas/clusters/postgres/migration-workload/order-ledger-db/upgrade

Live Traffic Audit Output:​

==========================================================================================
Okustera Live Database Migration Traffic Auditor
==========================================================================================
Time | Total Req | Writes (p95) | Reads (p95) | 5xx Errors | Switchover Retries
------------------------------------------------------------------------------------------
05s | 768 | 165 (319.7ms) | 587 (181.4ms) | 0 | 38
15s | 2350 | 466 (325.6ms) | 1869 (191.8ms) | 0 | 143
25s | 3653 | 755 (334.1ms) | 2878 (262.4ms) | 0 | 240
35s | 4921 | 1016 (397.6ms) | 3892 (327.1ms) | 0 | 365
44s | 6063 | 1254 (317.1ms) | 4797 (241.0ms) | 0 | 479
------------------------------------------------------------------------------------------
==========================================================================================
MIGRATION AUDIT FINAL REPORT
==========================================================================================
Total Requests Executed : 6201
Total Succeeded (2xx) : 6201 (100.00%)
Total Failed (5xx/Drops) : 0 (0.00%)
Write Latency Metrics : p50=127.8ms | p95=385.5ms | p99=624.0ms
Switchover Absorption : 490 queries retried and absorbed transparently
------------------------------------------------------------------------------------------
VERDICT: ZERO DOWNTIME CERTIFIED - ZERO TRANSACTIONS DROPPED
==========================================================================================

Step 3: Validate Post-Upgrade Data Integrity​

python3 scripts/verify_integrity.py \
--url https://orders.example.com \
--compare-with /tmp/pre_upgrade_baseline.json
======================================================================
DATABASE CLUSTER CURRENT METRICS
======================================================================
Total Orders Recorded : 1971
Total Ledger Balance : 514585.94 EUR
PostgreSQL Version : PostgreSQL 16.5 on x86_64-pc-linux-gnu
Replication Role : Primary Leader
======================================================================
[INTEGRITY AUDIT]
Baseline Orders : 678 | Current Orders: 1971
Baseline Balance: 179122.63 | Current Balance: 514585.94
Baseline Version: PostgreSQL 16.2
Current Version : PostgreSQL 16.5
DATA INTEGRITY VERIFIED: All baseline orders and ledger balances preserved.

Scenario 2: Major Blue-Green Live Migration (16.5 → 17.0)​

Major PostgreSQL releases modify internal system catalogs and on-disk storage formats, so Okustera provisions a parallel Green cluster running PostgreSQL 17, streams incremental changes until parity is reached, and performs an atomic endpoint cutover.

Step 1: Trigger Major Upgrade via Terraform or REST API​

# Direct Terraform apply:
terraform apply -var="enable_major_migration=true"

# Or via the automated traffic audit runner:
./scripts/run_major_upgrade.sh https://orders.example.com --terraform

Or via the DBaaS REST API:

curl -X POST \
-H "Authorization: Bearer <YOUR_API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"target_version": "17.0", "auto_rollback": true}' \
https://portal.okustera.com/api/v1/dbaas/clusters/postgres/migration-workload/order-ledger-db/upgrade

Step 2: Managed Data Synchronization & Parity Verification​

  1. Parallel Green Cluster Bootstrap: Okustera provisions order-ledger-db-v17 on dedicated replicated NVMe volumes and imports the baseline dataset from the active Blue cluster.
  2. Live Delta Catch-Up: Transactions committed to the Blue cluster while Green initializes are synchronized continuously until replication lag converges to zero and row checksum parity is verified.

Step 3: Atomic Endpoint Cutover & Connection Pool Refresh​

  1. Okustera atomically switches the active read-write and read-only endpoints (order-ledger-db-active-rw and order-ledger-db-active-ro) to point to the synchronized PostgreSQL 17 Green cluster.
  2. Active client sessions on the Blue cluster are gracefully drained so the microservice's execute_with_retry handler refreshes its connection pool and immediately routes subsequent transactions to PostgreSQL 17 with zero dropped writes.
  3. A final consistency check verifies that 100% of orders committed prior to cutover are present on the Green cluster.

Live Blue-Green Traffic Audit & Integrity Output:​

==========================================================================================
MIGRATION AUDIT FINAL REPORT
==========================================================================================
Total Requests Executed : 9246
Total Succeeded (2xx) : 9246 (100.00%)
Total Failed (5xx/Drops) : 0 (0.00%)
Write Latency Metrics : p50=111.6ms | p95=305.9ms | p99=570.9ms
Switchover Absorption : 587 queries retried and absorbed transparently
------------------------------------------------------------------------------------------
VERDICT: ZERO DOWNTIME CERTIFIED - ZERO TRANSACTIONS DROPPED
==========================================================================================

[INTEGRITY AUDIT]
Baseline Orders : 3869 | Current Orders: 5640
Baseline Balance: 999280.66 | Current Balance: 1449936.88
Baseline Version: PostgreSQL 16.5 on x86_64-pc-linux-gnu
Current Version : PostgreSQL 17.0 on x86_64-pc-linux-gnu
DATA INTEGRITY VERIFIED: All baseline orders and ledger balances preserved.

6. Service Level Agreements (SLA) & Verified Benchmarks​

Operational MetricTarget SLAVerified Live Benchmark (15,447 Total Requests)
Minor Upgrade (16.2 -> 16.5) Requests100% HTTP 2xx6,201 / 6,201 (100.00% success, 0 drops, 490 retries absorbed)
Major Migration (16.5 -> 17.0) Requests100% HTTP 2xx9,246 / 9,246 (100.00% success, 0 drops, 587 retries absorbed)
Minor Upgrade Write Latency< 1 secondp50=127.8ms | p95=385.5ms | p99=624.0ms
Major Upgrade Write Latency< 5 secondsp50=111.6ms | p95=305.9ms | p99=570.9ms
Data & Financial Ledger Fidelity100%0 dropped writes; 678 -> 1,971 -> 5,640 orders verified (1,449,936.88 EUR)
Pre-Flight Readiness ChecksAll Checks PassedCluster quorum, zero replication lag, storage headroom, snapshot verified