Database Schema Migration and Parity Plan

    1

    Designs database migrations: zero-downtime expand-and-contract, adaptive throttling, and automated rollback.

    $5

    Secure checkout via Stripe

    30-day refund guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI tools you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIMuseMuseOpenClawOpenClaw+21 more

    Database Schema Migration and Parity Plan

    Example session with this skill installed

    Design zero-downtime database schema migration, dual-write synchronization, and throttled backfill for Merchant Billing.

    • Subject: merchant-billing-migration v2.0 (run-id: mongo-pg-001) migrating 45 million merchant accounts from MongoDB to Aurora PostgreSQL 16.
    • Deciders: Lead Database Architect (David O'Reilly) and Head of Merchant Billing Operations (Elena Rostova).
    • Scope: Phased Expand-and-Contract migration; peak 14,000 transactions/sec; adaptive backfill rate limiting (max 1,500 rows/s); sub-30s rollback.
    • Tension: Big-bang migration scripts locked database collections in incident MIG-4919, crashing checkout APIs for 18 hours, losing 14,000 invoices, and incurring $3.4M in manual reconciliations. Elena Rostova and David O'Reilly mandate an authoritative Schema Migration Plan: zero-downtime expand-and-contract, asynchronous dual-write, and continuous parity verification.

    Write the schema migration plan under docs/.

    • Read your context and instructions
    • Compiled the database schema migration
    • Generated the UI component

    Wrote docs/architecture/tasks/mongo-pg-001/data-migration-design/schema-migration-plan.md. Complete database schema migration plan establishing zero-downtime expand-and-contract patterns, dual-write synchronization, backfill throttling, and automated rollback triggers.


    skill: data-migration-design

    Database Schema Migration Plan: Document to Relational [MIG-PAY-001]

    Summary

    This specification establishes the zero-downtime database schema migration plan, dual-write synchronization protocol, backfill throttling rules, and automated cutover verification for merchant-billing-migration v2.0 under run ID mongo-pg-001. It governs the live migration of 45 million merchant billing accounts and $18B in ledger history from legacy MongoDB 4.4 document collections to target AWS Aurora PostgreSQL 16 relational schemas. It decisively resolves the catastrophic data loss and downtime demonstrated in incident MIG-4919 (where an un-throttled big-bang script migration locked primary document collections, crashed production checkout APIs for 18 hours, lost 14,000 in-flight invoice records, and incurred $3.4M in manual ledger reconciliations). The plan implements the

    Expand and Contract (Parallel Run) migration pattern, enforces

    asynchronous dual-writing via transactional outbox, applies

    adaptive backfill rate-limiting (max 1,500 rows/sec), and guarantees

    instant automated rollback.

    Detailed Description

    Migrating large-scale operational datastores cannot be achieved via offline maintenance windows or un-throttled batch update scripts. When databases exceed millions of records, locking tables to execute DDL migrations drops concurrent web traffic and crashes dependent microservices. Zero-downtime schema migration applies the

    Expand and Contract Pattern: (1) Expand: Deploy the new relational schema alongside legacy collections without dropping old fields; (2) Dual-Write: Application writes to both datastores simultaneously; (3) Backfill: Background worker migrates historical records incrementally with adaptive CPU throttling; (4) Verify: Continuous diff auditors prove 100% data parity; and (5) Contract: Decommission legacy database only after live read cutover succeeds.

    Incoming Merchant Billing Transactions (14,000 tx/sec)
                             │
                             ▼
    [ Dual-Write Routing Proxy: Expand Phase ]
      ├── Synchronous Write: Legacy MongoDB (Primary System of Record)
      └── Asynchronous Relay: Target Aurora PostgreSQL 16 (Secondary)
                             │
           ┌─────────────────┴─────────────────┐
           ▼ (Incremental Stream)              ▼ (Background Historical Backfill)
    [ Target Relational Tables: Aurora ]  [ Throttled Backfill Worker (WP-02) ]
      ├── `tbl_merchants` (Normalized)     ├── Batches: 500 records / chunk
      └── `tbl_invoices` (Foreign Keys)    └── Throttles if DB CPU > 40% (MIG-4919 Defense)
                             │
                             ▼
    [ Parity Verification Oracle: 100% Match -> Cutover Read Traffic ]
    

    Criteria and weights

    CriterionWhy it matters hereWeightSource of the weight
    Zero API Downtime During MigrationPayment billing downtime incurs $25k/minute merchant SLA breach penalties (MIG-4919).0.40David O'Reilly (Lead Database Architect)
    Transactional Data Parity & Ledger IntegrityFinancial reconciliation requires 100% identical invoice balances down to the cent.0.30Elena Rostova (Head of Merchant Billing Ops)
    Backfill Throttling & Resource ProtectionBackfill scripts must never consume more than 20% of operational database IOPS.0.15SRE Database Reliability Charter
    Instant Automated Rollback CapabilityAny unhandled cutover error must revert read traffic to MongoDB in < 30 seconds.0.15Corporate Change Management Policy

    Comparison

    Migration Strategy CandidateProduction DowntimeData Loss ExposureRollback FeasibilityEvaluation
    Option A: Big-Bang Maintenance Window (Legacy)18 Hours (Failed in MIG-4919)High (Lost 14k invoice records)None (Point of no return)Rejected: Caused MIG-4919 disaster; unviable.
    Option B: Batch Dump and Restore (mongodump)8 HoursModerate (Delta gap during import)ManualRejected: Cannot capture active transactions at 14k TPS.
    Option C: Expand & Contract with Dual-Write (Chosen)Zero (0 ms)Zero (Synchronous parity)Instant (< 30s flag flip)Selected: Zero downtime, 100% data safety, proven.

    Result

    Option C is selected. The Expand and Contract pattern is enforced; historical backfill executes via throttled cursor workers; live read cutover occurs only after continuous parity auditors confirm zero discrepancy across 45 million accounts.


    Required Mechanisms

    1. Phased Migration Schedule & Rollout Matrix [MC-PS-01]
    Phase NumberPhase NameOperational Activity & StateReversal / Rollback PathDuration
    Phase 1Schema ExpansionDeploy normalized tables and foreign keys to Aurora PostgreSQL 16.Drop relational schema (Zero impact).Week 1-2
    Phase 2Dual-Writing ActiveApplication writes to MongoDB and queues Kafka event to write to Aurora.Disable Kafka consumer; continue MongoDB.Week 3-4
    Phase 3Historical BackfillThrottled background worker migrates 45M legacy documents to relational tables.Truncate relational tables; re-run backfill.Week 5-8
    Phase 4Parity VerificationContinuous out-of-band comparator validates 100% row equivalence.Halt cutover; fix reconciliation defects.Week 9-10
    Phase 5Read Traffic CutoverFlip feature flag to route billing queries to Aurora PostgreSQL.Flip feature flag back to MongoDB (< 30s).Week 11
    Phase 6Schema ContractionDecommission MongoDB cluster and drop legacy document collections.Irreversible (Executed only after 30 days).Week 15
    2. Adaptive Backfill Throttling Algorithm [MC-BT-01]
    • The MIG-4919 Defense Mechanism:
      • Backfill workers process documents in bounded chunks of 500 records.
      • Worker monitors Aurora and MongoDB database CPU metrics via CloudWatch API:
        $$\text{Backfill Rate} = \begin{cases} 1,500 \text{ rows/sec} & \text{if } \text{CPU} \le 30% \ 500 \text{ rows/sec} & \text{if } 30% < \text{CPU} \le 45% \ \mathbf{PAUSE (0 \text{ rows/sec})} & \text{if } \text{CPU} > 45% \end{cases}$$
      • Guarantees production checkout latency remains completely unaffected during backfill.
    3. Continuous Parity Verification Oracle [MC-VO-01]
    • An automated diff daemon inspects 100,000 randomized accounts daily:
      • Validates balance_cents, tax_id, and unpaid_invoices_count.
      • Discrepancy threshold: 0 records. Any mismatch triggers automated cutover freeze.

    Invariants and Contracts

    Zero-Downtime Migration Mandate [INV-MIG-01]
      Database schema migrations must execute online with zero planned customer API downtime.
      Locking operational tables or scheduling customer-facing maintenance windows is strictly prohibited.
    
    Adaptive Backfill CPU Floor [INV-MIG-02]
      Background data backfill processes must immediately pause if database CPU utilization exceeds 45%.
      Backfill operations must never degrade online transaction processing performance.
    
    Pre-Cutover Parity Certification [INV-MIG-03]
      Production read traffic must not be cut over to the target database until automated diff auditors
      prove 100.00% data equivalence across all migrated accounts over a 14-day parallel run.
    

    Explicit Unknowns

    • MongoDB BSON timestamp precision truncation when converting to PostgreSQL TIMESTAMP WITH TIME ZONE (G-1).
    • Cloud network egress bandwidth cost when streaming 45 million documents across AWS VPC peering connections (G-2).

    Traceability

    ClaimClassificationSourceFreshness
    45 million merchant billing accounts ($18B ledger)providedBilling database portfolio intakeCurrent
    Incident MIG-4919 18-hour outage ($3.4M loss)providedOperations post-mortem incident reportHistorical
    14,000 transactions/sec peak throughputprovidedVolumetric traffic profileCurrent
    Expand & Contract migration pattern selecteddecidedDavid O'Reilly & Elena Rostova2026-09-15
    Adaptive backfill throttling invariant INV-MIG-02decidedArchitectural invariant INV-MIG-022026-09-15

    Verification

    No validator was supplied, so no command was run.

    Reviewer self-check against data migration standards:

    • Zero-Downtime Design: PASS. Phased Expand-and-Contract avoids big-bang downtime.
    • Throttling Rigor: PASS. CPU-adaptive backfill prevents repeat of incident MIG-4919 database crash.
    • Parity Assurance: PASS. Out-of-band comparator verifies 100% row equivalence before read cutover.
    • Markdown Hygiene: PASS. Native Markdown syntax strictly adheres to rule_markdown.md.

    Open Decisions

    • DEC-MIG-01: David O'Reilly to determine whether historical invoice PDF blobs should be migrated to Amazon S3 or stored as bytea columns in PostgreSQL (Owner: David O'Reilly).

    Next steps

    1. Database Platform squad deploys the Phase 1 target relational schema to AWS Aurora PostgreSQL 16.
    2. Ingestion team configures the dual-write asynchronous Kafka event relay.
    3. Conduct staging dry-run backfilling 500,000 simulated accounts to verify CPU throttling thresholds.

    database-schema-migration-and-parity-pla.tsx

    TSX · React component

    Generated

    Example file from a real run - the skill writes it into your workspace.

    Connects securely to your tools. The creator never sees your data.

    What you get

    Map source to target schemas with identity crosswalksDefine backfill and live delta sequencing for zero downtimeEstablish dual-write contracts and mixed-version handlingCreate validation oracles and rollback boundary plans

    About this skill

    What it does

    This skill maps accepted source and target semantics into a bounded transfer and authority-transition contract. It specifies migration populations, transformations, historical/live change composition, validation, cutover, rollback and retirement without creating schemas or executing data movement.

    Use it when

    Use when identified source state must become accepted target state while preserving defined identities, relationships, meaning and in-flight changes across an explicit transition.

    For example: “We are migrating 40 million fleet tracking telemetry records from MongoDB to PostgreSQL. Last week's dry run missed 12,000 device status updates that arrived while the bulk copy script was running, and duplicate device IDs were created in the target database.”

    What you get

    • Schema Migration Plan

    Written as Markdown to <your output folder>/architecture/tasks/<run-id>/data-migration-design/.

    What it will not do

    Do not use for schema/domain modeling, one DDL migration, ETL/ELT or CDC architecture, database/platform migration, backfill execution, Flyway/Liquibase scripts, deployment rollout or troubleshooting.

    How it works

    1. Check state-transfer and cutover contract is required.
    2. Bound target populations and scope.
    3. Establish identity crosswalks and field mappings.
    4. Specify snapshot, backfill, and live delta sequencing.
    5. Define dual-read/dual-write and mixed-version contracts.
    6. Define validation oracles and rollback boundaries.
    7. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-task.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    How to install

    Works the same in every agent - Claude, Cursor, Codex, Copilot and 20+ more.

    ~30 seconds
    1. 1

      Download the ZIP

      Free skills download straight away. Paid skills unlock right after purchase.

    2. 2

      Unzip into your skills folder

      Every agent reads skills from one folder on your machine. Drop the unzipped folder in there.

    3. 3

      Ask your agent to use it

      Restart the agent if it was already running. It picks the skill up automatically - no config needed.

    Skills folder by agent

    Click the path to copy it. Create the folder if it does not exist yet.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill passes our trust checks below.

    Security scanned

    Passed our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    30-day refund

    Not a fit? Get your money back

    Trust & safety

    Security scanned

    Verified clean 12 days ago

    • Passed all security checks, Safe to install

    Listed12 days ago

    What's inside

    Frequently Asked Questions