Inferensys

Prompt

Database per Service Migration Planning Prompt

A practical prompt playbook for using a Database per Service Migration Planning Prompt in production AI workflows to generate phased, safe extraction plans.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal conditions, required inputs, and explicit boundaries for using the Database per Service Migration Planning Prompt.

This prompt is for teams that have already committed to a specific service boundary and need a concrete, phased plan to extract a set of tables from a shared database into a service-owned database. The ideal user is a backend engineer or architect who can provide a precise list of source tables, foreign key relationships, and the target service name. The prompt's job is not to debate whether the extraction is a good idea; it assumes the decision is made and focuses entirely on safe, sequenced execution. If you are still evaluating which tables belong to which service, use the Cross-Service Data Ownership Analysis Prompt first.

Before running this prompt, you must have a clear inventory of the tables to migrate, including their foreign key dependencies both within and outside the extraction set. The prompt requires you to specify a target service name, a list of tables, and any known cross-service foreign keys that will need to be broken or replaced with API calls. It will produce a phased migration plan that includes dual-write consistency windows, data synchronization checkpoints, and explicit rollback conditions for each phase. The output is designed to be reviewed by a database administrator and the owning engineering team before any migration step is executed in production.

Do not use this prompt for greenfield schema design, for evaluating whether a service boundary is correct, or for migrations where you cannot tolerate any dual-write period. This prompt assumes a shared database that is currently live and serving traffic; it does not cover offline data warehouse migrations or ETL-only pipelines. If your migration involves regulated data subject to strict consistency guarantees, you must add a human review gate after each phase and validate the plan against your specific compliance requirements before execution.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Database per Service Migration Planning Prompt works and where it introduces unacceptable risk. Use these cards to decide whether this prompt fits your current migration stage and system constraints.

01

Good Fit: Shared Database Extraction Planning

Use when: you have a shared database with clear table ownership boundaries and need a phased extraction plan. The prompt excels at analyzing foreign key dependencies, proposing dual-write windows, and sequencing extraction steps. Guardrail: provide the full schema DDL and entity ownership map as input; missing table relationships produce incomplete migration plans.

02

Bad Fit: Greenfield Service Design

Avoid when: you are designing services from scratch with no existing shared database. This prompt assumes an existing monolith schema to analyze and extract from. Guardrail: for greenfield work, use the Service Boundary Candidate Identification Prompt or Bounded Context Discovery Prompt instead.

03

Required Input: Full Schema with Foreign Keys

Risk: without complete foreign key relationships, the prompt cannot identify cross-table dependencies that would break during extraction. Guardrail: provide DDL including all FK constraints, views, triggers, and stored procedures that reference multiple tables. Incomplete schema input produces migration plans with hidden data integrity gaps.

04

Operational Risk: Dual-Write Consistency Windows

Risk: the prompt proposes dual-write periods where data flows to both the old shared database and the new service-owned database. Without application-level idempotency and reconciliation, this creates split-brain scenarios. Guardrail: validate every dual-write step against your application's idempotency guarantees and implement a reconciliation job before executing the plan.

05

Bad Fit: High-Throughput OLTP Without Maintenance Windows

Avoid when: your system cannot tolerate any write downtime or read replica lag during migration. The prompt assumes phased cutovers with brief consistency windows. Guardrail: for zero-downtime requirements, supplement the prompt output with a dedicated online schema migration tool assessment and load-test each extraction step against production traffic patterns.

06

Required Input: Rollback Safety Conditions

Risk: the prompt generates rollback conditions, but if your team cannot actually execute a rollback due to missing backups or irreversible schema changes, the plan creates false confidence. Guardrail: verify that every rollback gate in the plan corresponds to a tested, documented rollback procedure with point-in-time recovery capability before starting any extraction step.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for generating a phased database-per-service migration plan with foreign key impact analysis, dual-write consistency windows, and rollback safety conditions.

The prompt below is designed to be pasted directly into your AI harness. It expects you to replace square-bracket placeholders with your specific system context, including the current shared schema, the target service boundaries, and your organization's risk tolerance. The prompt instructs the model to produce a phased migration plan rather than a single-step cutover, which is critical for maintaining data integrity during the transition.

code
You are a database migration architect specializing in decomposing shared databases into service-owned databases. Your task is to produce a phased migration plan for extracting [TARGET_SERVICE] from the shared database described below.

