This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-json-table-memory-quota-standard-postgres-17-json-180

PostgreSQL 17 JSON_TABLE Memory Projection and Cardinality Quota Standard

Protects PostgreSQL 17 backend worker processes from out-of-memory (OOM) terminations and severe connection churn when dynamically shredding nested, high-cardinality JSONB payloads into relational tuples. Enforces deterministic PATH scoping, strict byte-length bounds on projected TEXT/VARCHAR columns, bounded pagination limits, and explicit work_mem execution ceilings prior to invoking JSON_TABLE. Eliminates unbounded tuple expansion, unindexed Cartesian product blowouts, and OOM-killer evictions across production database pools.

Prohibited Anti-Pattern: Unbounded Nested JSON_TABLE Invocations Without Memory and Cardinality Guardrails

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 JSON_TABLE Memory Projection and Cardinality Quota Standard - Protects PostgreSQL 17 backend worker processes from out-of-memory (OOM) terminations and severe connection churn when dynamically shredding nested, high-cardinality JSONB payloads into relational tuples. Enforces deterministic PATH scoping, strict byte-length bounds on projected TEXT/VARCHAR columns, bounded pagination limits, and explicit work_mem execution ceilings prior to invoking JSON_TABLE. Eliminates unbounded tuple expansion, unindexed Cartesian product blowouts, and OOM-killer evictions across production database pools.
globs: src/db/**/*.ts, src/repositories/**/*.ts, src/services/**/*.ts, src/migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-json-table-memory-quota-standard-postgres-17-json-180"
---

# PostgreSQL 17 JSON_TABLE Memory Projection and Cardinality Quota Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Nested JSON_TABLE Invocations Without Memory and Cardinality Guardrails

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 JSON_TABLE standards. You must ensure all queries utilizing the ANSI SQL standard JSON_TABLE function in PostgreSQL 17 enforce explicit projection bounds, strict column sizing, memory quota limits, and nested path constraints to prevent backend worker memory exhaustion.

## Strict Guidelines
- Engineers MUST ALWAYS enforce explicit maximum column lengths (e.g., VARCHAR(255), NUMERIC(12, 2)) instead of unbounded TEXT or unbounded NUMERIC types inside JSON_TABLE COLUMNS clauses to prevent excessive projection buffer allocation.
- Engineers MUST ALWAYS bound JSON_TABLE input arrays with an outer LIMIT clause or strict JSONPath slicing (e.g., '$[0 to 999]') to prevent memory runaway when ingesting external arbitrary payloads.
- Engineers MUST NOT shred multi-level nested JSON arrays within a single unconstrained JSON_TABLE expression using Cartesian NESTED PATH clauses without enforcing strict parent-child cardinality limits.
- Engineers MUST ALWAYS configure an explicit transaction-level work_mem quota or use statement_timeout before invoking complex JSON_TABLE projections across large batch jobs.
- Services MUST validate payload byte size in application code prior to handing multi-megabyte JSONB buffers directly to relational JSON_TABLE transformations in online transactional processing (OLTP) connections.
- Queries MUST ALWAYS specify explicit ERROR ON ERROR or DEFAULT ... ON EMPTY clauses on JSON_TABLE column mappings to eliminate hidden memory-retaining evaluation errors during bulk projection.

## Bad vs Good Implementations
### Postgres 17 JSON_TABLE Dynamic Ingestion Query Builder

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This query accepts an arbitrary JSON payload and expands nested items without pagination or slice guards ($[0 to 999]). Projecting TEXT and returning entire sub-objects as TEXT PATH '$' inside a nested join allocates uncontrolled backend process memory, easily triggering the OS OOM killer or exhausting work_mem.
```typescript
import { sql } from 'kysely';
import { db } from '../database';

export async function ingestNestedBatch(untrustedJson: string) {
  // Anti-pattern: Unbounded TEXT projection, nested cartesian expansion without path slicing,
  // and lack of work_mem or statement-level timeout guardrails.
  return await db.executeQuery(
    sql`
      SELECT jt.tenant_id, jt.event_type, jt.item_id, jt.item_payload
      FROM JSON_TABLE(
        ${untrustedJson}::jsonb, '$[*]'
        COLUMNS (
          tenant_id TEXT PATH '$.tenant_id',
          event_type TEXT PATH '$.event_type',
          NESTED PATH '$.items[*]'
          COLUMNS (
            item_id TEXT PATH '$.id',
            item_payload TEXT PATH '$'
          )
        )
      ) AS jt;
    `
  );
}
```

