This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-1-24-range-func-http-stream-backpressure

Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant

Enforces deterministic heap memory limits and cooperative backpressure during multi-gigabyte NDJSON HTTP chunked response streams via Go 1.24 standard library iterators (iter.Seq / iter.Seq2). Mandates zero-allocation buffer reuse, immediate flush verification, and fail-fast context propagation to prevent unbounded memory growth and goroutine leaks on slow or disconnected clients.

Prohibited Anti-Pattern: Buffering Unbounded Iterator Batches or Ignoring Flusher Deadlock & Client Disconnects in HTTP Range Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant - Enforces deterministic heap memory limits and cooperative backpressure during multi-gigabyte NDJSON HTTP chunked response streams via Go 1.24 standard library iterators (iter.Seq / iter.Seq2). Mandates zero-allocation buffer reuse, immediate flush verification, and fail-fast context propagation to prevent unbounded memory growth and goroutine leaks on slow or disconnected clients.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-1-24-range-func-http-stream-backpressure"
---

# Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Buffering Unbounded Iterator Batches or Ignoring Flusher Deadlock & Client Disconnects in HTTP Range Loops

## System Constraints
You are a Principal Engineer enforcing the Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant. Mandate zero heap bloat, explicit cooperative backpressure, strict context propagation, and guaranteed iterator termination across all streaming HTTP endpoints.

## Strict Guidelines
- Engineers MUST ALWAYS implement multi-gigabyte streaming sources using Go 1.24 iterators (`iter.Seq[T]` or `iter.Seq2[T, error]`) that strictly evaluate consumer yields to halt processing instantly when the yield callback returns false.
- Engineers MUST ALWAYS verify HTTP chunk streaming capability via `http.ResponseController` or type-asserting `http.Flusher`, returning an HTTP 500 or failing fast before writing headers if the underlying connection cannot flush.
- Engineers MUST ALWAYS set appropriate response headers (`Transfer-Encoding: chunked`, `Content-Type: application/x-ndjson`, and `X-Content-Type-Options: nosniff`) prior to flushing the first record.
- Engineers MUST NOT aggregate, batch, or collect iterator elements into unbounded slices or channel-based buffers prior to streaming out to `http.ResponseWriter`.
- Code MUST reuse serialization buffers (such as `sync.Pool` allocated buffers or `json.NewEncoder(w)` directly with flush cycles) to enforce an O(1) heap allocation ceiling regardless of response payload size.
- Services MUST check `r.Context().Done()` inside the range-over-func iterator yield and break loop execution immediately if the client disconnects, ensuring no orphan database cursors or producer goroutines remain active.
- Components NEVER continue iteration or invoke `Flusher.Flush()` if `w.Write()` yields an error or if the client connection has closed.

## Bad vs Good Implementations
### Go 1.24 Range-Over-Func Streaming vs. Unbounded Slice Buffering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Aggregating the entire iterator into an in-memory slice completely defeats streaming, exhausts heap memory on large payloads, causes high GC latency, and fails to handle mid-stream client disconnects.
```go
package api

import (
	"encoding/json"
	"net/http"
)

type Record struct {
	ID   string `json:"id"`
	Data []byte `json:"data"`
}

// BAD: Loads entire cursor dataset into memory and slices, ignoring backpressure and OOM risks.
func StreamHandler(w http.ResponseWriter, r *http.Request) {
	records := make([]Record, 0) // Unbounded heap growth on multi-gigabyte streams
	for rec := range queryRecordsIterator(r.Context()) {
		records = append(records, rec)
	}

	w.Header().Set("Content-Type", "application/json")
	// Marshals entire dataset at once, crashing container with OOM error
	_ = json.NewEncoder(w).Encode(records)
}

func queryRecordsIterator(ctx context.Context) func(func(Record) bool) {
	return func(yield func(Record) bool) {
		// dummy implementation
	}
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Go 1.24 `iter.Seq2` with immediate NDJSON encoding and `http.ResponseController.Flush()`. If the client disconnects or write fails, the loop breaks instantly, terminating upstream cursor operations without allocating unbounded heap.
```go
package api

import (
	"context"
	"encoding/json"
	"errors"
	"iter"
	"net/http"
)

type Record struct {
	ID   string `json:"id"`
	Data []byte `json:"data"`
}

// GOOD: Enforces Go 1.24 iter.Seq2, O(1) heap, ResponseController flushes, and client cancellation.
func StreamHandler(w http.ResponseWriter, r *http.Request) {
	rc := http.NewResponseController(w)

	w.Header().Set("Content-Type", "application/x-ndjson")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.WriteHeader(http.StatusOK)

	enc := json.NewEncoder(w)

	for rec, err := range queryRecordsSeq(r.Context()) {
		if err != nil {
			// Logging error; cannot rewrite status header as headers were flushed
			return
		}

		if err := enc.Encode(rec); err != nil {
			return // Break stream on network write failure
		}

		if err := rc.Flush(); err != nil {
			return // Break stream on client disconnect / buffer flush failure
		}
	}
}

