This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-zero-downtime-dual-write-schema-evolution

Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail

Enforces the expand-and-contract pattern for Drizzle ORM schema modifications in high-concurrency 24/7 OLTP environments. Strictly prevents atomic in-place column renames, type mutations, and immediate column drops that cause downtime across phased application fleet rollouts. Mandates explicit multi-phase dual-writing, non-destructive migration sequences, and type-safe schema fallback readers.

Prohibited Anti-Pattern: Executing in-place schema column renames or destructive drops directly in Drizzle ORM definitions during rolling deployments.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail - Enforces the expand-and-contract pattern for Drizzle ORM schema modifications in high-concurrency 24/7 OLTP environments. Strictly prevents atomic in-place column renames, type mutations, and immediate column drops that cause downtime across phased application fleet rollouts. Mandates explicit multi-phase dual-writing, non-destructive migration sequences, and type-safe schema fallback readers.
globs: src/db/schema/**/*.{ts,tsx}, src/db/migrations/**/*.{ts,sql}, src/repositories/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-zero-downtime-dual-write-schema-evolution"
---

# Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing in-place schema column renames or destructive drops directly in Drizzle ORM definitions during rolling deployments.

## System Constraints
You are a Principal Software Architect enforcing zero-downtime OLTP database evolutions using Drizzle ORM. You must reject any destructive schema change, direct in-place column rename, immediate type casting, or instant non-nullable column creation on active production tables. Enforce strict multi-phase expand/contract lifecycles with dual-write application layers, asynchronous historical backfilling, and coalesced backward-compatible query projections.

## Strict Guidelines
- Engineers MUST ALWAYS implement schema changes across multiple distinct deployment phases: Expand (add nullable target column), Dual-Write (write to both, read from legacy), Backfill (hydrate target column asynchronously), Flip Reads (read from target, write to both), and Contract (remove legacy column).
- Engineers MUST NOT execute `ALTER TABLE ... RENAME COLUMN` or rename Drizzle column keys directly in a single release cycle.
- Engineers MUST NOT use `drizzle-kit push` against live production databases; all migrations must be reviewed as explicit forward-only SQL artifacts via `drizzle-kit generate`.
- Code MUST dual-write to both legacy and shadow columns in all `db.insert()` and `db.update()` operations during active transition phases.
- Queries SHOULD read transitional columns using SQL `coalesce` or application-level fallback selectors (`newColumn ?? legacyColumn`) before the historical backfill phase completes.
- New columns added to existing tables with active traffic MUST be defined as `.default()` or nullable (`.$default()` / omitted `.notNull()`) on initial creation to avoid metadata locking and table rewrites.
- Services MUST verify zero pending legacy reads and validate 100% data parity between old and new columns via automated verification scripts prior to initiating the Contract phase.
- Components NEVER execute structural DDL modifications inside long-running application transactions.

## Bad vs Good Implementations
### Renaming a Column: In-Place Rename vs. Phased Dual-Write Evolution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly renaming the underlying database column in Drizzle results in an immediate `ALTER TABLE ... RENAME COLUMN` migration. Application instances running the prior code version immediately fail queries referencing the old column name. In addition, rollbacks become destructive.
```typescript
import { pgTable, text, uuid } from 'drizzle-orm/pg-core';

// ANTI-PATTERN: Renaming 'phone_number' to 'contact_phone' in-place.
// When deployed to production, old running pods immediately crash with 
// 'column users.phone_number does not exist' during rolling deployment.
export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  // In-place rename breaks rolling deployment replicas
  contactPhone: text('contact_phone').notNull(),
});

export async function updateUserPhone(db: any, id: string, phone: string) {
  return db.update(users)
    .set({ contactPhone: phone })
    .where(users.id.equals(id));
}
```

