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

PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance

Enforces deterministic per-transaction memory allocation bounds for Postgres 17 parallel workers during partition-wise joins and aggregations. Eliminates kernel OOM-killer invocations by dynamically calculating work_mem, hash_mem_multiplier, and max_parallel_workers_per_gather against cgroup memory ceilings before executing analytical fanout queries.

Prohibited Anti-Pattern: Global work_mem Multiplied Across Parallel Partition Workers Causing Process Termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance - Enforces deterministic per-transaction memory allocation bounds for Postgres 17 parallel workers during partition-wise joins and aggregations. Eliminates kernel OOM-killer invocations by dynamically calculating work_mem, hash_mem_multiplier, and max_parallel_workers_per_gather against cgroup memory ceilings before executing analytical fanout queries.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/services/**/*.ts, src/analytics/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-partition-parallel-aggregation-memory-boundary"
---

# PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global work_mem Multiplied Across Parallel Partition Workers Causing Process Termination

## System Constraints
You are a Principal Database Reliability Engineer enforcing Postgres 17 partition-aware parallel aggregation boundaries. Mandate strict transaction-scoped memory budgeting for all analytical parallel queries involving partitioned tables.

## Strict Guidelines
- Engineers MUST ALWAYS calculate and set transaction-local memory parameters using `SET LOCAL work_mem` prior to executing queries that enable `enable_partitionwise_join` or `enable_partitionwise_aggregate`.
- Engineers MUST NOT rely on static, cluster-wide `work_mem` configurations for partitioned analytical queries, as memory scales by (workers + 1) * active_partitions * hash_nodes * hash_mem_multiplier.
- Services MUST bound the maximum concurrent workers via `SET LOCAL max_parallel_workers_per_gather` to ensure deterministic worst-case memory ceiling calculations.
- Code SHOULD verify query execution plans using `EXPLAIN (ANALYZE, MEMORY, BUFFERS)` in staging environments to validate that worker memory usage does not exceed container cgroup thresholds.
- Components NEVER execute partition-wise aggregations across unbounded dynamic partition sets without specifying explicit date or key pruning in the WHERE clause.

## Bad vs Good Implementations
### Unbounded Partition-Aware Parallel Aggregation vs. Dynamically Governed Memory Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Enabling partition-wise operations without constraining workers or transaction-local work_mem creates a multiplicative memory demand. If Postgres executes across 12 partitions with 4 parallel workers, memory consumption can spike to 48x the standard work_mem per aggregation node, triggering OOM killer termination on the worker backend.
```typescript
import { PoolClient } from 'pg';

export async function runYearlyTenantAggregation(client: PoolClient, tenantId: string, year: number) {
  // ANTI-PATTERN: Activating partition-wise features with unconstrained parallel workers
  // and static/default work_mem. In Postgres 17, partition-wise aggregation duplicates
  // hash buckets across each partition per worker node, causing aggregate memory
  // consumption to balloon: workers * partitions * work_mem * hash_mem_multiplier.
  await client.query('BEGIN');
  await client.query('SET enable_partitionwise_join = on');
  await client.query('SET enable_partitionwise_aggregate = on');
  
  const result = await client.query(`
    SELECT 
      DATE_TRUNC('month', created_at) AS metric_month,
      COUNT(DISTINCT user_id) AS active_users,
      SUM(amount_cents) AS total_revenue
    FROM partitioned_events pe
    JOIN partitioned_transactions pt 
      ON pe.transaction_id = pt.id AND pe.partition_key = pt.partition_key
    WHERE pe.tenant_id = $1 AND pe.year = $2
    GROUP BY 1;
  `, [tenantId, year]);
  
  await client.query('COMMIT');
  return result.rows;
}
```

