This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: pg17-json-table-workmem-ceiling-invariant

PostgreSQL 17 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant

Enforces deterministic memory bounds and streaming execution semantics when evaluating PostgreSQL 17 native SQL/JSON operators (JSON_TABLE, JSON_QUERY, JSON_VALUE) over high-cardinality nested structures. Prevents backend worker Out-Of-Memory (OOM) panics by mandating transaction-local work_mem ceilings, explicit data type projections with byte-bounded VARCHAR limits, and streaming chunk-based batching.

Prohibited Anti-Pattern: Unbounded JSON_TABLE materialization inside default sessions triggering backend worker OOM kills

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant - Enforces deterministic memory bounds and streaming execution semantics when evaluating PostgreSQL 17 native SQL/JSON operators (JSON_TABLE, JSON_QUERY, JSON_VALUE) over high-cardinality nested structures. Prevents backend worker Out-Of-Memory (OOM) panics by mandating transaction-local work_mem ceilings, explicit data type projections with byte-bounded VARCHAR limits, and streaming chunk-based batching.
globs: src/**/*.ts, src/**/*.sql, src/**/*.service.ts, src/**/*.repository.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-json-table-workmem-ceiling-invariant"
---

# PostgreSQL 17 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded JSON_TABLE materialization inside default sessions triggering backend worker OOM kills

## System Constraints
You are a Principal Database Architect and Systems Engineer enforcing strict memory invariants for PostgreSQL 17 SQL/JSON features. Mandate strict work_mem ceilings (SET LOCAL work_mem), projection field bounds, and error-handling clauses for JSON_TABLE and SQL/JSON path evaluation to prevent unbounded memory allocation and silent session evictions under high concurrent load.

## Strict Guidelines
- Engineers MUST ALWAYS execute SQL/JSON queries utilizing JSON_TABLE within explicit transactions configured with a transaction-local memory ceiling via `SET LOCAL work_mem = '32MB'` (or an application-specific bounded ceiling).
- Engineers MUST NOT unpack nested JSON arrays into unbounded `TEXT` columns in `JSON_TABLE` column specifications; explicit length constraints (e.g., `VARCHAR(255)`, `NUMERIC(12,2)`) MUST be enforced on every projected field to limit tuple slot sizing.
- Engineers MUST ALWAYS include explicit `ON ERROR` and `ON EMPTY` clauses (e.g., `ERROR ON ERROR` or `EMPTY ON ERROR`) to prevent silent node materialization failures or runaway fallbacks.
- Services MUST process bulk enterprise payloads by segmenting documents into bounded batch sizes (< 5,000 entities) at the application layer before calling `JSON_TABLE`, rather than streaming single multi-gigabyte JSON documents into PostgreSQL backend memory.
- Queries MUST NOT use multiple unconstrained `NESTED PATH` clauses inside a single `JSON_TABLE` projection without benchmarking the cross-product materialization impact against the backend memory limit.

## Bad vs Good Implementations
### Unbounded JSON_TABLE execution vs. Transaction-bounded streaming JSON_TABLE

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing JSON_TABLE directly against a connection without setting a local work_mem ceiling allows queries to allocate memory up to the global server limits or exceed OS swap under concurrent execution. Using unbounded TEXT projections prevents PostgreSQL executor cost models from predicting tuple descriptor widths accurately.
```typescript
import { Pool } from 'pg';

export async function ingestEnterpriseEvents(pool: Pool, rawPayloadJson: string): Promise<void> {
  // ANTI-PATTERN: Unbounded work_mem, unbounded TEXT projections, and unbounded nested materialization
  // Running this against large nested payloads in multi-tenant contexts exhausts backend worker memory and crashes the connection
  await pool.query(`
    INSERT INTO audit_log (event_id, tenant_id, payload_summary, ingested_at)
    SELECT j.event_id, j.tenant_id, j.raw_detail, NOW()
    FROM JSON_TABLE(
      $1::jsonb, '$[*]'
      COLUMNS (
        event_id TEXT PATH '$.id',
        tenant_id TEXT PATH '$.tenantId',
        raw_detail TEXT PATH '$.detail'
      )
    ) AS j;
  `, [rawPayloadJson]);
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the ingestion in a client transaction with a local 32MB work_mem ceiling and strict statement timeout. The JSON_TABLE definition strictly types outputs (VARCHAR(64), UUID, VARCHAR(1024)) and defines deterministic ERROR ON ERROR handling, allowing the query planner to correctly allocate executor memory slots without risk of process memory exhaustion.
```typescript
import { Pool, PoolClient } from 'pg';