## Current State
- Shared database schema (DDL or table descriptions): [SHARED_SCHEMA]
- Service to extract: [TARGET_SERVICE]
- Tables currently accessed by [TARGET_SERVICE]: [TARGET_TABLES]
- Other services sharing these tables: [DEPENDENT_SERVICES]
- Total row counts and write throughput per table: [TABLE_METRICS]
- Acceptable downtime window (if any): [DOWNTIME_WINDOW]
- Maximum acceptable dual-write latency: [MAX_LATENCY_MS]

## Constraints
- Risk tolerance level: [RISK_LEVEL: LOW | MEDIUM | HIGH]
- Must preserve referential integrity for: [CRITICAL_FOREIGN_KEYS]
- Rollback must be possible within: [ROLLBACK_WINDOW_HOURS]
- Data consistency validation method: [VALIDATION_METHOD: CHECKSUM | ROW_COUNT | FULL_DIFF | APPLICATION_LEVEL]
- Regulatory or compliance constraints: [COMPLIANCE_REQUIREMENTS]

## Output Schema
Produce a JSON object with this exact structure:
{
  "migration_phases": [
    {
      "phase_number": integer,
      "phase_name": string,
      "objective": string,
      "duration_estimate_hours": integer,
      "steps": [
        {
          "step_number": integer,
          "action": string,
          "sql_or_command": string | null,
          "verification_query": string,
          "expected_result": string,
          "rollback_action": string
        }
      ],
      "foreign_key_impacts": [
        {
          "constraint_name": string,
          "source_table": string,
          "target_table": string,
          "resolution_strategy": "DROP_AND_RECREATE" | "APPLICATION_LEVEL" | "DEFERRED" | "KEEP_IN_SHARED",
          "risk_level": "LOW" | "MEDIUM" | "HIGH",
          "mitigation": string
        }
      ],
      "dual_write_config": {
        "enabled": boolean,
        "tables_in_scope": [string],
        "consistency_window_ms": integer,
        "conflict_resolution": "LAST_WRITE_WINS" | "SOURCE_OF_TRUTH" | "MANUAL" | null,
        "reconciliation_query": string | null
      },
      "data_sync_checkpoint": {
        "sync_method": "FULL_DUMP" | "CDC" | "LOG_REPLAY" | "DUAL_WRITE_BACKFILL",
        "verification_query": string,
        "sync_complete_criteria": string
      },
      "rollback_conditions": [string],
      "go_no_go_criteria": [string]
    }
  ],
  "pre_migration_checks": [string],
  "post_migration_validation": [string],
  "rollback_plan": {
    "trigger_conditions": [string],
    "full_rollback_steps": [string],
    "estimated_rollback_time_minutes": integer,
    "data_loss_risk": "NONE" | "MINIMAL" | "MODERATE" | "HIGH"
  },
  "risk_register": [
    {
      "risk_id": string,
      "description": string,
      "likelihood": "LOW" | "MEDIUM" | "HIGH",
      "impact": "LOW" | "MEDIUM" | "HIGH",
      "mitigation": string,
      "detection_method": string
    }
  ]
}

## Instructions
1. Phase the migration so that no single phase introduces an unrecoverable state.
2. For every foreign key that crosses the extraction boundary, propose a concrete resolution strategy with verification.
3. Include dual-write periods where necessary, specifying the consistency window and conflict resolution approach.
4. Define clear go/no-go criteria at each phase boundary.
5. Ensure the rollback plan is testable and includes data integrity verification after rollback.
6. Flag any table that cannot be safely extracted without application-level changes and recommend those changes.
7. If [RISK_LEVEL] is LOW, prefer simpler approaches even if they take longer. If HIGH, prioritize speed with explicit acceptance of data risk.

To adapt this prompt, replace each square-bracket placeholder with concrete values from your system. The [SHARED_SCHEMA] placeholder should include enough DDL or table descriptions for the model to identify foreign key relationships. If you don't have exact [TABLE_METRICS], provide order-of-magnitude estimates—row counts and write throughput directly affect the feasibility of dump-and-restore versus CDC-based sync strategies. The [RISK_LEVEL] parameter is not cosmetic; it changes the model's trade-off calculus between safety and speed throughout the plan.

