This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-http2-stream-timeout-decoupling

Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi

Enforces granular, per-stream idle read deadlines and stream concurrency limits within Go Chi HTTP/2 services. Prevents slowloris-style stream starvation attacks and ensures that stalled individual stream payloads do not trigger global TCP connection resets across concurrent multiplexed pipelines.

Prohibited Anti-Pattern: Global TCP Read Deadlines and Unbounded Body Reads on Multiplexed HTTP/2 Connections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi - Enforces granular, per-stream idle read deadlines and stream concurrency limits within Go Chi HTTP/2 services. Prevents slowloris-style stream starvation attacks and ensures that stalled individual stream payloads do not trigger global TCP connection resets across concurrent multiplexed pipelines.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, server/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http2-stream-timeout-decoupling"
---

# Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Global TCP Read Deadlines and Unbounded Body Reads on Multiplexed HTTP/2 Connections

## System Constraints
You are a Principal Software Architect enforcing production-grade HTTP/2 transport safety in Go Chi backends. You must mandate independent per-stream idle timeouts, explicit stream buffer caps, and strict isolation between connection-level TCP deadlines and individual multiplexed HTTP/2 stream lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS configure explicit HTTP/2 server parameters (MaxConcurrentStreams, MaxReadFrameSize, IdleTimeout) via golang.org/x/net/http2.ConfigureServer on the net/http Server.
- Engineers MUST NOT rely on connection-level http.Server.ReadTimeout for request body transmission delays in HTTP/2, as triggering this deadline terminates the shared TCP connection and destroys all healthy multiplexed streams.
- Code MUST enforce per-stream body read deadlines using http.ResponseController (Go 1.20+) or a deadline-guarded io.Reader wrapper within a Chi middleware before delegating to downstream handlers.
- Services MUST bound all request body reads using io.LimitReader or http.MaxBytesReader to eliminate stream-level memory exhaustion vectors.
- Handlers NEVER consume raw r.Body directly without both an active per-read deadline and a strict byte ceiling configured via Chi middleware.

## Bad vs Good Implementations
### Per-Stream Idle Read Deadline Middleware & Safe HTTP/2 Server Config

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring http.Server.ReadTimeout terminates the entire underlying TCP connection if any single stream stalls. Conversely, omitting it leaves the handler vulnerable to slowloris attacks across multiplexed streams because io.ReadAll on r.Body can block indefinitely without per-stream idle checks.
```go
package main

import (
	"io"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
)

func RunServer() {
	r := chi.NewRouter()
	r.Post("/upload", func(w http.ResponseWriter, r *http.Request) {
		// Flaw: Unbounded read with no per-stream idle deadline.
		// A slow client sending 1 byte/sec starves worker goroutines without
		// tripping server idle checks, while setting a short global ReadTimeout
		// would abort the entire shared HTTP/2 connection for all multiplexed streams.
		data, _ := io.ReadAll(r.Body)
		w.Write([]byte("received"))
	})

	srv := &http.Server{
		Addr:        ":8443",
		Handler:     r,
		ReadTimeout: 5 * time.Second, // Kills the entire TCP conn on slow upload
	}
	srv.ListenAndServeTLS("cert.pem", "key.pem")
}
```