export async function ingestEnterpriseEvents(pool: Pool, rawPayloadJson: string): Promise<void> {
  const client: PoolClient = await pool.connect();
  try {
    await client.query('BEGIN');
    // INVARIANT: Cap backend executor memory strictly for this transaction scope
    await client.query("SET LOCAL work_mem = '32MB'");
    // INVARIANT: Impose strict query timeout to mitigate runaway nested cross-product generation
    await client.query("SET LOCAL statement_timeout = '15s'");

    await client.query(`
      INSERT INTO audit_log (event_id, tenant_id, payload_summary, ingested_at)
      SELECT j.event_id, j.tenant_id, j.payload_summary, CLOCK_TIMESTAMP()
      FROM JSON_TABLE(
        $1::jsonb, '$[*]'
        ERROR ON ERROR
        COLUMNS (
          event_id VARCHAR(64) PATH '$.id' ERROR ON ERROR,
          tenant_id UUID PATH '$.tenantId' ERROR ON ERROR,
          payload_summary VARCHAR(1024) PATH '$.detail.summary' EMPTY ON ERROR
        )
      ) AS j;
    `, [rawPayloadJson]);

    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant

PostgreSQL 17 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory bounds and streaming execution semantics when evaluating PostgreSQL 17 native SQL/JSON operators (JSON_TABLE, JSON_QUERY, JSON_VALUE) over high-cardinality nested structures. Prevents backend worker Out-Of-Memory (OOM) panics by mandating transaction-local work_mem ceilings, explicit data type projections with byte-bounded VARCHAR limits, and streaming chunk-based batching. 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 JSON_TABLE materialization inside default sessions triggering backend worker OOM kills 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 JSON_TABLE materialization inside default sessions triggering backend worker OOM killsCritical
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 execute SQL/JSON queries utilizing JSON_TABLE within explicit transactions configured with a transaction-local memory ceiling via `SET LOCAL work_mem = '32MB'` (or an application-specific bounded ceiling).

Engineers MUST ALWAYS execute SQL/JSON queries utilizing JSON_TABLE within explicit transactions configured with a transaction-local memory ceiling via `SET LOCAL work_mem = '32MB'` (or an application-specific bounded ceiling).

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 unpack nested JSON arrays into unbounded `TEXT` columns in `JSON_TABLE` column specifications

Engineers MUST NOT unpack nested JSON arrays into unbounded `TEXT` columns in `JSON_TABLE` column specifications; explicit length constraints (e.g., `VARCHAR(255)`, `NUMERIC(12,2)`) MUST be enforced on every projected field to limit tuple slot sizing.

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 ALWAYS include explicit `ON ERROR` and `ON EMPTY` clauses (e.g., `ERROR ON ERROR` or `EMPTY ON ERROR`) to prevent silent node materialization failures or runaway fallbacks.

Engineers MUST ALWAYS include explicit `ON ERROR` and `ON EMPTY` clauses (e.g., `ERROR ON ERROR` or `EMPTY ON ERROR`) to prevent silent node materialization failures or runaway fallbacks.

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

Services MUST process bulk enterprise payloads by segmenting documents into bounded batch sizes (< 5,000 entities) at the application layer before calling `JSON_TABLE`, rather than streaming single multi-gigabyte JSON documents into PostgreSQL backend memory.

Services MUST process bulk enterprise payloads by segmenting documents into bounded batch sizes (< 5,000 entities) at the application layer before calling `JSON_TABLE`, rather than streaming single multi-gigabyte JSON documents into PostgreSQL backend memory.

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 NOT use multiple unconstrained `NESTED PATH` clauses inside a single `JSON_TABLE` projection without benchmarking the cross-product materialization impact against the backend memory limit.

Queries MUST NOT use multiple unconstrained `NESTED PATH` clauses inside a single `JSON_TABLE` projection without benchmarking the cross-product materialization impact against the backend memory limit.

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 SQL/JSON JSON_TABLE WorkMem Ceiling Invariant critical for AI coding assistants?

Enforces deterministic memory bounds and streaming execution semantics when evaluating PostgreSQL 17 native SQL/JSON operators (JSON_TABLE, JSON_QUERY, JSON_VALUE) over high-cardinality nested structures. Prevents backend worker Out-Of-Memory (OOM) panics by mandating transaction-local work_mem ceilings, explicit data type projections with byte-bounded VARCHAR limits, and streaming chunk-based batching. 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 JSON_TABLE materialization inside default sessions triggering backend worker OOM kills) 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