Before running this prompt in production, validate the output against your actual schema by diffing the model's foreign key impact list against a database introspection tool. The model may hallucinate constraint names or miss implicit relationships encoded in application logic rather than DDL. Always pair this prompt's output with a human review step that verifies every proposed DROP_AND_RECREATE action against your actual migration tooling and deployment pipeline. For high-risk extractions, run the generated verification queries in a staging environment before executing any phase in production.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder must be populated for the prompt to produce a reliable, actionable plan.

PlaceholderPurposeExampleValidation Notes

[CURRENT_STATE_DESCRIPTION]

Describes the existing shared database topology, including tables, access patterns, and service consumers.

A 500-line PostgreSQL schema with 120 tables shared by 4 services: orders, inventory, billing, and shipping.

Must contain at least one explicit foreign key relationship. Null not allowed.

[TARGET_ARCHITECTURE_GOALS]

Defines the desired end state, including service ownership boundaries, latency budgets, and consistency requirements.

Each service owns its data store. Orders service owns order tables. Cross-service data access only via API. P99 latency under 50ms.

Must specify at least one non-functional requirement. Null not allowed.

[EXTRACTION_CANDIDATES]

Lists the specific tables, schemas, or domains to be extracted, prioritized by business value or risk.

Extract orders schema first, then inventory, then billing. Shipping tables remain shared temporarily.

Must contain at least one named table or schema. Null not allowed.

[FOREIGN_KEY_MAP]

Provides a list of all cross-table foreign key relationships that will be broken by the extraction.

orders.order_id -> shipments.order_id, orders.customer_id -> billing.customer_id

Each entry must be a valid table.column reference. Null allowed if no FKs exist.

[DUAL_WRITE_WINDOW]

Specifies the maximum acceptable duration for dual-write inconsistency during the cutover phase.

300 seconds

Must be a positive integer representing seconds. Null not allowed.

[ROLLBACK_SAFETY_CONDITIONS]

Defines the specific metrics or conditions that must trigger an automatic rollback of the migration step.

Replication lag exceeds 5 seconds, or error rate on new service writes exceeds 0.1%.

Must contain at least one measurable condition. Null not allowed.

[DATA_SYNC_CHECKPOINT_CRITERIA]

Specifies the verification queries or reconciliation checks to confirm data integrity after synchronization.

SELECT COUNT() FROM orders.orders must equal SELECT COUNT() FROM orders_new.orders.

Must be a valid SQL comparison or a defined reconciliation script. Null not allowed.

[COMPLIANCE_AND_REGULATORY_CONSTRAINTS]

Lists any data handling regulations (e.g., GDPR, PCI-DSS) that constrain the migration strategy.

PCI-DSS applies to billing tables. Data must not be logged in plaintext during migration.

Must reference a specific regulation or internal policy. Null allowed if no constraints exist.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Database per Service Migration Planning Prompt into a reliable application workflow with validation, retries, and safety gates.

This prompt is designed to be called from an application layer that manages the full lifecycle of a migration planning request. The harness should accept a structured input payload containing the current shared schema, the proposed service boundaries, and the target service ownership map. Because the output is a multi-phase migration plan with foreign key impact analysis and rollback conditions, the harness must validate the plan's structural integrity before presenting it to the engineering team. Treat this prompt as a planning engine whose output must pass deterministic checks before it becomes an actionable document.

The implementation should wrap the LLM call in a validation pipeline. First, parse the model output into a typed object with fields for phases (ordered list), foreign_key_impacts (per-phase list of affected relationships), dual_write_windows (service pairs and consistency mode), sync_checkpoints (data validation queries), and rollback_conditions (per-phase safety gates). Validate that every extracted table appears in exactly one service's ownership scope, that no phase references a table before its foreign key dependencies are resolved in prior phases, and that every dual-write window includes both a start condition and a consistency verification query. If validation fails, retry the prompt once with the specific validation errors injected into the [CONSTRAINTS] block. After two failures, escalate to a human reviewer with the partial plan and the error log. Log every attempt, the raw output, the validation result, and the final accepted plan for auditability.

Model choice matters here. Use a model with strong reasoning capabilities and a large context window, as the prompt must ingest the full shared schema, service boundaries, and ownership map in a single request. If the schema exceeds the context window, pre-process it by extracting only table names, columns, foreign keys, and row count estimates, omitting index definitions and storage parameters. For production use, store the accepted migration plan as a versioned artifact in the same repository as the service code, and run the sync checkpoints as automated data validation tests during each extraction phase. Never execute a phase without confirming that its rollback conditions are still valid given the current production state.

IMPLEMENTATION TABLE

