Communitygithub.com

ゼロダウンタイムマイグレーション

データベーススキーマを変更する際にデータを失わずに、カラム、制約、インデックスの追加・削除・リネーム、バックフィルなどを安全に行うためのスキルです。コードデプロイと破壊的なマイグレーションの同時実行によるダウンタイムを防止します。

ゼロダウンタイムマイグレーション とは?

このスキルは、ローリングデプロイ中にデータベースを稼働させたままスキーマ変更を実行する「Expand/Contract(パラレルチェンジ)」パターンを体系化したものです。本番環境では新旧両方のアプリケーションバージョンが同一のデータベースを共有するため、スキーマは両方と互換性を持つ必要があります。このスキルは3つのリリースに分割して変更を行います。Expandフェーズでは新しいカラムやテーブルを互換性のある形で追加し、Migrateフェーズでバックフィルとデュアルライトを実行、Contractフェーズで旧構造を削除します。PostgreSQL特有の注意点として、NOT NULL制約の追加は「NOT VALID」+「VALIDATE」の2段階、インデックス作成は「CREATE INDEX CONCURRENTLY」をトランザクション外で実行すること、ロックタイムアウトの設定などが含まれます。Cursor、Claude Code、CodexなどのAIエージェントが、データベースマイグレーションの計画立案やコード生成時にこのパターンを適用できるように設計されています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lguidolin/agent-skills/tree/main/skills/zero-downtime-migrations

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

ゼロダウンタイムマイグレーション は何をしますか?

概要

ローリングデプロイ中にシステムを稼働させたままスキーマ変更を行うための規律です。ロールアウト中は、古いPodと新しいPodが 1つのデータベースを共有 します。そのため、スキーマは 両方のアプリバージョンと同時に互換性 がなければなりません。破壊的なマイグレーションを、それを必要とするデプロイと一緒に実行することは、古典的なセルフダウンタイムの原因です。

作成ルール(全プロジェクト共通)

  • 2種類のマイグレーションを明確に区別する: 冪等性を持つ current/ セット(開発時のイテレーション用 — 毎サイクル再実行可能、CREATE OR REPLACE / IF NOT EXISTS を使用、オブジェクトは 最終形 で記述、作成後の ALTER は不可)と コミット済み のマイグレーション(不変、順序付け、実際に出荷されるもの)。ALTER DEFAULT PRIVILEGES のみ、インライン ALTER として許容されます。
  • 所有権はマイグレーションの実行方法に基づく: 散在する ALTER ... OWNER は使用しません。
  • 単一のブートストラップ情報源 をローカル/Dockerの初期化パスとシャドウ/テストDBで共有する — すべての環境が同一に構築されます。

Expand/Contract(パラレルチェンジ)

適用条件: データベースにデプロイ後も保持すべきデータが存在する場合(ステージング+実データ、本番)。対象外: ローカル/リセット可能なプロジェクト — ただし、コミット済みマイグレーションは あたかもこのルールが適用されるかのように 記述し、プロモーション時に書き換えが発生しないようにします。

スキーマ変更は 3つのリリース に分割して実行します。1回のリリースでは行いません。

  1. Expand — 新しい形状を 追加的に、後方互換性を持って追加する:新しいNULL許容カラム、新しいテーブル、新しい関数。アプリバージョン N はそのまま稼働し続けます。
  2. Migrate — 境界のあるバッチ でバックフィルを実行する(テーブル全体をロックする UPDATE は避ける)。必要に応じてアプリ N+1 からデュアルライトを行う。読み取りを新しい形状に切り替える。NOT NULL はこのタイミングでのみ追加する(制約は NOT VALID で追加し、その後 VALIDATE を別途実行する)。
  3. Contract — アプリ N が完全に退役した 後 に、後の リリースで古いカラムや制約を削除する。

PostgreSQLの落とし穴

落とし穴安全なアプローチ
揮発性/大規模なバックフィルデフォルト値を持つ NOT NULL カラムNULL許容で追加 → バッチでバックフィル → 制約 NOT VALID を追加 → VALIDATE
制約の追加最初に NOT VALID を追加し、その後 VALIDATE CONSTRAINT を実行する(弱いロック)
インデックスの構築CREATE INDEX CONCURRENTLY — トランザクション内では実行できません。マイグレーションツールのトランザクションラッピングから隔離する
ブロックされたマイグレーションによる本番停止lock_timeout / statement_timeout を設定し、迅速に失敗させる
カラムのリネームExpand/Contractパターン:新しいカラムを追加 → バックフィル → 読み取りを切り替え → 古いカラムを削除(リリースを分ける)

「最終形の CREATE OR REPLACE」が本番では不十分な理由

そのルールは 開発者のエルゴノミクス であり、開発環境では正しいものです。しかし、実ユーザーが存在しローリングデプロイを行う本番環境では、ロールアウト中は両方のアプリバージョンがスキーマを共有するため、Expand/Contract こそが変更を安全にする方法です。両者を混同してはいけません。

詳細な根拠: 憲法第17条、engineering-constitution/references/engineering-constitution.md にバンドルされています。デプロイパイプライン: cloud-delivery-aks。

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

