This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: drizzle-keyset-cursor-monotonicity-fence

Drizzle ORM 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant

Enforces strictly monotonic, composite keyset cursors paired with an explicit read-view fence timestamp across all infinite pagination queries in Drizzle ORM 0.38. Prevents duplicate rows, skipped records, and phantom drift caused by concurrent writes under relational MVCC engines.

Prohibited Anti-Pattern: Offset-based pagination or unfenced single-column keyset cursors leading to duplicate rows and phantom data drift.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Drizzle ORM 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant - Enforces strictly monotonic, composite keyset cursors paired with an explicit read-view fence timestamp across all infinite pagination queries in Drizzle ORM 0.38. Prevents duplicate rows, skipped records, and phantom drift caused by concurrent writes under relational MVCC engines.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/services/**/*.ts, src/api/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/drizzle-keyset-cursor-monotonicity-fence"
---

# Drizzle ORM 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Offset-based pagination or unfenced single-column keyset cursors leading to duplicate rows and phantom data drift.

## System Constraints
You are a Principal Software Architect enforcing production-grade data consistency standards for high-concurrency relational queries using Drizzle ORM 0.38. You must reject any infinite pagination implementation relying on OFFSET/LIMIT or unfenced non-unique keyset cursors. You will mandate strictly monotonic composite keyset clauses with deterministic unique tie-breakers (e.g., id) and an immutable read-view fence timestamp to isolate against MVCC concurrent write drift.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a strictly monotonic composite keyset cursor consisting of the primary sorting field (e.g., createdAt) paired with an immutable unique tie-breaker (e.g., id).
- Engineers MUST ALWAYS bound pagination queries with an immutable read-view fence timestamp (`lte(table.createdAt, fenceTimestamp)`) established on page 0 to prevent newly committed transactions from displacing the cursor window.
- Engineers MUST NOT use `.offset()` for infinite scroll or feed pagination in high-write transactional tables.
- Engineers MUST ensure every keyset pagination query has an exact-match composite B-tree index in the Drizzle schema aligned with the query order (e.g., `index('idx_entity_created_id').on(table.createdAt.desc(), table.id.desc())`).
- Queries MUST fetch `limit + 1` rows to determine `hasNextPage` deterministically without executing a secondary `count()` query.
- Cursors emitted to clients MUST be opaque, serialized payloads (e.g., base64 encoded JSON) containing both the composite key values and the original `fenceTimestamp`.

## Bad vs Good Implementations
### Non-Monotonic Unfenced Keyset Cursor (Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Filtering solely by a non-unique timestamp causes records sharing identical timestamps across pages to be skipped or duplicated. The lack of a read-view fence allows concurrent inserts with older or matching timestamps to alter result boundaries dynamically between cursor fetches.
```typescript
import { desc, lt } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { posts } from './schema';

export async function getPostsFeed(
  db: NodePgDatabase,
  limit: number,
  cursorCreatedAt?: Date
) {
  // FAILS: Non-unique keyset (duplicate timestamps drop/skip records)
  // FAILS: No read-view fence (concurrent inserts shift results across pages)
  return db
    .select()
    .from(posts)
    .where(cursorCreatedAt ? lt(posts.createdAt, cursorCreatedAt) : undefined)
    .orderBy(desc(posts.createdAt))
    .limit(limit);
}
```

