惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
N
News and Events Feed by Topic
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
博客园 - 叶小钗
B
Blog
Vercel News
Vercel News
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Microsoft Security Blog
Microsoft Security Blog
S
Securelist
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
DataBreaches.Net
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Project Zero
Project Zero
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Check Point Blog
A
About on SuperTechFans
W
WeLiveSecurity
The GitHub Blog
The GitHub Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Zero-Downtime Migrations: A Step-by-Step Playbook
Digital Unicon · 2026-06-22 · via DEV Community

If you've ever typed ALTER TABLE on a production database and held your breath, this article is for you.

Database migrations are one of the most dangerous routine operations in software engineering. Done wrong, a simple column rename can take down your entire platform — locking tables, timing out connections, and turning your Monday morning deploy into an all-hands incident.

The good news: zero-downtime migrations are entirely achievable, even on large, high-traffic databases. They just require a different mental model – one where your schema and your code evolve together but independently.

This is the playbook my team uses. It's boring, methodical, and it works.


Why Migrations Go Wrong

Before the playbook, let's understand the failure modes.

Problem 1: The Lock

Most databases acquire an ACCESS EXCLUSIVE lock when you alter a table. This blocks every read and write until the migration finishes. On a large table, "finishes" can mean minutes or hours.

-- This looks innocent. It is not.
ALTER TABLE users ADD COLUMN last_seen_at TIMESTAMP;

-- On a 50M row table with active traffic?
-- You just blocked every query touching `users`.

Problem 2: Deploying Code and Schema Together

The classic mistake: you rename a column and deploy your app at the same time. For one brief window, your new code is looking for email_address while the database still has email. Errors spike. Users see failures. You roll back both and start over.

Problem 3: The Irreversible Change

You drop a column. The deploy succeeds. Then you realize the old version of your app (still running on 2 of your 10 servers during a rolling deploy) needed that column. Now you have 500 errors per second and no way to un-drop.


The Mental Model: Expand and Contract

The solution to all three problems is a pattern called Expand and Contract (sometimes called parallel change).

The idea is simple:

Never make a breaking schema change in a single step. Instead, expand the schema to support both old and new states, update your application code, then contract the schema by removing what's no longer needed.

Every migration becomes a 3-phase process spread across multiple deploys:

Phase 1: EXPAND   → Add new structure, keep old structure intact
Phase 2: MIGRATE  → Move data, update app code to use new structure
Phase 3: CONTRACT → Remove old structure once it's no longer referenced

Each phase is independently deployable. Each phase is independently rollback-safe.

Let's walk through it concretely.


Phase 1: Expand

Goal: Make the database compatible with both the old app and the new app simultaneously.

Say you want to rename users.name to users.full_name.

In the Expand phase, you add the new column without removing the old one:

-- Migration: 001_add_full_name_column.sql
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);

Why this is safe: Adding a nullable column (or one with a default) doesn't require a full table rewrite in modern databases. PostgreSQL 11+ handles this instantly via a catalog change. MySQL 8.0+ with ALGORITHM=INSTANT does the same.

At this point, your old app still reads and writes name. The new column exists but is empty. Nothing breaks.

Pro tip for large tables — avoid long locks entirely:

-- PostgreSQL: Use concurrent index builds, not blocking ones
CREATE INDEX CONCURRENTLY idx_users_full_name ON users(full_name);

-- MySQL: Use pt-online-schema-change or gh-ost for large table alters


Phase 2: Migrate (Data + Code)

This is the meaty phase. It has two parts that happen together.

Part A: Backfill the Data

Copy data from the old column to the new one. Don't do this in a single UPDATE — it locks the table and may run for hours.

Instead, backfill in batches:

import psycopg2
import time

conn = psycopg2.connect(DATABASE_URL)
cursor = conn.cursor()

BATCH_SIZE = 1000
last_id = 0

while True:
    cursor.execute("""
        UPDATE users
        SET full_name = name
        WHERE id > %s
          AND full_name IS NULL
        ORDER BY id
        LIMIT %s
        RETURNING id
    """, (last_id, BATCH_SIZE))

    rows = cursor.fetchall()
    conn.commit()

    if not rows:
        break

    last_id = rows[-1][0]
    print(f"Backfilled up to id={last_id}")
    time.sleep(0.05)  # Breathing room for other queries

print("Backfill complete.")

This approach:

  • Never locks the table for more than a few milliseconds per batch
  • Can be paused and resumed
  • Can run in production without impacting traffic

Part B: Update Your Application Code

Now deploy the application code that writes to both columns and reads from the new column:

