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

Postgres 17 Parallel Vacuum Maintenance Work Memory Cap Allocation

Prevents catastrophic Out-Of-Memory (OOM) events and severe disk I/O thrashing during heavy write surges by governing PostgreSQL 17 vacuum worker allocations. Enforces dynamic ceilings across maintenance_work_mem, autovacuum_max_workers, and max_parallel_maintenance_workers, utilizing PG17's internal vacuum memory limits rather than unbounded global memory assignments. Eliminates multi-gigabyte memory exhaustion where concurrent index scans and parallel vacuum worker allocations cause cascading backend evictions.

Prohibited Anti-Pattern: Global Uncapped Maintenance Work Memory Allocation Across Concurrent Parallel Vacuum Workers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Parallel Vacuum Maintenance Work Memory Cap Allocation - Prevents catastrophic Out-Of-Memory (OOM) events and severe disk I/O thrashing during heavy write surges by governing PostgreSQL 17 vacuum worker allocations. Enforces dynamic ceilings across maintenance_work_mem, autovacuum_max_workers, and max_parallel_maintenance_workers, utilizing PG17's internal vacuum memory limits rather than unbounded global memory assignments. Eliminates multi-gigabyte memory exhaustion where concurrent index scans and parallel vacuum worker allocations cause cascading backend evictions.
globs: src/database/**/*.{ts,js,sql}, src/infra/**/*.{ts,js,sql}, src/config/**/*.{ts,js}, docker/postgres/**/*.sql, k8s/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-parallel-vacuum-memory-cap-guardrail"
---

# Postgres 17 Parallel Vacuum Maintenance Work Memory Cap Allocation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global Uncapped Maintenance Work Memory Allocation Across Concurrent Parallel Vacuum Workers

## System Constraints
You are a Principal Database Infrastructure Architect enforcing Postgres 17 Parallel Vacuum and Maintenance Memory limits. Postgres 17 radically modernizes vacuum indexing memory management, but uncoordinated configurations combining `maintenance_work_mem`, `max_parallel_maintenance_workers`, and `autovacuum_max_workers` will induce kernel OOM-killer termination during write surges. Mandate strictly bounded session-level memory overrides, dynamic per-worker allocation caps, and telemetry verification in all migrations, client drivers, and infrastructure-as-code manifests.

## Strict Guidelines
- Engineers MUST ALWAYS compute the maximum concurrent vacuum memory consumption using the invariant formula: `Peak_Memory = autovacuum_max_workers * (1 + max_parallel_maintenance_workers) * maintenance_work_mem` and guarantee this sum never exceeds 20% of total host RAM.
- Engineers MUST NOT issue raw `VACUUM (PARALLEL ...)` queries in application logic or scheduled jobs without explicitly bounding session-local `maintenance_work_mem` and `max_parallel_maintenance_workers` prior to invocation.
- Infrastructure scripts MUST set per-table autovacuum tuning using `autovacuum_vacuum_cost_limit` and `vacuum_maintenance_work_mem` overrides instead of globally inflating instance-wide maintenance memory to high gigabyte values.
- Database maintenance scripts and migration runners SHOULD inspect `pg_stat_progress_vacuum` to verify memory deadbands and ensure parallel worker allocations are dynamically throttled when replication lag or active client connections cross critical thresholds.
- Services MUST NEVER configure Postgres 17 vacuum workers using deprecated assumptions where individual parallel workers consume divided subsets of memory; parallel worker index vacuuming in high parallelism can scale aggregate allocation up to the configured cap concurrently.

## Bad vs Good Implementations
### Unsafe Parallel Vacuum Trigger vs. Guarded Adaptive Work Memory Allocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing parallel vacuum with an unmanaged parallel worker count and default server-level maintenance_work_mem (often inflated to 2-4GB by engineers) allows each active worker and autovacuum thread to exhaust host swap space and provoke Linux kernel OOM kills during ongoing write surges.
```typescript
import { Pool } from 'pg';

export async function runManualMaintenance(pool: Pool, tableName: string): Promise<void> {
  // DANGEROUS: Invokes unthrottled parallel vacuum on heavy write table.
  // Can trigger OOM if autovacuum is simultaneously active with high global maintenance_work_mem.
  await pool.query(`VACUUM (PARALLEL 8, ANALYZE, FULL) ${tableName};`);
}
```

