This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-memory-tuning-index-pinning-guardrail

Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning

Prevents catastrophic transaction ID (TXID) wraparound outages and query plan degradation across multi-terabyte transactional datasets. Enforces Postgres 17 radix-tree vacuum memory utilization, adaptive WAL checkpoint smoothing, and deterministic buffer pinning of mission-critical indexes via pg_prewarm to protect shared buffer hit rates under concurrent write spikes.

Prohibited Anti-Pattern: Unbounded Autovacuum Degradation, Missing Buffer Pinning, and Premature WAL Flush Storms Under High Concurrency

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning - Prevents catastrophic transaction ID (TXID) wraparound outages and query plan degradation across multi-terabyte transactional datasets. Enforces Postgres 17 radix-tree vacuum memory utilization, adaptive WAL checkpoint smoothing, and deterministic buffer pinning of mission-critical indexes via pg_prewarm to protect shared buffer hit rates under concurrent write spikes.
globs: infra/postgres/**/*.conf, infra/k8s/**/*.yaml, migrations/**/*.sql, src/database/**/*.ts, src/infra/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-memory-tuning-index-pinning-guardrail"
---

# Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Autovacuum Degradation, Missing Buffer Pinning, and Premature WAL Flush Storms Under High Concurrency

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing Postgres 17 memory sizing, adaptive checkpointing, and vacuum concurrency invariants. In multi-terabyte transactional workloads, prevent TXID wraparound and I/O buffer thrashing by mandating Postgres 17's internal radix tree vacuum configuration, aggressive autovacuum cost scaling, index pre-warming, and strict lock-timeout wrapped operational scripts.

## Strict Guidelines
- Engineers MUST configure 'checkpoint_completion_target = 0.9' and scale 'max_wal_size' to at least 64GB in multi-terabyte engines to avoid I/O spikes caused by premature checkpoint flushing.
- Engineers MUST leverage Postgres 17's optimized radix tree vacuum memory management by setting 'maintenance_work_mem' to at least 2GB without exceeding 1/8th of host RAM to prevent per-worker swap thrashing.
- Engineers MUST set 'autovacuum_freeze_max_age' to 1.5 billion (safe margin below the 2 billion hard wraparound) and configure 'autovacuum_vacuum_cost_limit = 2000' with 'autovacuum_vacuum_cost_delay = 2ms' to ensure autovacuum outpaces ingest volume.
- Database deployment scripts MUST execute 'pg_prewarm' with the 'buffer' mode on primary foreign-key and B-tree ordering indexes immediately after instance initialization or failover.
- Engineers MUST NOT execute long-running transactional scripts, index operations, or manual VACUUM ANALYZE commands without setting explicit 'lock_timeout' and 'statement_timeout' barriers.
- Connection pools MUST dynamically configure connection-level 'work_mem' overrides for memory-heavy analytic queries rather than globally inflating cluster-wide 'work_mem'.
- Services MUST monitor catalog metrics 'pg_database.datfrozenxid' and 'pg_stat_database.xact_commit' to trigger P1 alerts when remaining TXIDs drop below 200 million.

## Bad vs Good Implementations
### Postgres 17 Engine Bootstrapping & Buffer Pinning Automation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing manual VACUUM ANALYZE without lock_timeout risks severe lock queuing behind long-running queries. Scanning tables via SELECT COUNT(*) populates shared buffers with table heap data instead of pinning high-utility index leaves, leading to buffer eviction under concurrent writes.
```typescript
import { Pool } from 'pg';

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

// ANTI-PATTERN: Executing DDL/maintenance without lock safeguards,
// using global work_mem defaults, and relying on cold cache reads
export async function bootstrapWarmCache(criticalTables: string[]): Promise<void> {
  const client = await pool.connect();
  try {
    for (const table of criticalTables) {
      // Running synchronous vacuum without timeout can stall transactions
      await client.query(`VACUUM ANALYZE ${table}`);
      // Simple seq-scan does not pin index blocks to shared_buffers cleanly
      await client.query(`SELECT COUNT(*) FROM ${table}`);
    }
  } finally {
    client.release();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Sets strict local lock and statement timeouts to avoid head-of-line blocking in connection queues. Employs Postgres's pg_prewarm extension to deterministically warm shared buffers for index relations rather than polluting cache with full table scans.
```typescript
import { Pool, PoolClient } from 'pg';

interface WarmupTarget {
  relation: string;
  mode: 'buffer' | 'read';
}

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 10000,
});