#### Production Standard (Correct)
> **Standard**: Decouples stream reading from the transport connection. Uses http.ResponseController to apply dynamic per-read stream deadlines alongside strict byte limits. Configures http2.Server with bounded MaxConcurrentStreams, protecting innocent multiplexed streams from connection-level aborts when a single stream throttles.
```go
package main

import (
	"context"
	"errors"
	"io"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
	"golang.org/x/net/http2"
)

type deadlineReader struct {
	r        io.Reader
	rc       *http.ResponseController
	deadline time.Duration
}

func (dr *deadlineReader) Read(p []byte) (int, error) {
	if err := dr.rc.SetReadDeadline(time.Now().Add(dr.deadline)); err != nil {
		return 0, err
	}
	return dr.r.Read(p)
}

func StreamTimeoutMiddleware(streamReadIdle time.Duration, maxBodyBytes int64) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			rc := http.NewResponseController(w)
			limited := io.LimitReader(r.Body, maxBodyBytes)
			r.Body = io.NopCloser(&deadlineReader{
				r:        limited,
				rc:       rc,
				deadline: streamReadIdle,
			})
			next.ServeHTTP(w, r)
		})
	}
}

func RunServer() {
	r := chi.NewRouter()
	r.Use(StreamTimeoutMiddleware(5*time.Second, 10<<20)) // 5s idle per read, 10MB limit

	r.Post("/upload", func(w http.ResponseWriter, r *http.Request) {
		data, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "Stream payload timeout or read error", http.StatusRequestTimeout)
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})

	srv := &http.Server{
		Addr:              ":8443",
		Handler:           r,
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       120 * time.Second,
	}

	h2Server := &http2.Server{
		MaxConcurrentStreams: 250,
		MaxReadFrameSize:     1048576,
		IdleTimeout:          60 * time.Second,
	}
	if err := http2.ConfigureServer(srv, h2Server); err != nil {
		panic(err)
	}
	_ = srv.ListenAndServeTLS("cert.pem", "key.pem")
}
```

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: Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi

Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi defines an industrial-grade behavioral standard for backend engineering. Enforces granular, per-stream idle read deadlines and stream concurrency limits within Go Chi HTTP/2 services. Prevents slowloris-style stream starvation attacks and ensures that stalled individual stream payloads do not trigger global TCP connection resets across concurrent multiplexed pipelines. 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: Global TCP Read Deadlines and Unbounded Body Reads on Multiplexed HTTP/2 Connections 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 DriftGlobal TCP Read Deadlines and Unbounded Body Reads on Multiplexed HTTP/2 ConnectionsCritical
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 configure explicit HTTP/2 server parameters (MaxConcurrentStreams, MaxReadFrameSize, IdleTimeout) via golang.org/x/net/http2.ConfigureServer on the net/http Server.

Engineers MUST ALWAYS configure explicit HTTP/2 server parameters (MaxConcurrentStreams, MaxReadFrameSize, IdleTimeout) via golang.org/x/net/http2.ConfigureServer on the net/http Server.

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 rely on connection-level http.Server.ReadTimeout for request body transmission delays in HTTP/2, as triggering this deadline terminates the shared TCP connection and destroys all healthy multiplexed streams.

Engineers MUST NOT rely on connection-level http.Server.ReadTimeout for request body transmission delays in HTTP/2, as triggering this deadline terminates the shared TCP connection and destroys all healthy multiplexed streams.

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

Code MUST enforce per-stream body read deadlines using http.ResponseController (Go 1.20+) or a deadline-guarded io.Reader wrapper within a Chi middleware before delegating to downstream handlers.

Code MUST enforce per-stream body read deadlines using http.ResponseController (Go 1.20+) or a deadline-guarded io.Reader wrapper within a Chi middleware before delegating to downstream handlers.

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 bound all request body reads using io.LimitReader or http.MaxBytesReader to eliminate stream-level memory exhaustion vectors.

Services MUST bound all request body reads using io.LimitReader or http.MaxBytesReader to eliminate stream-level memory exhaustion vectors.

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

Handlers NEVER consume raw r.Body directly without both an active per-read deadline and a strict byte ceiling configured via Chi middleware.

Handlers NEVER consume raw r.Body directly without both an active per-read deadline and a strict byte ceiling configured via Chi middleware.

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 Decoupled Per-Stream Idle Deadlines for Multiplexed HTTP/2 in Go Chi critical for AI coding assistants?

Enforces granular, per-stream idle read deadlines and stream concurrency limits within Go Chi HTTP/2 services. Prevents slowloris-style stream starvation attacks and ensures that stalled individual stream payloads do not trigger global TCP connection resets across concurrent multiplexed pipelines. 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 (Global TCP Read Deadlines and Unbounded Body Reads on Multiplexed HTTP/2 Connections) 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

Decoupled