#### Production Standard (Correct)
> **Standard**: Applies session-level constraints via SET LOCAL, capping memory to safe boundaries (256-512MB) and setting parallel worker thresholds to mitigate CPU/IO starvation and eliminate uncoordinated multi-gigabyte worker memory saturation.
```typescript
import { PoolClient } from 'pg';

interface SafeVacuumOptions {
  maxParallelWorkers?: number;
  boundedMemoryMb?: number;
  costDelayMs?: number;
}

export async function runSafeParallelVacuum(
  client: PoolClient,
  tableName: string,
  options: SafeVacuumOptions = {}
): Promise<void> {
  const maxWorkers = Math.min(options.maxParallelWorkers ?? 2, 4);
  const memoryMb = Math.min(options.boundedMemoryMb ?? 256, 512);
  const costDelay = Math.max(options.costDelayMs ?? 10, 2);

  // Guardrail: Restrict transaction/session context to isolated caps before vacuuming
  await client.query(`
    SET LOCAL maintenance_work_mem = '${memoryMb}MB';
    SET LOCAL max_parallel_maintenance_workers = ${maxWorkers};
    SET LOCAL vacuum_cost_delay = ${costDelay};
  `);

  try {
    // In Postgres 17, bounded maintenance_work_mem and explicit parallel bounds prevent IO/Memory blowups
    await client.query(`VACUUM (PARALLEL ${maxWorkers}, ANALYZE) ${tableName};`);
  } finally {
    await client.query(`
      RESET maintenance_work_mem;
      RESET max_parallel_maintenance_workers;
      RESET vacuum_cost_delay;
    `);
  }
}
```

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 Parallel Vacuum Maintenance Work Memory Cap Allocation

Postgres 17 Parallel Vacuum Maintenance Work Memory Cap Allocation defines an industrial-grade behavioral standard for backend engineering. Prevents catastrophic Out-Of-Memory (OOM) events and severe disk I/O thrashing during heavy write surges by governing PostgreSQL 17 vacuum worker allocations. Enforces dynamic ceilings across maintenance_work_mem, autovacuum_max_workers, and max_parallel_maintenance_workers, utilizing PG17's internal vacuum memory limits rather than unbounded global memory assignments. Eliminates multi-gigabyte memory exhaustion where concurrent index scans and parallel vacuum worker allocations cause cascading backend evictions. 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: Global Uncapped Maintenance Work Memory Allocation Across Concurrent Parallel Vacuum Workers 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 DriftGlobal Uncapped Maintenance Work Memory Allocation Across Concurrent Parallel Vacuum WorkersCritical
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 compute the maximum concurrent vacuum memory consumption using the invariant formula

Engineers MUST ALWAYS compute the maximum concurrent vacuum memory consumption using the invariant formula: `Peak_Memory = autovacuum_max_workers * (1 + max_parallel_maintenance_workers) * maintenance_work_mem` and guarantee this sum never exceeds 20% of total host RAM.

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 issue raw `VACUUM (PARALLEL ...)` queries in application logic or scheduled jobs without explicitly bounding session-local `maintenance_work_mem` and `max_parallel_maintenance_workers` prior to invocation.

Engineers MUST NOT issue raw `VACUUM (PARALLEL ...)` queries in application logic or scheduled jobs without explicitly bounding session-local `maintenance_work_mem` and `max_parallel_maintenance_workers` prior to invocation.

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

Infrastructure scripts MUST set per-table autovacuum tuning using `autovacuum_vacuum_cost_limit` and `vacuum_maintenance_work_mem` overrides instead of globally inflating instance-wide maintenance memory to high gigabyte values.

Infrastructure scripts MUST set per-table autovacuum tuning using `autovacuum_vacuum_cost_limit` and `vacuum_maintenance_work_mem` overrides instead of globally inflating instance-wide maintenance memory to high gigabyte values.

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 maintenance scripts and migration runners SHOULD inspect `pg_stat_progress_vacuum` to verify memory deadbands and ensure parallel worker allocations are dynamically throttled when replication lag or active client connections cross critical thresholds.

Database maintenance scripts and migration runners SHOULD inspect `pg_stat_progress_vacuum` to verify memory deadbands and ensure parallel worker allocations are dynamically throttled when replication lag or active client connections cross critical thresholds.

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

Services MUST NEVER configure Postgres 17 vacuum workers using deprecated assumptions where individual parallel workers consume divided subsets of memory

Services MUST NEVER configure Postgres 17 vacuum workers using deprecated assumptions where individual parallel workers consume divided subsets of memory; parallel worker index vacuuming in high parallelism can scale aggregate allocation up to the configured cap concurrently.

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 Parallel Vacuum Maintenance Work Memory Cap Allocation critical for AI coding assistants?

Prevents catastrophic Out-Of-Memory (OOM) events and severe disk I/O thrashing during heavy write surges by governing PostgreSQL 17 vacuum worker allocations. Enforces dynamic ceilings across maintenance_work_mem, autovacuum_max_workers, and max_parallel_maintenance_workers, utilizing PG17's internal vacuum memory limits rather than unbounded global memory assignments. Eliminates multi-gigabyte memory exhaustion where concurrent index scans and parallel vacuum worker allocations cause cascading backend evictions. 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 (Global Uncapped Maintenance Work Memory Allocation Across Concurrent Parallel Vacuum Workers) 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