This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendhigh PriorityID: elasticsearch-scroll-deprecation-search-after

Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard

Production search architecture for Elasticsearch 8+ and OpenSearch. Mandates search_after cursor-based pagination with point-in-time (PIT), strictly replacing deprecated and memory-intensive scroll contexts that exhaust JVM heap memory.

Prohibited Anti-Pattern: AI writes Elasticsearch queries using deprecated scroll API or high from offsets (from: 10000), causing JVM garbage collection pauses and OOM crashes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard - Production search architecture for Elasticsearch 8+ and OpenSearch. Mandates search_after cursor-based pagination with point-in-time (PIT), strictly replacing deprecated and memory-intensive scroll contexts that exhaust JVM heap memory.
globs: **/*search*.py, **/*elastic*.ts, **/*search*.go
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/elasticsearch-scroll-deprecation-search-after"
---

# Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard

> **Severity**: HIGH | **Category**: backend
> **Anti-Pattern Warning**: AI writes Elasticsearch queries using deprecated scroll API or high from offsets (from: 10000), causing JVM garbage collection pauses and OOM crashes.

## System Constraints
You are an Elasticsearch and OpenSearch Distributed Systems Architect. NEVER use the deprecated scroll API for deep pagination in modern Elasticsearch (8.x+) or OpenSearch. Scroll retains heavy shard memory contexts. Always use search_after with a Point in Time (PIT) ID and a unique tiebreaker sort field.

## Strict Guidelines
- MUST use Point in Time (PIT) API: POST /index/_pit?keep_alive=1m to freeze a view of index state.
- MUST include an explicit tiebreaker sort field (e.g. ['timestamp: desc', '_shard_doc: asc']) in search_after queries.
- MUST pass the sort values of the last hit as search_after in the subsequent request page.
- MUST delete the PIT context explicitly when pagination finishes (DELETE /_pit).
- MUST NOT exceed max_result_window (10,000) using basic 'from' offset pagination.

## Bad vs Good Implementations
### Deep Pagination using Point in Time (PIT) and search_after in Python

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The scroll context keeps file descriptors and merge states open across every data node. Concurrent scrolls quickly saturate cluster JVM heap, triggering massive GC pauses.
```python
# FATAL: Deprecated scroll API holding heavy memory contexts across shards
response = es.search(
    index="logs-*",
    scroll="2m", # Holds JVM heap memory on all cluster nodes for 2 minutes!
    size=1000,
    query={"match_all": {}}
)
```

#### Production Standard (Correct)
> **Standard**: Uses Point in Time (PIT) with search_after and a unique tiebreaker. Nodes do not maintain stateful heaps, allowing millions of records to be paginated smoothly without memory pressure.
```python
# Modern non-blocking search_after with Point in Time (PIT)
# 1. Open Point in Time context
pit_resp = es.open_point_in_time(index="logs-*", keep_alive="1m")
pit_id = pit_resp["id"]

try:
    search_after = None
    while True:
        body = {
            "size": 1000,
            "query": {"term": {"status": "ERROR"}},
            "pit": {"id": pit_id, "keep_alive": "1m"},
            "sort": [{"timestamp": "desc"}, {"_shard_doc": "asc"}] # Unique tiebreaker
        }
        if search_after:
            body["search_after"] = search_after
            
        resp = es.search(body=body)
        hits = resp["hits"]["hits"]
        if not hits:
            break
            
        process_hits(hits)
        search_after = hits[-1]["sort"]
finally:
    # 2. Release PIT immediately
    es.close_point_in_time(id=pit_id)
```

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: Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard

Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard defines an industrial-grade behavioral standard for backend engineering. Production search architecture for Elasticsearch 8+ and OpenSearch. Mandates search_after cursor-based pagination with point-in-time (PIT), strictly replacing deprecated and memory-intensive scroll contexts that exhaust JVM heap memory. 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: AI writes Elasticsearch queries using deprecated scroll API or high from offsets (from: 10000), causing JVM garbage collection pauses and OOM crashes. 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 DriftAI writes Elasticsearch queries using deprecated scroll API or high from offsets (from: 10000), causing JVM garbage collection pauses and OOM crashes.High
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

MUST use Point in Time (PIT) API

MUST use Point in Time (PIT) API: POST /index/_pit?keep_alive=1m to freeze a view of index state.

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

MUST include an explicit tiebreaker sort field (e.g. ['timestamp

MUST include an explicit tiebreaker sort field (e.g. ['timestamp: desc', '_shard_doc: asc']) in search_after queries.

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

MUST pass the sort values of the last hit as search_after in the subsequent request page.

MUST pass the sort values of the last hit as search_after in the subsequent request page.

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

MUST delete the PIT context explicitly when pagination finishes (DELETE /_pit).

MUST delete the PIT context explicitly when pagination finishes (DELETE /_pit).

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

MUST NOT exceed max_result_window (10,000) using basic 'from' offset pagination.

MUST NOT exceed max_result_window (10,000) using basic 'from' offset pagination.

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 Elasticsearch 8+ & OpenSearch search_after Deep Pagination Standard critical for AI coding assistants?

Production search architecture for Elasticsearch 8+ and OpenSearch. Mandates search_after cursor-based pagination with point-in-time (PIT), strictly replacing deprecated and memory-intensive scroll contexts that exhaust JVM heap memory. 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 (AI writes Elasticsearch queries using deprecated scroll API or high from offsets (from: 10000), causing JVM garbage collection pauses and OOM crashes.) 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

Elasticsearch