This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-orm-zero-downtime-migration-advisory-locking-standard

Drizzle ORM Zero-Downtime Safe DDL Migrations & Advisory Locking Standard

Enforces non-blocking zero-downtime database migrations with Drizzle ORM through strict PostgreSQL advisory locking, bounded lock timeouts, and multi-phase expand-contract schema evolution. Eliminates race conditions across auto-scaling replicas and prevents cascading connection pool exhaustion caused by unconstrained ACCESS EXCLUSIVE locks.

Prohibited Anti-Pattern: Running concurrent unprotected Drizzle migrations on app boot without advisory locks or bounded lock timeouts.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM Zero-Downtime Safe DDL Migrations & Advisory Locking Standard - Enforces non-blocking zero-downtime database migrations with Drizzle ORM through strict PostgreSQL advisory locking, bounded lock timeouts, and multi-phase expand-contract schema evolution. Eliminates race conditions across auto-scaling replicas and prevents cascading connection pool exhaustion caused by unconstrained ACCESS EXCLUSIVE locks.
globs: src/db/migrate.{ts,js}, src/db/schema/**/*.{ts,js}, drizzle.config.ts, scripts/migrate.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-orm-zero-downtime-migration-advisory-locking-standard"
---

# Drizzle ORM Zero-Downtime Safe DDL Migrations & Advisory Locking Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Running concurrent unprotected Drizzle migrations on app boot without advisory locks or bounded lock timeouts.

## System Constraints
You are a Principal Software Architect enforcing zero-downtime database evolution and concurrency guardrails for Drizzle ORM. Mandate transactional PostgreSQL advisory locks, strict statement and lock timeouts, and decoupled execution architectures to eliminate deployment deadlocks and catastrophic table locks.

## Strict Guidelines
- Engineers MUST ALWAYS acquire an explicit PostgreSQL advisory lock (e.g., via `pg_advisory_xact_lock`) before executing Drizzle DDL operations across distributed environments.
- Engineers MUST ALWAYS enforce bounded session-level timeouts (`lock_timeout = '3s'` and `statement_timeout = '30s'`) prior to running migrations to prevent queued DDL statements from blocking application queries.
- Engineers MUST NOT execute `migrate()` or DDL queries within application runtime initialization loops across horizontally scaled web containers.
- Engineers MUST execute all schema mutations via an isolated, single-runner orchestrator (such as a dedicated CI/CD pipeline step or Kubernetes Job).
- Engineers MUST execute column renames, drops, and constraints using expand-contract patterns across multiple deployment phases rather than single-step destructive alterations.
- Engineers MUST specify non-blocking index creation (`CREATE INDEX CONCURRENTLY`) outside transaction blocks when adding indexes to high-traffic tables.

## Bad vs Good Implementations
### Unsafe boot-time migration without advisory locking or lock timeouts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Running migrate() on server boot across multiple auto-scaling containers causes race conditions and concurrent schema modifications. Without setting lock_timeout, any pending DDL statement acquires an ACCESS EXCLUSIVE lock queue, blocking all subsequent reads and writes and exhausting connection pools.
```typescript
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import express from 'express';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool);
const app = express();

// ANTI-PATTERN: Migrations run inside every pod startup simultaneously,
// with no distributed locks and no lock timeouts, triggering ACCESS EXCLUSIVE blocking.
async function startServer() {
  await migrate(db, { migrationsFolder: './drizzle' });
  app.listen(3000, () => console.log('Server running'));
}

startServer();
```