func queryRecordsSeq(ctx context.Context) iter.Seq2[Record, error] {
	return func(yield func(Record, error) bool) {
		// In production, backed by a database cursor or reader
		for {
			select {
			case <-ctx.Done():
				yield(Record{}, ctx.Err())
				return
			default:
				rec, hasMore, err := fetchNextRecord()
				if err != nil {
					yield(Record{}, err)
					return
				}
				if !hasMore || !yield(rec, nil) {
					return // Yield returned false: consumer broke out or failed
				}
			}
		}
	}
}

func fetchNextRecord() (Record, bool, error) {
	return Record{}, false, nil
}
```

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: Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant

Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic heap memory limits and cooperative backpressure during multi-gigabyte NDJSON HTTP chunked response streams via Go 1.24 standard library iterators (iter.Seq / iter.Seq2). Mandates zero-allocation buffer reuse, immediate flush verification, and fail-fast context propagation to prevent unbounded memory growth and goroutine leaks on slow or disconnected clients. 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: Buffering Unbounded Iterator Batches or Ignoring Flusher Deadlock & Client Disconnects in HTTP Range Loops 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 DriftBuffering Unbounded Iterator Batches or Ignoring Flusher Deadlock & Client Disconnects in HTTP Range LoopsCritical
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 implement multi-gigabyte streaming sources using Go 1.24 iterators (`iter.Seq[T]` or `iter.Seq2[T, error]`) that strictly evaluate consumer yields to halt processing instantly when the yield callback returns false.

Engineers MUST ALWAYS implement multi-gigabyte streaming sources using Go 1.24 iterators (`iter.Seq[T]` or `iter.Seq2[T, error]`) that strictly evaluate consumer yields to halt processing instantly when the yield callback returns false.

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 verify HTTP chunk streaming capability via `http.ResponseController` or type-asserting `http.Flusher`, returning an HTTP 500 or failing fast before writing headers if the underlying connection cannot flush.

Engineers MUST ALWAYS verify HTTP chunk streaming capability via `http.ResponseController` or type-asserting `http.Flusher`, returning an HTTP 500 or failing fast before writing headers if the underlying connection cannot flush.

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 set appropriate response headers (`Transfer-Encoding

Engineers MUST ALWAYS set appropriate response headers (`Transfer-Encoding: chunked`, `Content-Type: application/x-ndjson`, and `X-Content-Type-Options: nosniff`) prior to flushing the first record.

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 NOT aggregate, batch, or collect iterator elements into unbounded slices or channel-based buffers prior to streaming out to `http.ResponseWriter`.

Engineers MUST NOT aggregate, batch, or collect iterator elements into unbounded slices or channel-based buffers prior to streaming out to `http.ResponseWriter`.

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

Code MUST reuse serialization buffers (such as `sync.Pool` allocated buffers or `json.NewEncoder(w)` directly with flush cycles) to enforce an O(1) heap allocation ceiling regardless of response payload size.

Code MUST reuse serialization buffers (such as `sync.Pool` allocated buffers or `json.NewEncoder(w)` directly with flush cycles) to enforce an O(1) heap allocation ceiling regardless of response payload size.

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

Services MUST check `r.Context().Done()` inside the range-over-func iterator yield and break loop execution immediately if the client disconnects, ensuring no orphan database cursors or producer goroutines remain active.

Services MUST check `r.Context().Done()` inside the range-over-func iterator yield and break loop execution immediately if the client disconnects, ensuring no orphan database cursors or producer goroutines remain active.

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.
7

Components NEVER continue iteration or invoke `Flusher.Flush()` if `w.Write()` yields an error or if the client connection has closed.

Components NEVER continue iteration or invoke `Flusher.Flush()` if `w.Write()` yields an error or if the client connection has closed.

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 Go 1.24 Range-Over-Func HTTP Chunked Streaming Invariant critical for AI coding assistants?

Enforces deterministic heap memory limits and cooperative backpressure during multi-gigabyte NDJSON HTTP chunked response streams via Go 1.24 standard library iterators (iter.Seq / iter.Seq2). Mandates zero-allocation buffer reuse, immediate flush verification, and fail-fast context propagation to prevent unbounded memory growth and goroutine leaks on slow or disconnected clients. 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 (Buffering Unbounded Iterator Batches or Ignoring Flusher Deadlock & Client Disconnects in HTTP Range Loops) 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

Go