Skip to main content
rulesSource-backed

Production Database Migration Safety Rules

Source-backed rules for reviewing production database migrations before merge with lock-risk checks, expand-contract rollout, backfill controls, rollback limits, and privacy-safe migration evidence.

by MkDev11·added 2026-06-04·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://docs.gitlab.com/development/database/avoiding_downtime_in_migrations/, https://github.com/JSONbored/awesome-claude/blob/main/content/rules/production-database-migration-safety-rules.mdx
Safety notes
Production migrations can lock tables, rewrite rows, drop data, invalidate indexes, break old application versions, delay deploys, or require backup restore instead of a simple revert., Generated ORM migrations should be reviewed as SQL or engine-specific operations; do not assume type-safe schema code is operationally safe., Backfills, constraint validation, index builds, and cleanup migrations should run with batching, monitoring, retry behavior, and stop conditions appropriate to the production workload.
Privacy notes
Migration diffs, dry-run logs, explain plans, table names, column names, row counts, sample rows, tenant IDs, and rollback notes can expose sensitive product or customer information., Do not paste production rows, unredacted schema snapshots, connection strings, database hostnames, backup locations, or incident-specific migration logs into public PR comments., When evidence must stay private, leave a minimal public note that names the verification class and owner without exposing database contents or operational secrets.
Author
MkDev11
Submitted by
MkDev11
Claim status
unclaimed
Last verified
2026-06-04

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

20 minutes

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Prerequisite readiness

Prerequisite readiness

4 prerequisites to line up before setup. Includes a review or approval gate.

0/4 ready
Install & runtime1Configuration2Review & approval120 minutes

Safety & privacy surface

Safety & privacy surface

3 safety and 3 privacy notes across 4 risk areas. Review closely: credentials & tokens.

4 areas
  • SafetyData retentionProduction migrations can lock tables, rewrite rows, drop data, invalidate indexes, break old application versions, delay deploys, or require backup restore instead of a simple revert.
  • SafetyGeneralGenerated ORM migrations should be reviewed as SQL or engine-specific operations; do not assume type-safe schema code is operationally safe.
  • SafetyExecution & processesBackfills, constraint validation, index builds, and cleanup migrations should run with batching, monitoring, retry behavior, and stop conditions appropriate to the production workload.
  • PrivacyExecution & processesMigration diffs, dry-run logs, explain plans, table names, column names, row counts, sample rows, tenant IDs, and rollback notes can expose sensitive product or customer information.
  • PrivacyData retentionDo not paste production rows, unredacted schema snapshots, connection strings, database hostnames, backup locations, or incident-specific migration logs into public PR comments.
  • PrivacyCredentials & tokensWhen evidence must stay private, leave a minimal public note that names the verification class and owner without exposing database contents or operational secrets.

Safety notes

  • Production migrations can lock tables, rewrite rows, drop data, invalidate indexes, break old application versions, delay deploys, or require backup restore instead of a simple revert.
  • Generated ORM migrations should be reviewed as SQL or engine-specific operations; do not assume type-safe schema code is operationally safe.
  • Backfills, constraint validation, index builds, and cleanup migrations should run with batching, monitoring, retry behavior, and stop conditions appropriate to the production workload.

Privacy notes

  • Migration diffs, dry-run logs, explain plans, table names, column names, row counts, sample rows, tenant IDs, and rollback notes can expose sensitive product or customer information.
  • Do not paste production rows, unredacted schema snapshots, connection strings, database hostnames, backup locations, or incident-specific migration logs into public PR comments.
  • When evidence must stay private, leave a minimal public note that names the verification class and owner without exposing database contents or operational secrets.

Prerequisites

  • A migration pull request, SQL patch, ORM migration, release plan, or generated schema diff that may run against a shared or production database.
  • Access to the target database engine documentation, migration tool behavior, current CI status, staging or dry-run result, and affected service owner.
  • A documented deployment order for application code, background jobs, migrations, backfills, cleanup migrations, and rollback or forward-fix steps.
  • Permission to block merge when the migration risk, owner review, test evidence, or privacy handling is incomplete.

Schema details

Install type
copy
Reading time
6 min
Difficulty score
45
Troubleshooting
Yes
Breaking changes
No
Collection metadata
Estimated setup
20 minutes
Difficulty
intermediate
Full copyable content
You are reviewing a production database migration.

Rules:
1. Classify the migration by lock risk, data-loss risk, deploy-order risk,
   backfill size, and rollback limits before approving.
2. Prefer expand-contract changes for renames, type changes, required fields,
   and data backfills; split schema, code, and cleanup steps when needed.
3. Require staging or dry-run evidence, owner review, fresh tests, backup or
   restore notes, and a monitored rollout plan.