#### Production Standard (Correct)
> **Standard**: The composite cursor `(createdAt, id)` guarantees absolute uniqueness and monotonic progression. The `fenceTimestamp` creates an explicit temporal boundary that stops concurrent MVCC writes from polluting earlier or subsequent pages in the pagination stream.
```typescript
import { and, desc, eq, lt, lte, or } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { posts } from './schema';

export interface KeysetCursor {
  createdAt: Date;
  id: string;
  fenceTimestamp: Date;
}

export async function getPostsFeed(
  db: NodePgDatabase,
  limit: number,
  cursor?: KeysetCursor
) {
  const fenceTimestamp = cursor ? cursor.fenceTimestamp : new Date();
  const fetchLimit = limit + 1;

  const fenceCondition = lte(posts.createdAt, fenceTimestamp);

  const cursorCondition = cursor
    ? or(
        lt(posts.createdAt, cursor.createdAt),
        and(
          eq(posts.createdAt, cursor.createdAt),
          lt(posts.id, cursor.id)
        )
      )
    : undefined;

  const rows = await db
    .select()
    .from(posts)
    .where(cursorCondition ? and(fenceCondition, cursorCondition) : fenceCondition)
    .orderBy(desc(posts.createdAt), desc(posts.id))
    .limit(fetchLimit);

  const hasNextPage = rows.length > limit;
  const items = hasNextPage ? rows.slice(0, limit) : rows;
  const lastItem = items[items.length - 1];

  const nextCursor: KeysetCursor | null = hasNextPage && lastItem
    ? {
        createdAt: lastItem.createdAt,
        id: lastItem.id,
        fenceTimestamp,
      }
    : null;

  return {
    items,
    nextCursor,
  };
}
```

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 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant

Drizzle ORM 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strictly monotonic, composite keyset cursors paired with an explicit read-view fence timestamp across all infinite pagination queries in Drizzle ORM 0.38. Prevents duplicate rows, skipped records, and phantom drift caused by concurrent writes under relational MVCC engines. 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: Offset-based pagination or unfenced single-column keyset cursors leading to duplicate rows and phantom data drift. 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 DriftOffset-based pagination or unfenced single-column keyset cursors leading to duplicate rows and phantom data drift.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 enforce a strictly monotonic composite keyset cursor consisting of the primary sorting field (e.g., createdAt) paired with an immutable unique tie-breaker (e.g., id).

Engineers MUST ALWAYS enforce a strictly monotonic composite keyset cursor consisting of the primary sorting field (e.g., createdAt) paired with an immutable unique tie-breaker (e.g., id).

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 bound pagination queries with an immutable read-view fence timestamp (`lte(table.createdAt, fenceTimestamp)`) established on page 0 to prevent newly committed transactions from displacing the cursor window.

Engineers MUST ALWAYS bound pagination queries with an immutable read-view fence timestamp (`lte(table.createdAt, fenceTimestamp)`) established on page 0 to prevent newly committed transactions from displacing the cursor window.

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 `.offset()` for infinite scroll or feed pagination in high-write transactional tables.

Engineers MUST NOT use `.offset()` for infinite scroll or feed pagination in high-write transactional 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.
4

Engineers MUST ensure every keyset pagination query has an exact-match composite B-tree index in the Drizzle schema aligned with the query order (e.g., `index('idx_entity_created_id').on(table.createdAt.desc(), table.id.desc())`).

Engineers MUST ensure every keyset pagination query has an exact-match composite B-tree index in the Drizzle schema aligned with the query order (e.g., `index('idx_entity_created_id').on(table.createdAt.desc(), table.id.desc())`).

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 MUST fetch `limit + 1` rows to determine `hasNextPage` deterministically without executing a secondary `count()` query.

Queries MUST fetch `limit + 1` rows to determine `hasNextPage` deterministically without executing a secondary `count()` query.

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

Cursors emitted to clients MUST be opaque, serialized payloads (e.g., base64 encoded JSON) containing both the composite key values and the original `fenceTimestamp`.

Cursors emitted to clients MUST be opaque, serialized payloads (e.g., base64 encoded JSON) containing both the composite key values and the original `fenceTimestamp`.

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 0.38 Keyset Cursor Monotonicity and Read-View Fence Invariant critical for AI coding assistants?

Enforces strictly monotonic, composite keyset cursors paired with an explicit read-view fence timestamp across all infinite pagination queries in Drizzle ORM 0.38. Prevents duplicate rows, skipped records, and phantom drift caused by concurrent writes under relational MVCC engines. 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 (Offset-based pagination or unfenced single-column keyset cursors leading to duplicate rows and phantom data drift.) 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