#### Production Standard (Correct)
> **Standard**: Enforces an application-level byte limit (2MB), confines database execution to isolated local work_mem and statement_timeout values, restricts root array elements to 500 and nested items to 100 via JSONPath slices, uses bounded VARCHAR lengths, and provides explicit error handling policies.
```typescript
import { sql } from 'kysely';
import { db } from '../database';

const MAX_BATCH_JSON_BYTES = 2 * 1024 * 1024; // 2MB hard guardrail

export async function ingestNestedBatch(untrustedJson: string) {
  if (Buffer.byteLength(untrustedJson, 'utf8') > MAX_BATCH_JSON_BYTES) {
    throw new Error('Payload exceeds maximum allowable JSON ingest quota of 2MB');
  }

  // Production Invariant: Restrict work_mem, apply path slicing ($[0 to 499]),
  // project explicit column lengths, and handle errors deterministically.
  return await db.transaction().execute(async (trx) => {
    await trx.executeQuery(sql`SET LOCAL work_mem = '16MB';`);
    await trx.executeQuery(sql`SET LOCAL statement_timeout = '3000ms';`);

    return await trx.executeQuery(
      sql`
        SELECT jt.tenant_id, jt.event_type, jt.item_id
        FROM JSON_TABLE(
          ${untrustedJson}::jsonb, '$[0 to 499]'
          COLUMNS (
            tenant_id VARCHAR(64) PATH '$.tenant_id' ERROR ON ERROR,
            event_type VARCHAR(64) PATH '$.event_type' DEFAULT 'UNKNOWN' ON EMPTY,
            NESTED PATH '$.items[0 to 99]'
            COLUMNS (
              item_id VARCHAR(128) PATH '$.id' ERROR ON ERROR
            )
          )
        ) AS jt;
      `
    );
  });
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 JSON_TABLE Memory Projection and Cardinality Quota Standard

PostgreSQL 17 JSON_TABLE Memory Projection and Cardinality Quota Standard defines an industrial-grade behavioral standard for backend engineering. Protects PostgreSQL 17 backend worker processes from out-of-memory (OOM) terminations and severe connection churn when dynamically shredding nested, high-cardinality JSONB payloads into relational tuples. Enforces deterministic PATH scoping, strict byte-length bounds on projected TEXT/VARCHAR columns, bounded pagination limits, and explicit work_mem execution ceilings prior to invoking JSON_TABLE. Eliminates unbounded tuple expansion, unindexed Cartesian product blowouts, and OOM-killer evictions across production database pools. 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 Nested JSON_TABLE Invocations Without Memory and Cardinality Guardrails 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 Nested JSON_TABLE Invocations Without Memory and Cardinality GuardrailsCritical
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 explicit maximum column lengths (e.g., VARCHAR(255), NUMERIC(12, 2)) instead of unbounded TEXT or unbounded NUMERIC types inside JSON_TABLE COLUMNS clauses to prevent excessive projection buffer allocation.

Engineers MUST ALWAYS enforce explicit maximum column lengths (e.g., VARCHAR(255), NUMERIC(12, 2)) instead of unbounded TEXT or unbounded NUMERIC types inside JSON_TABLE COLUMNS clauses to prevent excessive projection buffer allocation.

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 JSON_TABLE input arrays with an outer LIMIT clause or strict JSONPath slicing (e.g., '$[0 to 999]') to prevent memory runaway when ingesting external arbitrary payloads.

Engineers MUST ALWAYS bound JSON_TABLE input arrays with an outer LIMIT clause or strict JSONPath slicing (e.g., '$[0 to 999]') to prevent memory runaway when ingesting external arbitrary payloads.

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 shred multi-level nested JSON arrays within a single unconstrained JSON_TABLE expression using Cartesian NESTED PATH clauses without enforcing strict parent-child cardinality limits.

Engineers MUST NOT shred multi-level nested JSON arrays within a single unconstrained JSON_TABLE expression using Cartesian NESTED PATH clauses without enforcing strict parent-child cardinality limits.

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 ALWAYS configure an explicit transaction-level work_mem quota or use statement_timeout before invoking complex JSON_TABLE projections across large batch jobs.

Engineers MUST ALWAYS configure an explicit transaction-level work_mem quota or use statement_timeout before invoking complex JSON_TABLE projections across large batch jobs.

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 validate payload byte size in application code prior to handing multi-megabyte JSONB buffers directly to relational JSON_TABLE transformations in online transactional processing (OLTP) connections.

Services MUST validate payload byte size in application code prior to handing multi-megabyte JSONB buffers directly to relational JSON_TABLE transformations in online transactional processing (OLTP) connections.

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

Queries MUST ALWAYS specify explicit ERROR ON ERROR or DEFAULT ... ON EMPTY clauses on JSON_TABLE column mappings to eliminate hidden memory-retaining evaluation errors during bulk projection.

Queries MUST ALWAYS specify explicit ERROR ON ERROR or DEFAULT ... ON EMPTY clauses on JSON_TABLE column mappings to eliminate hidden memory-retaining evaluation errors during bulk projection.

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 JSON_TABLE Memory Projection and Cardinality Quota Standard critical for AI coding assistants?

Protects PostgreSQL 17 backend worker processes from out-of-memory (OOM) terminations and severe connection churn when dynamically shredding nested, high-cardinality JSONB payloads into relational tuples. Enforces deterministic PATH scoping, strict byte-length bounds on projected TEXT/VARCHAR columns, bounded pagination limits, and explicit work_mem execution ceilings prior to invoking JSON_TABLE. Eliminates unbounded tuple expansion, unindexed Cartesian product blowouts, and OOM-killer evictions across production database pools. 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 Nested JSON_TABLE Invocations Without Memory and Cardinality Guardrails) 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