4. Block merge when the migration can rewrite large tables, lock writes, drop
   data, expose private rows, or break old application versions without an
   explicit mitigation.
5. Keep table names, row samples, migration logs, production metrics, and
   rollback notes privacy-safe in public review channels.

About this resource

Purpose

Use these rules when an AI coding assistant, ORM generator, migration tool, or human contributor proposes a database schema or data migration that may reach a shared environment.

The goal is to make risky migrations boring to review. A migration should name the operational risk, prove that old and new application versions can coexist, show how the team tested the path, and explain what rollback really means for the affected data.

Migration Risk Classes

Classify the migration before reviewing style or generated-file formatting.

  1. Additive schema change. Adds nullable columns, tables, indexes, constraints marked for later validation, or compatibility fields.
  2. Backfill or data rewrite. Updates existing rows, copies data between columns, changes data shape, or runs an application job that touches many records.
  3. Constraint or index change. Adds uniqueness, foreign keys, not-null requirements, check constraints, partial indexes, or generated columns.
  4. Destructive cleanup. Drops columns, tables, indexes, values, or old compatibility paths after a release has already stopped using them.
  5. Rename or type change. Renames objects, changes enum semantics, changes column types, or rewrites application assumptions about stored values.
  6. Operational migration. Changes replication, partitions, extensions, permissions, database roles, retention, archives, triggers, or scheduled jobs.

If the class is unclear, treat the migration as high risk until the submitter can show the SQL or engine behavior that will actually run.

Required Evidence

A production migration PR should include enough evidence for a reviewer to understand the release decision later.

  • The target environment, database engine, migration tool, and reviewed SQL or generated diff are named.
  • The migration is tied to the application deploy order, including whether old and new app versions can read and write during rollout.
  • Lock risk, table rewrite risk, index-build behavior, and long-transaction behavior are checked against the target engine documentation.
  • Staging, dry-run, shadow database, or equivalent validation ran after the latest migration change.
  • Backfills have batching, retry, idempotency, progress monitoring, stop conditions, and ownership.
  • Backup, restore, rollback, or forward-fix limits are stated honestly, especially when data loss or irreversible cleanup is possible.
  • Privacy-sensitive logs, row samples, metrics, explain plans, and schema details are redacted before public review.

Do not approve a production migration when the PR only says that the ORM generated it successfully. The reviewer needs operational evidence, not only a schema diff.

Safe Rollout Rules

  • Prefer expand-contract rollout for required fields, renames, type changes, and data moves: add the new shape, deploy compatible code, backfill, switch reads and writes, then clean up later.
  • Keep destructive cleanup in a separate PR or later migration after production code no longer depends on the old object.
  • Build large indexes with the database engine's non-blocking option when available and document any remaining write-lock window.
  • Add constraints in a way that avoids surprising table scans or long blocking locks, then validate after data is known to satisfy the rule.
  • Split large data backfills from schema changes when a failure would require retry logic, progress tracking, throttling, or operator intervention.
  • Avoid application startup migrations in production unless the deployment platform, lock behavior, concurrency, and rollback path are explicit.
  • Review generated ORM migrations before apply, especially drops, renames, not-null changes, enum changes, default changes, and implicit data rewrites.

Reviewer Rules

  • Start by asking what SQL or engine operation will run, not what the ORM model looked like before generation.
  • Confirm that the migration can run safely while old and new application versions overlap during rolling deploys.
  • Require a data owner or service owner for migrations that touch customer records, tenant boundaries, billing, auth, audit logs, or retention policy.
  • Re-check risk after rebases, regenerated migrations, dependency upgrades, or framework-version changes that can alter generated SQL.
  • Treat migration credentials, backup locations, table samples, row counts, and production metrics as sensitive review material.
  • Ask for a forward-fix plan when rollback cannot restore the previous data shape without backup restore.

Merge Blockers

Block merge until resolved when:

  • the migration drops, truncates, renames, rewrites, or changes required data without an expand-contract or cleanup-window explanation;
  • generated SQL, migration tool output, or database-engine behavior is not visible to reviewers;
  • the PR can lock writes, scan large tables, rebuild indexes, or hold long transactions without mitigation;
  • old and new application versions cannot coexist during the deployment order;
  • a backfill lacks batching, idempotency, monitoring, retry, or stop criteria;
  • tests or dry-run evidence are stale after the latest migration edit;
  • rollback claims ignore irreversible data loss, constraint side effects, or backup restore requirements;
  • public comments include production rows, raw logs, connection strings, hostnames, tenant identifiers, or private schema details.