#### Production Standard (Correct)
> **Standard**: The migration runs in an isolated single-client process. It sets a 3-second `lock_timeout` to prevent blocking the query queue if a lock cannot be immediately acquired, and leverages `pg_advisory_xact_lock` to ensure strictly serialized execution across distributed runners.
```typescript
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { sql } from 'drizzle-orm';
import { Pool } from 'pg';

const MIGRATION_LOCK_ID = 8529340192837482n; // Unique 64-bit advisory lock key

export async function runZeroDowntimeMigration(): Promise<void> {
  const pool = new Pool({
    connectionString: process.env.MIGRATION_DATABASE_URL,
    max: 1,
    connectionTimeoutMillis: 5000,
  });

  const client = await pool.connect();
  const db = drizzle(client);

  try {
    await client.query('BEGIN');

    // Invariant 1: Constrain lock wait time to 3 seconds to avoid queuing behind long transactions
    await client.query("SET LOCAL lock_timeout = '3s'");
    await client.query("SET LOCAL statement_timeout = '30s'");

    // Invariant 2: Distributed mutual exclusion via transaction-scoped advisory lock
    await client.query('SELECT pg_advisory_xact_lock($1)', [MIGRATION_LOCK_ID.toString()]);

    // Invariant 3: Execute versioned migrations under locked transaction context
    await migrate(db, { migrationsFolder: './drizzle' });

    await client.query('COMMIT');
    console.log('Migration successfully applied with advisory lock.');
  } catch (error) {
    await client.query('ROLLBACK');
    console.error('Migration aborted to protect production workloads:', error);
    throw error;
  } finally {
    client.release();
    await pool.end();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Drizzle ORM Zero-Downtime Safe DDL Migrations & Advisory Locking Standard

Drizzle ORM Zero-Downtime Safe DDL Migrations & Advisory Locking Standard defines an industrial-grade behavioral standard for backend engineering. Enforces non-blocking zero-downtime database migrations with Drizzle ORM through strict PostgreSQL advisory locking, bounded lock timeouts, and multi-phase expand-contract schema evolution. Eliminates race conditions across auto-scaling replicas and prevents cascading connection pool exhaustion caused by unconstrained ACCESS EXCLUSIVE locks. 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: Running concurrent unprotected Drizzle migrations on app boot without advisory locks or bounded lock timeouts. 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 DriftRunning concurrent unprotected Drizzle migrations on app boot without advisory locks or bounded lock timeouts.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 acquire an explicit PostgreSQL advisory lock (e.g., via `pg_advisory_xact_lock`) before executing Drizzle DDL operations across distributed environments.

Engineers MUST ALWAYS acquire an explicit PostgreSQL advisory lock (e.g., via `pg_advisory_xact_lock`) before executing Drizzle DDL operations across distributed environments.

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 ALWAYS enforce bounded session-level timeouts (`lock_timeout = '3s'` and `statement_timeout = '30s'`) prior to running migrations to prevent queued DDL statements from blocking application queries.

Engineers MUST ALWAYS enforce bounded session-level timeouts (`lock_timeout = '3s'` and `statement_timeout = '30s'`) prior to running migrations to prevent queued DDL statements from blocking application queries.

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 execute `migrate()` or DDL queries within application runtime initialization loops across horizontally scaled web containers.

Engineers MUST NOT execute `migrate()` or DDL queries within application runtime initialization loops across horizontally scaled web containers.

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

Engineers MUST execute all schema mutations via an isolated, single-runner orchestrator (such as a dedicated CI/CD pipeline step or Kubernetes Job).

Engineers MUST execute all schema mutations via an isolated, single-runner orchestrator (such as a dedicated CI/CD pipeline step or Kubernetes Job).

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

Engineers MUST execute column renames, drops, and constraints using expand-contract patterns across multiple deployment phases rather than single-step destructive alterations.

Engineers MUST execute column renames, drops, and constraints using expand-contract patterns across multiple deployment phases rather than single-step destructive alterations.

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

Engineers MUST specify non-blocking index creation (`CREATE INDEX CONCURRENTLY`) outside transaction blocks when adding indexes to high-traffic tables.

Engineers MUST specify non-blocking index creation (`CREATE INDEX CONCURRENTLY`) outside transaction blocks when adding indexes to high-traffic tables.

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 Safe DDL Migrations & Advisory Locking Standard critical for AI coding assistants?

Enforces non-blocking zero-downtime database migrations with Drizzle ORM through strict PostgreSQL advisory locking, bounded lock timeouts, and multi-phase expand-contract schema evolution. Eliminates race conditions across auto-scaling replicas and prevents cascading connection pool exhaustion caused by unconstrained ACCESS EXCLUSIVE locks. 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 (Running concurrent unprotected Drizzle migrations on app boot without advisory locks or bounded lock timeouts.) 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