This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-iterseq-chi-pipeline-backpressure

Go 1.24 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware

Enforces strict coupling between Go 1.24 iter.Seq yield suspension and network socket drain events within Chi HTTP middleware chains. Eliminates unbounded heap allocation during streaming responses by propagating client TCP window stalls directly into iterator cancellation and upstream pipeline pauses.

Prohibited Anti-Pattern: Decoupled Goroutine Buffering and Ignored Yield Falsehoods in Streaming HTTP Responders

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware - Enforces strict coupling between Go 1.24 iter.Seq yield suspension and network socket drain events within Chi HTTP middleware chains. Eliminates unbounded heap allocation during streaming responses by propagating client TCP window stalls directly into iterator cancellation and upstream pipeline pauses.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-iterseq-chi-pipeline-backpressure"
---

# Go 1.24 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Decoupled Goroutine Buffering and Ignored Yield Falsehoods in Streaming HTTP Responders

## System Constraints
You are a Principal Backend Architect enforcing Go 1.24 iter.Seq and iter.Seq2 streaming backpressure propagation in Chi router middleware. You must strictly prevent unbounded in-memory buffering, goroutine leaks on severed HTTP connections, and uninspected yield return states in push iterator chains.

## Strict Guidelines
- Engineers MUST ALWAYS check the boolean return value of 'yield()' in custom iter.Seq and iter.Seq2 pipelines, immediately halting producer iteration and releasing upstream resources when yield returns false.
- Engineers MUST NOT decouple HTTP response streaming from iter.Seq execution using intermediate unbounded channels or unmonitored goroutines.
- Middleware chains MUST wrap http.ResponseWriter with an explicit Flush mechanism (http.Flusher) and verify Write errors directly inside the iteration loop.
- Pipelines MUST integrate r.Context().Done() checks into iter.Seq iteration loops to abort immediately on client disconnections.
- Code MUST NEVER swallow write errors or treat http.ErrAbortHandler as a transient condition during chunked HTTP transmission.

## Bad vs Good Implementations
### Unbounded Channel Buffering vs. Direct iter.Seq Backpressure with Yield Suspension

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decoupling the producer into an arbitrarily sized channel prevents the client's TCP receive window from slowing down data production. If the client disconnects or reads slowly, the producer continues to fetch and buffer records in memory, leading to memory exhaustion (OOM) and goroutine leaks.
```go
package transport

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

// Bad: Spawns unbounded goroutine producer that ignores client TCP backpressure and socket closure
func StreamBad(w http.ResponseWriter, r *http.Request, fetchRecords func() []Record) {
	ch := make(chan Record, 10000) // Unbounded memory expansion during slow client reads
	go func() {
		defer close(ch)
		for _, rec := range fetchRecords() {
			ch <- rec
		}
	}()

	w.Header().Set("Content-Type", "application/x-ndjson")
	enc := json.NewEncoder(w)
	for rec := range ch {
		_ = enc.Encode(rec) // Ignores write errors; upstream continues buffering
	}
}
```

#### Production Standard (Correct)
> **Standard**: By utilizing Go 1.24 iter.Seq2 natively inside the HTTP handler loop, writing directly to the network flusher couples production pace to the consumer TCP drain rate. Returning on encode failure or context cancellation triggers the yield termination protocol, immediately halting upstream generators without heap buffers.
```go
package transport

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

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

// Good: iter.Seq directly drives the write loop; false yield halts upstream extraction immediately
func StreamPipeline(w http.ResponseWriter, r *http.Request, records iter.Seq2[Record, error]) {
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/x-ndjson")
	w.Header().Set("Transfer-Encoding", "chunked")
	w.WriteHeader(http.StatusOK)

	enc := json.NewEncoder(w)
	ctx := r.Context()

	for rec, err := range records {
		if err != nil {
			return
		}
		select {
		case <-ctx.Done():
			return
		default:
		}

		if err := enc.Encode(rec); err != nil {
			// Network socket is saturated or closed; exit loop to abort upstream iter.Seq
			return
		}
		flusher.Flush()
	}
}
```

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 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware

Go 1.24 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware defines an industrial-grade behavioral standard for backend engineering. Enforces strict coupling between Go 1.24 iter.Seq yield suspension and network socket drain events within Chi HTTP middleware chains. Eliminates unbounded heap allocation during streaming responses by propagating client TCP window stalls directly into iterator cancellation and upstream pipeline pauses. 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: Decoupled Goroutine Buffering and Ignored Yield Falsehoods in Streaming HTTP Responders 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 DriftDecoupled Goroutine Buffering and Ignored Yield Falsehoods in Streaming HTTP RespondersCritical
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 check the boolean return value of 'yield()' in custom iter.Seq and iter.Seq2 pipelines, immediately halting producer iteration and releasing upstream resources when yield returns false.

Engineers MUST ALWAYS check the boolean return value of 'yield()' in custom iter.Seq and iter.Seq2 pipelines, immediately halting producer iteration and releasing upstream resources when yield 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 NOT decouple HTTP response streaming from iter.Seq execution using intermediate unbounded channels or unmonitored goroutines.

Engineers MUST NOT decouple HTTP response streaming from iter.Seq execution using intermediate unbounded channels or unmonitored goroutines.

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

Middleware chains MUST wrap http.ResponseWriter with an explicit Flush mechanism (http.Flusher) and verify Write errors directly inside the iteration loop.

Middleware chains MUST wrap http.ResponseWriter with an explicit Flush mechanism (http.Flusher) and verify Write errors directly inside the iteration loop.

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

Pipelines MUST integrate r.Context().Done() checks into iter.Seq iteration loops to abort immediately on client disconnections.

Pipelines MUST integrate r.Context().Done() checks into iter.Seq iteration loops to abort immediately on client disconnections.

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 NEVER swallow write errors or treat http.ErrAbortHandler as a transient condition during chunked HTTP transmission.

Code MUST NEVER swallow write errors or treat http.ErrAbortHandler as a transient condition during chunked HTTP transmission.

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 iter.Seq Push Iterator Backpressure Propagation in Chi Middleware critical for AI coding assistants?

Enforces strict coupling between Go 1.24 iter.Seq yield suspension and network socket drain events within Chi HTTP middleware chains. Eliminates unbounded heap allocation during streaming responses by propagating client TCP window stalls directly into iterator cancellation and upstream pipeline pauses. 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 (Decoupled Goroutine Buffering and Ignored Yield Falsehoods in Streaming HTTP Responders) 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