# Before (Phase 1 app code)
def update_user_name(user_id, name):
    db.execute("UPDATE users SET name = %s WHERE id = %s", (name, user_id))

def get_user(user_id):
    return db.fetchone("SELECT name FROM users WHERE id = %s", (user_id,))


# After (Phase 2 app code) — dual-write, read from new column
def update_user_name(user_id, name):
    db.execute("""
        UPDATE users
        SET name = %s, full_name = %s
        WHERE id = %s
    """, (name, name, user_id))

def get_user(user_id):
    return db.fetchone("SELECT full_name FROM users WHERE id = %s", (user_id,))

Why dual-write matters: During a rolling deploy, some servers run the old code, some run the new. Dual-writing ensures both versions stay in sync with no data loss regardless of which server handles a request.

Verify Before Moving On

Before Phase 3, confirm that:

  1. The backfill is 100% complete (no NULL values in full_name for rows that should have data)
  2. All application servers are on the Phase 2 code
  3. No old-code servers are still running (check your deployment dashboard)
-- Verify backfill completeness
SELECT COUNT(*)
FROM users
WHERE name IS NOT NULL
  AND full_name IS NULL;

-- Should return 0


Phase 3: Contract

Only when Phase 2 has been fully deployed and verified do you remove the old column.

-- Migration: 003_drop_old_name_column.sql
ALTER TABLE users DROP COLUMN name;

And clean up your application code:

# Phase 3 app code — old column gone, no more dual-write
def update_user_name(user_id, name):
    db.execute("UPDATE users SET full_name = %s WHERE id = %s", (name, user_id))

def get_user(user_id):
    return db.fetchone("SELECT full_name FROM users WHERE id = %s", (user_id,))

The key insight: At this point, nothing in your codebase references name anymore. Dropping it is completely safe. If something breaks, it was already broken before you ran this migration.


The Rollback Plan

Every phase should have an explicit rollback strategy.

Phase If something goes wrong... Rollback action
Phase 1 (Expand) App misbehaves after new column added Drop the new column. Old code never touched it.
Phase 2 (Migrate) New code has bugs, reads fail Re-deploy old code. Old column is still intact. Data is still there.
Phase 3 (Contract) Realise old column was still needed This is hard. Don't rush Phase 3.

The most important rule: never skip Phase 2. The temptation to combine "add new column, migrate data, drop old column" into a single migration script is real — and it's how incidents happen.


Real-World Patterns Cheat Sheet

Here are common migration scenarios mapped to the Expand/Contract approach:

Rename a Column

  • Expand: Add new column
  • Migrate: Backfill data, dual-write in code
  • Contract: Drop old column

Add a NOT NULL Column

-- Phase 1: Add as nullable
ALTER TABLE orders ADD COLUMN shipped_at TIMESTAMP NULL;

-- Phase 2: Backfill, then add constraint
UPDATE orders SET shipped_at = created_at WHERE status = 'shipped';

-- Phase 3: Enforce the constraint
ALTER TABLE orders ALTER COLUMN shipped_at SET NOT NULL;

Split a Column into Two

  • Expand: Add both new columns
  • Migrate: Parse and populate from old column in batches
  • Contract: Drop old column

Change a Column Type (e.g. INT → BIGINT)

  • Expand: Add new column with new type
  • Migrate: Copy and cast data, dual-write in code
  • Contract: Drop old column, rename new one (or keep new name in code)

Tools Worth Knowing

Tool Use case
gh-ost (GitHub) Online schema changes for MySQL — copies table in background, applies binlog changes
pglogical Logical replication for PostgreSQL migrations between major versions
Flyway / Liquibase Schema version control — tracks which migrations have run per environment
pt-online-schema-change Percona's alternative to gh-ost for MySQL
strong_migrations (Ruby) Catches unsafe migrations in Rails at dev time before they hit production

The 3 AM Test

Before you run any migration in production, ask yourself:

If this migration goes wrong at 3 AM, can I roll it back in under 5 minutes without data loss?

If the answer is no — split it into smaller phases until it is.

Zero-downtime migrations aren't magic. They're discipline. Each phase is small, safe, and independently reversible. The whole process takes longer than a single scary ALTER TABLE, but it's the difference between a boring Tuesday deploy and an incident retrospective.

Your on-call rotation will thank you.


Summary

  1. Never change schema and code atomically. Decouple them across phases.
  2. Expand first — add new structure, don't remove old structure.
  3. Migrate safely — batch backfills, dual-write during transition.
  4. Contract last — only drop old structure after all code has moved on.
  5. Always have a rollback plan for each phase independently.
  6. Use the right toolsgh-ost, CREATE INDEX CONCURRENTLY, and batch scripts are your friends.