Review Checklist

  • {"task": "Risk class named", "description": "The PR classifies additive, backfill, constraint, destructive, rename, type, or operational migration risk"}
  • {"task": "SQL reviewed", "description": "Reviewers can inspect the SQL, engine operation, or generated migration diff that will run"}
  • {"task": "Deploy order safe", "description": "Old and new application versions can coexist, or the rollout window and owner exception are explicit"}
  • {"task": "Lock risk checked", "description": "Table locks, scans, index builds, long transactions, and constraint validation are reviewed against the target engine"}
  • {"task": "Backfill controlled", "description": "Large data changes have batching, idempotency, progress monitoring, retry behavior, and stop conditions"}
  • {"task": "Privacy protected", "description": "Logs, samples, row counts, hostnames, backup paths, and schema details are redacted or kept in approved private channels"}

AI Review Rules

AI assistants can help classify a migration, but they should not invent operational certainty.

  • Ask the assistant to list risky SQL operations and unknowns separately.
  • Require file paths, migration names, and engine-specific behavior for each warning.
  • Have the assistant compare generated migrations against model changes rather than trusting either side alone.
  • Do not let the assistant run production migration commands, connect to live databases, or inspect real rows without explicit operator approval.
  • Re-run the review after generation, rebase, or manual SQL edits.

Troubleshooting

  • A rename is needed: add the new object, dual-write or copy data, switch reads, then remove the old object after compatible code has shipped.
  • A not-null constraint is needed: backfill first, enforce application writes, then add or validate the constraint with engine-aware locking review.
  • An index build is slow: choose the non-blocking index path supported by the engine, monitor progress, and document the write-lock tradeoff.
  • The rollback is not reversible: say so. Use backup restore, forward-fix, or delayed cleanup instead of promising a simple revert.
  • Logs contain real data: move evidence to a private channel, redact public notes, and leave only the verification class, owner, and result in the PR.

Duplicate And History Check

Checked existing rules, hooks, agents, skills, guides, collections, open PRs, and closed PR history for database migration safety, production schema-change rules, zero-downtime migration review, backfill review, safe migration hooks, and ORM migration workflows.

Adjacent content includes a database migration safety hook, a database migration runner hook, database expert agents, Drizzle migration skill content, and a high-risk code review escalation rule. This entry is distinct because it is a portable rules policy for merge review: it decides what production migration evidence must exist, when expand-contract rollout is required, how reviewers classify lock and data-loss risk, and what privacy constraints apply to migration evidence.

GitLab Operation Rollout Reference

The GitLab database migration guide classifies common schema operations by the rollout procedure they require. Use this when checking a PR's deploy-order claim.

Operation Rollout per GitLab guide
Adding tables Safe; no code uses the table yet
Adding indexes Use add_concurrent_index (non-blocking)
Dropping columns Three releases: ignore (M), drop (M+1), remove ignore rule (M+2)
Renaming columns rename_column_concurrently with disable_ddl_transaction!
Removing foreign keys Wrap remove_foreign_key_if_exists in with_lock_retries

The three-release column-drop pattern in the guide:

# Release M: ignore the column
class User < ApplicationRecord
  ignore_column :updated_at, remove_with: '12.7', remove_after: '2019-12-22'
end

# Release M+1: drop the column
class RemoveUsersUpdatedAtColumn < Gitlab::Database::Migration[2.1]
  def up
    remove_column :users, :updated_at
  end

  def down
    add_column :users, :updated_at, :datetime
  end
end

Sources

Source citations

Add this badge to your README