// PRODUCTION INVARIANT: Use pg_prewarm for deterministic index caching,
// bound maintenance timeouts, and enforce non-blocking lock governance
export async function pinCriticalIndexes(targets: WarmupTarget[]): Promise<void> {
  const client: PoolClient = await pool.connect();
  try {
    await client.query('BEGIN;');
    // Establish deterministic operational fences
    await client.query("SET LOCAL lock_timeout = '3s';");
    await client.query("SET LOCAL statement_timeout = '60s';");
    
    // Ensure extension availability
    await client.query('CREATE EXTENSION IF NOT EXISTS pg_prewarm;');

    for (const target of targets) {
      // Pin index and high-frequency tables specifically into shared_buffers
      await client.query(
        'SELECT pg_prewarm($1, $2, $3);',
        [target.relation, target.mode, 'main']
      );
    }
    
    await client.query('COMMIT;');
  } catch (error) {
    await client.query('ROLLBACK;').catch(() => {});
    throw new Error(`Failed to pin Postgres indexes safely: ${(error as Error).message}`);
  } finally {
    client.release();
  }
}
```

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: Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning

Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning defines an industrial-grade behavioral standard for backend engineering. Prevents catastrophic transaction ID (TXID) wraparound outages and query plan degradation across multi-terabyte transactional datasets. Enforces Postgres 17 radix-tree vacuum memory utilization, adaptive WAL checkpoint smoothing, and deterministic buffer pinning of mission-critical indexes via pg_prewarm to protect shared buffer hit rates under concurrent write spikes. 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: Unbounded Autovacuum Degradation, Missing Buffer Pinning, and Premature WAL Flush Storms Under High Concurrency 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 DriftUnbounded Autovacuum Degradation, Missing Buffer Pinning, and Premature WAL Flush Storms Under High ConcurrencyCritical
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 configure 'checkpoint_completion_target = 0.9' and scale 'max_wal_size' to at least 64GB in multi-terabyte engines to avoid I/O spikes caused by premature checkpoint flushing.

Engineers MUST configure 'checkpoint_completion_target = 0.9' and scale 'max_wal_size' to at least 64GB in multi-terabyte engines to avoid I/O spikes caused by premature checkpoint flushing.

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 leverage Postgres 17's optimized radix tree vacuum memory management by setting 'maintenance_work_mem' to at least 2GB without exceeding 1/8th of host RAM to prevent per-worker swap thrashing.

Engineers MUST leverage Postgres 17's optimized radix tree vacuum memory management by setting 'maintenance_work_mem' to at least 2GB without exceeding 1/8th of host RAM to prevent per-worker swap thrashing.

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 set 'autovacuum_freeze_max_age' to 1.5 billion (safe margin below the 2 billion hard wraparound) and configure 'autovacuum_vacuum_cost_limit = 2000' with 'autovacuum_vacuum_cost_delay = 2ms' to ensure autovacuum outpaces ingest volume.

Engineers MUST set 'autovacuum_freeze_max_age' to 1.5 billion (safe margin below the 2 billion hard wraparound) and configure 'autovacuum_vacuum_cost_limit = 2000' with 'autovacuum_vacuum_cost_delay = 2ms' to ensure autovacuum outpaces ingest volume.

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

Database deployment scripts MUST execute 'pg_prewarm' with the 'buffer' mode on primary foreign-key and B-tree ordering indexes immediately after instance initialization or failover.

Database deployment scripts MUST execute 'pg_prewarm' with the 'buffer' mode on primary foreign-key and B-tree ordering indexes immediately after instance initialization or failover.

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 NOT execute long-running transactional scripts, index operations, or manual VACUUM ANALYZE commands without setting explicit 'lock_timeout' and 'statement_timeout' barriers.

Engineers MUST NOT execute long-running transactional scripts, index operations, or manual VACUUM ANALYZE commands without setting explicit 'lock_timeout' and 'statement_timeout' barriers.

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

Connection pools MUST dynamically configure connection-level 'work_mem' overrides for memory-heavy analytic queries rather than globally inflating cluster-wide 'work_mem'.

Connection pools MUST dynamically configure connection-level 'work_mem' overrides for memory-heavy analytic queries rather than globally inflating cluster-wide 'work_mem'.

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 monitor catalog metrics 'pg_database.datfrozenxid' and 'pg_stat_database.xact_commit' to trigger P1 alerts when remaining TXIDs drop below 200 million.

Services MUST monitor catalog metrics 'pg_database.datfrozenxid' and 'pg_stat_database.xact_commit' to trigger P1 alerts when remaining TXIDs drop below 200 million.

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 Postgres 17 Workload-Adaptive Memory Tuning & High-Concurrency Index Pinning critical for AI coding assistants?

Prevents catastrophic transaction ID (TXID) wraparound outages and query plan degradation across multi-terabyte transactional datasets. Enforces Postgres 17 radix-tree vacuum memory utilization, adaptive WAL checkpoint smoothing, and deterministic buffer pinning of mission-critical indexes via pg_prewarm to protect shared buffer hit rates under concurrent write spikes. 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 (Unbounded Autovacuum Degradation, Missing Buffer Pinning, and Premature WAL Flush Storms Under High Concurrency) 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

Postgres