#### Production Standard (Correct)
> **Standard**: Computes a deterministic `work_mem` cap derived from available container memory, estimated worker count, and active partitions. Uses `SET LOCAL` within a transaction to contain boundaries to the specific analytical query, setting `hash_mem_multiplier = 1.0` and controlling `max_parallel_workers_per_gather` to guarantee safety against Linux OOM killer invocation.
```typescript
import { PoolClient } from 'pg';

interface MemoryBoundaryOptions {
  maxCgroupMemoryMb: number;
  activePartitions: number;
  maxWorkers?: number;
  safetyFactor?: number;
}

export async function runYearlyTenantAggregation(
  client: PoolClient,
  tenantId: string,
  year: number,
  options: MemoryBoundaryOptions = { maxCgroupMemoryMb: 2048, activePartitions: 12 }
) {
  const workers = options.maxWorkers ?? 4;
  const safetyFactor = options.safetyFactor ?? 0.65; // Retain 35% headroom for shared_buffers & OS
  const maxUsableMemoryMb = options.maxCgroupMemoryMb * safetyFactor;
  
  // Worst case: (workers + 1) * activePartitions * hash_mem_multiplier (default 2.0 for HashAggregate)
  const estimatedSlots = (workers + 1) * options.activePartitions * 2;
  const boundedWorkMemMb = Math.max(4, Math.floor(maxUsableMemoryMb / estimatedSlots));

  try {
    await client.query('BEGIN TRANSACTION READ ONLY');

    // Scope memory and parallelism strictly to this transaction
    await client.query(`SET LOCAL work_mem = '${boundedWorkMemMb}MB'`);
    await client.query(`SET LOCAL max_parallel_workers_per_gather = ${workers}`);
    await client.query('SET LOCAL hash_mem_multiplier = 1.0');
    await client.query('SET LOCAL enable_partitionwise_join = on');
    await client.query('SET LOCAL enable_partitionwise_aggregate = on');

    const result = await client.query(`
      SELECT 
        DATE_TRUNC('month', created_at) AS metric_month,
        COUNT(DISTINCT user_id) AS active_users,
        SUM(amount_cents) AS total_revenue
      FROM partitioned_events pe
      JOIN partitioned_transactions pt 
        ON pe.transaction_id = pt.id AND pe.partition_key = pt.partition_key
      WHERE pe.tenant_id = $1 AND pe.year = $2
      GROUP BY 1;
    `, [tenantId, year]);

    await client.query('COMMIT');
    return result.rows;
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  }
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance

PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic per-transaction memory allocation bounds for Postgres 17 parallel workers during partition-wise joins and aggregations. Eliminates kernel OOM-killer invocations by dynamically calculating work_mem, hash_mem_multiplier, and max_parallel_workers_per_gather against cgroup memory ceilings before executing analytical fanout queries. 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 work_mem Multiplied Across Parallel Partition Workers Causing Process Termination 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 work_mem Multiplied Across Parallel Partition Workers Causing Process TerminationCritical
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 calculate and set transaction-local memory parameters using `SET LOCAL work_mem` prior to executing queries that enable `enable_partitionwise_join` or `enable_partitionwise_aggregate`.

Engineers MUST ALWAYS calculate and set transaction-local memory parameters using `SET LOCAL work_mem` prior to executing queries that enable `enable_partitionwise_join` or `enable_partitionwise_aggregate`.

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 rely on static, cluster-wide `work_mem` configurations for partitioned analytical queries, as memory scales by (workers + 1) * active_partitions * hash_nodes * hash_mem_multiplier.

Engineers MUST NOT rely on static, cluster-wide `work_mem` configurations for partitioned analytical queries, as memory scales by (workers + 1) * active_partitions * hash_nodes * hash_mem_multiplier.

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

Services MUST bound the maximum concurrent workers via `SET LOCAL max_parallel_workers_per_gather` to ensure deterministic worst-case memory ceiling calculations.

Services MUST bound the maximum concurrent workers via `SET LOCAL max_parallel_workers_per_gather` to ensure deterministic worst-case memory ceiling calculations.

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 SHOULD verify query execution plans using `EXPLAIN (ANALYZE, MEMORY, BUFFERS)` in staging environments to validate that worker memory usage does not exceed container cgroup thresholds.

Code SHOULD verify query execution plans using `EXPLAIN (ANALYZE, MEMORY, BUFFERS)` in staging environments to validate that worker memory usage does not exceed container cgroup 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

Components NEVER execute partition-wise aggregations across unbounded dynamic partition sets without specifying explicit date or key pruning in the WHERE clause.

Components NEVER execute partition-wise aggregations across unbounded dynamic partition sets without specifying explicit date or key pruning in the WHERE clause.

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 PostgreSQL 17 Partition-Aware Parallel Aggregation & Join Memory Governance critical for AI coding assistants?

Enforces deterministic per-transaction memory allocation bounds for Postgres 17 parallel workers during partition-wise joins and aggregations. Eliminates kernel OOM-killer invocations by dynamically calculating work_mem, hash_mem_multiplier, and max_parallel_workers_per_gather against cgroup memory ceilings before executing analytical fanout queries. 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 work_mem Multiplied Across Parallel Partition Workers Causing Process Termination) 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

PostgreSQL