Expected Output Contract

The JSON structure the model must return for the Database per Service Migration Plan. Each field includes a validation rule that can be checked programmatically before the plan is accepted.

Field or ElementType or FormatRequiredValidation Rule

migration_plan.title

string

Must be non-empty and contain the target service name from [SERVICE_NAME]

migration_plan.phases

array of objects

Array length must be >= 1. Each phase object must include phase_id, description, and steps fields

migration_plan.phases[].phase_id

integer

Must be sequential starting from 1. No gaps or duplicates allowed

migration_plan.phases[].steps

array of objects

Array length must be >= 1. Each step must include step_id, action, and rollback_action fields

migration_plan.phases[].steps[].action

string

Must reference at least one table or foreign key from [AFFECTED_TABLES]. Use exact table names from input

migration_plan.foreign_key_impact

array of objects

Each object must include fk_name, source_table, target_table, and resolution fields. fk_name must match a constraint from [FK_LIST]

migration_plan.dual_write_consistency_window

object

Must include duration_seconds (integer > 0) and consistency_check_query (non-empty string). duration_seconds must not exceed [MAX_CONSISTENCY_WINDOW_SECONDS]

migration_plan.data_sync_checkpoints

array of objects

Each checkpoint must include checkpoint_name, validation_query, and expected_row_count_threshold. validation_query must be a valid SQL SELECT statement

migration_plan.rollback_safety_conditions

array of strings

Array length must be >= 1. Each condition must be a falsifiable statement that can be evaluated as true or false before rollback execution

migration_plan.estimated_downtime_per_phase_seconds

array of integers

Array length must equal number of phases. Each value must be >= 0. Sum must not exceed [MAX_TOTAL_DOWNTIME_SECONDS]

PRACTICAL GUARDRAILS

Common Failure Modes

Database per service migrations fail in predictable ways. These cards cover the most common prompt and planning failures when generating phased migration plans, along with concrete guardrails to catch them before they reach production.

01

Hallucinated Foreign Key Dependencies

Risk: The model invents foreign key relationships that don't exist in the actual schema, producing a migration plan that assumes dependencies where none are present. This leads to incorrect extraction ordering and phantom coupling constraints. Guardrail: Always provide the actual DDL or a verified entity-relationship diagram as input. Add an explicit instruction: 'Only reference foreign keys present in the provided schema. If a relationship is inferred rather than declared, flag it as UNVERIFIED and request confirmation.' Validate the output against a known FK list before accepting the plan.

02

Missing Dual-Write Consistency Windows

Risk: The generated plan describes extracting a service to its own database but omits the dual-write period where both the old shared database and the new service-owned database must stay consistent. Without this, the plan implies a dangerous cutover with no rollback path. Guardrail: Add a required output section: 'For each extraction step, define the dual-write start trigger, consistency validation check, and dual-write end condition. If dual-write is not feasible for a given step, explain why and propose an alternative consistency mechanism.'

03

Ignoring Cross-Service Query Patterns

Risk: The model focuses on table ownership but ignores application query patterns that join across the proposed boundary. The resulting plan extracts tables that are frequently joined in read paths, creating N+1 query problems or forcing immediate API composition that wasn't planned. Guardrail: Require the prompt to ingest a sample of production query logs or an access pattern inventory. Add instruction: 'For each proposed extraction, list cross-boundary queries that will break. Propose a read-side pattern (CQRS view, API composition, data replication) or flag the extraction as premature.'

04

Unordered Extraction Sequence

Risk: The plan proposes extracting services in an order that violates dependency constraints, such as extracting a child table before its parent or a service that depends on another service's data before that data is available. Guardrail: Add a dependency graph validation step to the prompt: 'Before finalizing the extraction sequence, produce a dependency graph showing which tables and services depend on which others. Number each extraction step and verify that no step depends on a later step. Flag any circular dependencies that prevent linear extraction.'

05

Rollback Safety Gaps

Risk: The plan describes forward migration steps but omits rollback conditions, data reconciliation checkpoints, and rollback procedures. If migration fails mid-step, the team has no documented path back to a consistent state. Guardrail: Require a rollback section for every extraction step: 'For each phase, define the rollback trigger condition, the data reconciliation query to verify consistency before rollback, and the exact steps to revert. If rollback is impossible after a certain point, mark it as a POINT OF NO RETURN with required approval gate.'

06

Schema Drift During Migration

