Communitygithub.com

lguidolin/zero-downtime-migrations

用于在数据库模式变更时确保数据存活——添加/移除/重命名列、约束、索引或回填数据。典型症状:破坏性迁移与代码部署捆绑、带回填的 NOT NULL 列、表锁 UPDATE 或重命名操作。关键词:扩展/收缩、并行变更、回填、NOT VALID、CREATE INDEX CONCURRENTLY、graphile-migrate。

zero-downtime-migrations 是什么?

该技能提供了一套零停机数据库模式变更的严谨方法,适用于持续运行的系统在滚动部署期间必须保持可用性的场景。在滚动部署过程中,新旧 Pod 共享同一个数据库,因此模式必须同时兼容两个应用版本。将破坏性迁移与依赖该迁移的部署捆绑在一起是导致自产停机的经典错误。技能的核心是“扩展/收缩”(Expand/Contract)模式,将模式变更拆分为三个独立的发布阶段:扩展阶段以向后兼容的方式添加新结构(如可空列、新表),迁移阶段通过分批回填和双写操作过渡,收缩阶段仅在旧应用完全退役后移除遗留结构。此外,还详细列出了 Postgres 的常见陷阱及安全做法,例如使用 NOT VALID 约束后再 VALIDATE、CREATE INDEX CONCURRENTLY 必须脱离事务执行等。该技能适用于所有需要数据存活的部署环境,尤其是带有阶段性数据或生产数据的系统。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lguidolin/agent-skills/tree/main/skills/zero-downtime-migrations

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

零停机迁移

概述

一种模式变更规范,确保在滚动部署期间运行的系统保持在线。在发布过程中,旧 Pod 和新 Pod 共享同一个数据库——因此模式必须同时兼容两个应用版本。 将破坏性迁移与依赖该迁移的部署捆绑在一起是导致自产停机的经典错误。

编写规则(所有项目)

  • 两种迁移类型,保持区分: 幂等的 current/ 集合(开发迭代——每次循环重新运行,使用 CREATE OR REPLACE / IF NOT EXISTS,对象处于最终形式,创建后无 ALTER)和已提交的迁移(不可变、有序,实际发布的版本)。ALTER DEFAULT PRIVILEGES 是唯一允许的内联 ALTER。
  • 所有权源自迁移运行的方式,而非零散的 ALTER ... OWNER。
  • 单一引导源,由本地/Docker 初始化路径和影子/测试数据库共享——每个环境以相同方式构建。

扩展/收缩(并行变更)

适用场景: 数据库包含在部署中必须存活的数据(阶段性数据或生产数据)。例外: 本地/可重置项目——但请按照此原则适用的方式编写已提交迁移,以便升级时无需重写。

模式变更分为三个发布阶段,而非一次完成:

  1. 扩展 —— 以增量方式添加新结构,保持向后兼容:新可空列、新表、新函数。应用版本 N 继续正常运行。
  2. 迁移 —— 在有限批次中进行回填(绝不用一个表锁 UPDATE);如果需要,从应用 N+1 进行双写;将读取切换到新结构。此时才添加 NOT NULL(先添加 NOT VALID 约束,然后单独执行 VALIDATE)。
  3. 收缩 —— 仅在应用 N 完全退役后,在后续发布中移除旧列/约束。

Postgres 常见陷阱

陷阱安全方法
带有易变/大型回填默认值的 NOT NULL 列添加可空列 → 分批回填 → 添加 NOT VALID 约束 → 执行 VALIDATE
添加约束先添加 NOT VALID,然后 VALIDATE CONSTRAINT(锁较弱)
构建索引CREATE INDEX CONCURRENTLY — 不能在事务中运行;隔离迁移工具的事务包装
阻塞的迁移冻结生产环境设置 lock_timeout / statement_timeout 以便快速失败
重命名列采用扩展/收缩模式:跨发布阶段添加新列 → 回填 → 切换读取 → 删除旧列

为什么“最终形式 CREATE OR REPLACE”在生产环境中不够用

该规则是开发人员的最佳实践,在开发环境中正确。但在生产环境中(有真实用户和滚动部署),两个应用版本在发布期间共享模式——因此扩展/收缩才是确保安全的方法。不要混淆两者。

完整原理:参见随附的 engineering-constitution/references/engineering-constitution.md 文档第 XVII 条。部署管道: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.

相关技能