Show that Production Database Migration Safety Rules is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/rules/production-database-migration-safety-rules.svg)](https://heyclau.de/entry/rules/production-database-migration-safety-rules)

How it compares

Production Database Migration Safety Rules side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

Source-backed rules for reviewing production database migrations before merge with lock-risk checks, expand-contract rollout, backfill controls, rollback limits, and privacy-safe migration evidence.

Open dossier

Source-backed rules for reviewing event-sourcing implementation changes, covering immutable event design, event schema evolution without breaking projections, idempotent event handlers, snapshot and replay correctness, and consistent event-store access patterns.

Open dossier

Source-backed rules for deciding when an AI-assisted code review must escalate high-risk changes to security, infrastructure, data, release, or domain owners before merge.

Open dossier

Source-backed rules for reviewing TypeScript API client compatibility before merge, with exported type-surface diffs, inferred router inputs and outputs, runtime validator alignment, downstream compile checks, and privacy-safe evidence.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersMkDev11jaso0n0818MkDev11MkDev11
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryrulesrulesrulesrules
SourceSource-backedSource-backedSource-backedSource-backed
AuthorMkDev11jaso0n0818MkDev11MkDev11
Added2026-06-042026-06-192026-06-042026-06-04
Platforms
Harness
Source repo
Safety notesProduction migrations can lock tables, rewrite rows, drop data, invalidate indexes, break old application versions, delay deploys, or require backup restore instead of a simple revert. Generated ORM migrations should be reviewed as SQL or engine-specific operations; do not assume type-safe schema code is operationally safe. Backfills, constraint validation, index builds, and cleanup migrations should run with batching, monitoring, retry behavior, and stop conditions appropriate to the production workload.Mutating or deleting a persisted event corrupts the audit log and breaks replays that depend on the original event sequence, potentially causing unrecoverable inconsistency. A non-backward-compatible event schema change can break all running projections that read older events, causing data loss in read models or replay failures. A non-idempotent event handler can apply the same event twice on replay or redelivery, producing incorrect aggregate state that is invisible in normal operation but surfaces during recovery.High-risk changes can alter auth, authorization, secrets, production data, network exposure, infrastructure, release automation, or dependency trust; escalate before merge instead of relying on a single reviewer. Treat AI-generated patches, summaries, migrations, policy edits, generated clients, and workflow changes as untrusted until the source diff and checks are reviewed. Require a rollback or disablement path for production-facing changes, especially when the blast radius includes customer data, credentials, deployments, billing, or public APIs.A TypeScript API change can compile in the edited package while breaking frontend consumers, generated clients, cache invalidation, form validation, or error handling in another workspace. Generated declaration files, SDK clients, and API reports should be regenerated from reviewed source and inspected before commit; stale generated output can make reviewers approve the wrong contract. Runtime validators and inferred types must be reviewed together because a type-only change can still accept or reject different data at runtime.
Privacy notesMigration diffs, dry-run logs, explain plans, table names, column names, row counts, sample rows, tenant IDs, and rollback notes can expose sensitive product or customer information. Do not paste production rows, unredacted schema snapshots, connection strings, database hostnames, backup locations, or incident-specific migration logs into public PR comments. When evidence must stay private, leave a minimal public note that names the verification class and owner without exposing database contents or operational secrets.Event stores often contain an immutable history of personal data; deletion requests for GDPR or similar regulations must be handled by encryption-key rotation or event compaction, not by deleting events. Do not include sensitive personal data (passwords, payment card details, health records) directly in event payloads; reference identifiers and look up sensitive data separately. Be careful with event replay in non-production environments that copy the production event log, since they inherit all personal data in the event history.Escalation notes can expose private incident context, customer identifiers, secrets, account IDs, internal topology, or vulnerability details if copied into public PR comments. Use private security channels for embargoed vulnerabilities, secrets, regulated data, and exploit details; keep public PR notes synthetic and minimally revealing. Do not paste raw logs, traces, prompts, database rows, screenshots, or security scan output into review notes unless they have been redacted.API client types, API reports, router names, procedure names, schemas, examples, error unions, and generated clients can expose internal routes, unreleased features, auth models, tenant fields, and private payload shapes. Do not paste raw production request bodies, response examples, validation errors, API reports, or downstream compile logs into public comments without redacting private fields and internal identifiers. Use synthetic fixtures for compatibility examples when the client surface includes customer data, billing fields, healthcare data, education records, support tickets, or private workspace metadata.
Prerequisites
  • A migration pull request, SQL patch, ORM migration, release plan, or generated schema diff that may run against a shared or production database.
  • Access to the target database engine documentation, migration tool behavior, current CI status, staging or dry-run result, and affected service owner.
  • A documented deployment order for application code, background jobs, migrations, backfills, cleanup migrations, and rollback or forward-fix steps.
  • Permission to block merge when the migration risk, owner review, test evidence, or privacy handling is incomplete.
  • A pull request or diff that adds or edits event types, handlers, projections, aggregates, snapshots, or event-store queries in an event-sourced system.
  • Knowledge of the event store and framework in use, since stream naming, optimistic concurrency, and replay semantics differ between implementations.
  • Access to a test environment where event replay, schema evolution, and snapshot consistency can be exercised without corrupting the production event log.
  • Permission to block merge when an event schema change breaks existing projections, a handler is not idempotent, or aggregate state diverges between load paths.
  • A pull request, patch, or generated code change with enough diff context to classify the risk.
  • A repository policy that names security, infrastructure, data, API, dependency, and release owners or escalation channels.
  • Access to current CI results, required checks, deployment plan, rollback plan, and affected service ownership.
  • Permission to block approval when the risk class, source evidence, or owner signoff is incomplete.
  • A TypeScript web app, package, SDK, typed API client, tRPC router, generated client, or shared types package whose public surface is consumed outside the edited module.
  • Access to the relevant type-check command, package build, generated declaration output, API report, type tests, and at least one downstream consumer or fixture.
  • A named owner for client compatibility, deprecation policy, generated artifacts, runtime validators, and release notes.
  • Permission to block merge when a type-surface change has no downstream compile evidence or safe migration path.
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.