Risk: The plan assumes a static schema, but the shared database continues to evolve during the migration period. New columns, tables, or constraints added mid-migration can break the extraction logic or create data loss windows. Guardrail: Add a schema freeze or change-control instruction: 'Identify which tables are subject to schema changes during migration. For each, specify whether a schema freeze is required, a change notification trigger, or a reconciliation step to catch drift. Include a pre-extraction schema snapshot comparison step.'

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality of a generated database-per-service migration plan before it is reviewed by the engineering team. Each criterion includes a pass standard, a failure signal, and a test method that can be automated or performed manually.

CriterionPass StandardFailure SignalTest Method

Foreign Key Impact Coverage

Every cross-schema foreign key in the source system is explicitly listed with its owning table, referencing table, and a migration action (denormalize, sync, or break).

A known cross-schema FK is missing from the impact analysis, or an FK is listed without a concrete migration action.

Parse the output JSON for the foreign_key_impacts array. Assert that its length matches the count from a pre-computed schema introspection query. Validate that each entry has non-null action and table fields.

Dual-Write Consistency Window Definition

Each extraction step that introduces a dual-write period specifies the start trigger, end condition, consistency mechanism (e.g., outbox, CDC), and maximum acceptable lag in milliseconds.

A dual-write step is described without a defined end condition or a maximum lag threshold, making the consistency window unbounded.

Check each object in the extraction_steps array where strategy is dual-write. Assert that consistency_window.end_condition and consistency_window.max_lag_ms are not null.

Data Synchronization Checkpoint Design

The plan includes a specific checkpoint after each data migration step that verifies row counts, checksum parity, or application-level consistency before proceeding to the next step.

A migration step that moves data between databases lacks a subsequent checkpoint, or the checkpoint only checks row counts without a checksum or business-level validation.

For each step in extraction_steps with type equal to data_migration, assert that a corresponding entry exists in the synchronization_checkpoints array with a non-null validation_query or checksum_algorithm.

Rollback Safety Condition Per Step

Every extraction step has a specific, testable rollback condition that is not simply 'restore from backup'. It must include a data integrity check (e.g., 'halt if writes to old primary exceed 100 after cutover').

A step's rollback condition is a generic 'revert to snapshot' statement, or a step with a cutover action has no rollback condition at all.

Iterate over extraction_steps. For each, assert that rollback_condition is a non-empty string containing a specific metric or threshold (e.g., '>', '<', 'error rate'). Reject generic phrases like 'restore backup'.

Service-Code Coupling Identification

The plan identifies application code modules or services that must be modified for each extraction step, referencing specific repository paths or package names.

An extraction step that changes a database connection string or schema does not list any dependent application code that needs updating.

For each step in extraction_steps where schema_change is true, assert that the dependent_code_modules array is not empty and contains at least one string matching a path pattern (e.g., contains '/').

Phased Sequencing with Dependency Order

The extraction sequence is topologically sorted so that tables with no foreign keys to other tables being extracted are moved first. The plan explicitly states this dependency order.

The plan proposes moving a child table before its parent table, or the sequence is arbitrary with no dependency justification.

Extract the ordered list of table names from the extraction_steps sequence. For each step, assert that all tables it depends on (via FK) appear earlier in the sequence. Use a pre-computed dependency graph for validation.

Cutover Strategy Specification

For each extraction, the plan specifies whether the cutover is big-bang, canary by tenant, or feature-flagged, and includes the exact steps to redirect traffic.

A cutover step says 'switch traffic' without specifying the mechanism (e.g., feature flag name, load balancer rule, DNS update).

Check each step in extraction_steps with action equal to cutover. Assert that the cutover_strategy field is one of an allowed enum (big-bang, canary, feature-flag) and that traffic_redirect_mechanism is a non-null string.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single database and a small set of tables. Remove the dual-write consistency window and rollback safety condition sections. Focus on generating a simple extraction sequence and foreign key impact list. Replace [OUTPUT_SCHEMA] with a free-text migration step list.

Prompt snippet

code
You are a database migration planner. Given [DATABASE_SCHEMA] and [TARGET_SERVICE], produce a step-by-step extraction plan. Include foreign key dependencies and a suggested extraction order. Skip consistency windows and rollback plans.

Watch for

  • Circular foreign key references that confuse the extraction order
  • Missing cross-table dependency chains
  • Overly optimistic single-step extraction plans
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.