lguidolin/change-hygiene-and-code-craft

Use when writing or refactoring code, structuring a commit or PR, or deciding whether to abstract duplication. Symptoms — mixing reorg with logic changes, a PR doing several things at once, a file growing large, the second copy of similar code, or unsure whether to DRY something up.

lguidolin/cloud-delivery-aks

Use when deploying to Kubernetes or Azure Kubernetes Service (AKS), configuring cloud secrets, setting up progressive rollout/canary, per-PR ephemeral environments, or k8s health probes. Keywords — Kubernetes, AKS, Key Vault, Argo Rollouts, Flagger, canary, blue-green, liveness, readiness, PodDisruptionBudget, HPA, rollback, GHCR.

lguidolin/commit-history-rewrite

Use when an existing repository has messy commit history that needs to conform to conventional commits before adopting release-please, or when intermediate WIP/fixup/merge commits need to be cleaned up.

lguidolin/conventional-commits-and-releases

Use when committing, writing a commit message, opening a PR that will be squash-merged, or configuring automated versioning/changelogs. Keywords — conventional commits, release-please, semver, feat/fix/chore, breaking change, changelog.

lguidolin/defense-in-depth-security

Use when handling untrusted input, secrets, authentication/authorization, or dependencies — or threat-modeling a new surface. Keywords — STRIDE, threat model, least privilege, secrets management, supply chain, dependency scanning, input validation, audit log, defense in depth.

lguidolin/designing-before-building

Use when starting a feature, fixing a non-trivial bug, or about to write implementation code — before any code exists. Symptoms you need this: "this is simple, I'll just code it", reaching for the editor before a design is approved, or an idea that hasn't been turned into a spec and plan.

lguidolin/engineering-constitution

Use when starting work in a project that follows the engineering constitution, orienting to its rules, or deciding which engineering practice applies to a task — spec writing, commits, testing, security, deploys, database, or UI work.

lguidolin/graphql-contract-testing

Use when writing a GraphQL query/mutation that the UI and a test will share, or building route/schema contract or smoke tests. Symptoms — copying a query into a test, a test asserting on query text, schema change that didn't break the UI build, or RLS/permission drift. Keywords — graphql-codegen, typed document, contract test, route smoke test.

lguidolin/init-repo-CI

Use when setting up a new repository with conventional commits, release-please, and CI automation, or when retrofitting an existing repository that lacks automated versioning and PR validation workflows.

lguidolin/interface-craft-and-accessibility

Use when building or styling UI — components, layouts, forms, design tokens — or making accessibility decisions. Keywords — a11y, WCAG, keyboard navigation, focus state, contrast, design system, minimalist UI, component reuse, ARIA, semantic HTML.

lguidolin/merge-gates-and-automation

Use when setting up or changing CI, pre-push hooks, or a task runner, or deciding what must pass before merge. Symptoms — tempted to put authoritative checks only in a local hook, skip CI, bypass with --no-verify, or unsure what gates a merge vs. runs locally.

lguidolin/observability-and-slos

Use when adding logging, metrics, tracing, health checks, SLOs, or alerting — or when building a service surface that needs to be operable and debuggable. Keywords — structured logs, OpenTelemetry, correlation id, RED metrics, liveness, readiness, SLI, SLO, error budget, alerting.

lguidolin/performance-and-scale

Use when working on hot paths, list endpoints, pagination, data-access in loops, or public interfaces/schemas. Symptoms — unbounded queries, N+1 access, no latency budget, optimizing without measuring, or changing an interface many consumers depend on. Keywords — pagination, N+1, Hyrum's Law, performance budget, bundle size.

lguidolin/postgres-postgraphile-rls-and-sql

Use when writing PostgreSQL, PostGraphile config, Row-Level Security policies, SQL schema files, or working on the Browser→App→PostGraphile→Postgres data path. Keywords — RLS, SECURITY DEFINER, search_path, pgSettings, grants, roles, GraphQL depth limit, query cost, statement_timeout, SQL file organization.

lguidolin/recording-decisions

Use when a design or architecture decision has been made and needs to be captured — writing a decision record or ADR, updating a decision index, noting a deferred idea, or superseding a past decision. Keywords — ADR, decision record, rationale, rejected alternatives, dependency index.

lguidolin/resilience-and-deploy-safety

Use when planning a deploy, designing a rollback, or responding to an incident or writing a postmortem. Keywords — deploy safety, rollback, immutable artifact, progressive delivery, canary, blast radius, incident response, blameless postmortem, error budget.

lguidolin/ship-it

Use when the user wants to ship work — push, PR, archive decision records, merge, and clean up. Handles the full lifecycle from committing final changes through post-merge cleanup including converting specs/plans to compact decision records.

lguidolin/tests-as-a-control

Use when writing or modifying tests, when a test breaks during a refactor, or when testing permission/role rules. Symptoms — tempted to edit a test to make it pass, testing only the happy path, a deny-test that started passing, flaky tests, or unsure what to assert.

関連スキル