#### Production Standard (Correct)
> **Standard**: The schema preserves both columns during the migration window. All write operations simultaneously update both columns (dual-write), and reads use SQL `COALESCE` to ensure zero missing data regardless of whether historical rows have been backfilled or if old/new application versions are currently executing.
```typescript
import { pgTable, text, uuid } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';

// PHASE 1 & 2: EXPAND & DUAL-WRITE
// Retain legacy column while provisioning the new column as nullable for non-blocking DDL.
export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  // Legacy column maintained for backward compatibility
  phoneNumber: text('phone_number'),
  // New column deployed as nullable without table-level write locks
  contactPhone: text('contact_phone'),
});

// Data Access Layer enforces dual-write across both columns
export async function updateUserPhone(db: any, id: string, phone: string) {
  return db.update(users)
    .set({
      phoneNumber: phone,
      contactPhone: phone,
    })
    .where(sql`${users.id} = ${id}`);
}

// Read query provides fallback compatibility during backfill
export async function getUserPhone(db: any, id: string) {
  const [record] = await db.select({
    resolvedPhone: sql<string>`COALESCE(${users.contactPhone}, ${users.phoneNumber})`,
  })
  .from(users)
  .where(sql`${users.id} = ${id}`);

  return record?.resolvedPhone ?? null;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail

Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces the expand-and-contract pattern for Drizzle ORM schema modifications in high-concurrency 24/7 OLTP environments. Strictly prevents atomic in-place column renames, type mutations, and immediate column drops that cause downtime across phased application fleet rollouts. Mandates explicit multi-phase dual-writing, non-destructive migration sequences, and type-safe schema fallback readers. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Executing in-place schema column renames or destructive drops directly in Drizzle ORM definitions during rolling deployments. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftExecuting in-place schema column renames or destructive drops directly in Drizzle ORM definitions during rolling deployments.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS implement schema changes across multiple distinct deployment phases

Engineers MUST ALWAYS implement schema changes across multiple distinct deployment phases: Expand (add nullable target column), Dual-Write (write to both, read from legacy), Backfill (hydrate target column asynchronously), Flip Reads (read from target, write to both), and Contract (remove legacy column).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT execute `ALTER TABLE ... RENAME COLUMN` or rename Drizzle column keys directly in a single release cycle.

Engineers MUST NOT execute `ALTER TABLE ... RENAME COLUMN` or rename Drizzle column keys directly in a single release cycle.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT use `drizzle-kit push` against live production databases

Engineers MUST NOT use `drizzle-kit push` against live production databases; all migrations must be reviewed as explicit forward-only SQL artifacts via `drizzle-kit generate`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST dual-write to both legacy and shadow columns in all `db.insert()` and `db.update()` operations during active transition phases.

Code MUST dual-write to both legacy and shadow columns in all `db.insert()` and `db.update()` operations during active transition phases.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Queries SHOULD read transitional columns using SQL `coalesce` or application-level fallback selectors (`newColumn ?? legacyColumn`) before the historical backfill phase completes.

Queries SHOULD read transitional columns using SQL `coalesce` or application-level fallback selectors (`newColumn ?? legacyColumn`) before the historical backfill phase completes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

New columns added to existing tables with active traffic MUST be defined as `.default()` or nullable (`.$default()` / omitted `.notNull()`) on initial creation to avoid metadata locking and table rewrites.

New columns added to existing tables with active traffic MUST be defined as `.default()` or nullable (`.$default()` / omitted `.notNull()`) on initial creation to avoid metadata locking and table rewrites.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Services MUST verify zero pending legacy reads and validate 100% data parity between old and new columns via automated verification scripts prior to initiating the Contract phase.

Services MUST verify zero pending legacy reads and validate 100% data parity between old and new columns via automated verification scripts prior to initiating the Contract phase.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
8

Components NEVER execute structural DDL modifications inside long-running application transactions.

Components NEVER execute structural DDL modifications inside long-running application transactions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Drizzle ORM Zero-Downtime Dual-Write Schema Evolution Guardrail critical for AI coding assistants?

Enforces the expand-and-contract pattern for Drizzle ORM schema modifications in high-concurrency 24/7 OLTP environments. Strictly prevents atomic in-place column renames, type mutations, and immediate column drops that cause downtime across phased application fleet rollouts. Mandates explicit multi-phase dual-writing, non-destructive migration sequences, and type-safe schema fallback readers. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Executing in-place schema column renames or destructive drops directly in Drizzle ORM definitions during rolling deployments.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Drizzle