This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-sub-deadline-budgeting-guardrail

Go Chi v5 Context Sub-Deadline Budget Allocation Guardrail

Enforces deterministic context deadline budgeting and sub-deadline allocation across sequential and parallel outbound operations within Go Chi v5 HTTP handlers. Prevents cascade connection exhaustion and thread starvation caused by static timeouts that ignore remaining request lifetime budgets or lack defensive deadline propagation.

Prohibited Anti-Pattern: Inheriting unbounded Chi request contexts or applying static outbound timeouts exceeding parent context deadlines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 Context Sub-Deadline Budget Allocation Guardrail - Enforces deterministic context deadline budgeting and sub-deadline allocation across sequential and parallel outbound operations within Go Chi v5 HTTP handlers. Prevents cascade connection exhaustion and thread starvation caused by static timeouts that ignore remaining request lifetime budgets or lack defensive deadline propagation.
globs: **/*.go, internal/**/*.go, pkg/**/*.go, cmd/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-sub-deadline-budgeting-guardrail"
---

# Go Chi v5 Context Sub-Deadline Budget Allocation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Inheriting unbounded Chi request contexts or applying static outbound timeouts exceeding parent context deadlines

## System Constraints
You are a Principal Backend Architect enforcing strict context deadline budgeting in Go Chi v5 microservices. You must ensure that every outbound call (RPC, database, cache, third-party HTTP) derives a sub-context bounded by fractional allocations of the remaining parent deadline. Never allow static, hardcoded timeouts that disregard context.Deadline() or fail to invoke cancel functions, risking goroutine and socket leaks.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the incoming request context via ctx.Deadline() before initiating downstream network operations.
- Engineers MUST calculate remaining deadline budget (time.Until(deadline)) and allocate explicit fractional quotas (e.g., 40% DB, 40% downstream HTTP, 20% slack/serialization) rather than applying uncoordinated static timeouts.
- Engineers MUST NOT create outbound contexts using context.WithTimeout with a duration greater than the parent context's remaining duration without clamping to the parent deadline.
- Code SHOULD abort execution immediately and return http.StatusGatewayTimeout (504) if remaining context budget falls below a defined operational threshold (e.g., 20ms).
- Services MUST invoke the context.CancelFunc in a defer statement immediately upon deriving any context.WithTimeout or context.WithDeadline to guarantee resource reclamation.
- Components NEVER use context.Background() or context.TODO() to initiate secondary network calls inside a Chi request-response lifecycle.

## Bad vs Good Implementations
### Context Budget Allocation in Sequential Downstream Calls

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates child contexts with static timeouts without inspecting remaining deadline or calling cancel(), which leads to goroutine and connection pool exhaustion when upstream callers drop connections.
```go
package handlers

import (
	"context"
	"net/http"
	"time"
)

type Service struct {
	cacheClient *http.Client
	dbClient    *http.Client
}

func (s *Service) HandleOrder(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: Hardcoded static timeouts ignore the parent Chi middleware
	// request deadline. If the parent has 100ms left, these 2s timeouts
	// mask the impending cancellation and leak socket resources.
	cacheCtx, _ := context.WithTimeout(r.Context(), 2*time.Second)
	_, err := s.cacheClient.Get("http://cache.internal/order")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Unbounded second call may execute when the client has already disconnected
	dbCtx, _ := context.WithTimeout(r.Context(), 5*time.Second)
	_, err = s.dbClient.Get("http://db.internal/order")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}
```

#### Production Standard (Correct)
> **Standard**: Defensively budgets sub-deadlines based on real-time remaining context duration, enforces minimum thresholds to fast-fail exhausted chains, and guarantees deterministic cancellation cleanup via deferred CancelFunc calls.
```go
package handlers

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

const minBudgetThreshold = 25 * time.Millisecond

type Service struct {
	cacheClient *http.Client
	dbClient    *http.Client
}

func allocateSubBudget(ctx context.Context, fraction float64) (context.Context, context.CancelFunc, error) {
	deadline, ok := ctx.Deadline()
	if !ok {
		// Fallback with defensive maximum ceiling if no root deadline exists
		return context.WithTimeout(ctx, 2*time.Second)
	}

	remaining := time.Until(deadline)
	if remaining < minBudgetThreshold {
		return nil, nil, errors.New("insufficient deadline budget remaining")
	}

	subBudget := time.Duration(float64(remaining) * fraction)
	return context.WithTimeout(ctx, subBudget)
}

func (s *Service) HandleOrder(w http.ResponseWriter, r *http.Request) {
	// Allocate 30% of remaining deadline to cache
	cacheCtx, cancelCache, err := allocateSubBudget(r.Context(), 0.30)
	if err != nil {
		http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout)
		return
	}
	defer cancelCache()

	reqCache, _ := http.NewRequestWithContext(cacheCtx, http.MethodGet, "http://cache.internal/order", nil)
	if _, err := s.cacheClient.Do(reqCache); err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}

	// Allocate 60% of remaining deadline to database, retaining 10% safety cushion
	dbCtx, cancelDB, err := allocateSubBudget(r.Context(), 0.60)
	if err != nil {
		http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout)
		return
	}
	defer cancelDB()

	reqDB, _ := http.NewRequestWithContext(dbCtx, http.MethodGet, "http://db.internal/order", nil)
	if _, err := s.dbClient.Do(reqDB); err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}

	w.WriteHeader(http.StatusOK)
}
```

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 Chi v5 Context Sub-Deadline Budget Allocation Guardrail

Go Chi v5 Context Sub-Deadline Budget Allocation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic context deadline budgeting and sub-deadline allocation across sequential and parallel outbound operations within Go Chi v5 HTTP handlers. Prevents cascade connection exhaustion and thread starvation caused by static timeouts that ignore remaining request lifetime budgets or lack defensive deadline propagation. 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: Inheriting unbounded Chi request contexts or applying static outbound timeouts exceeding parent context deadlines 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 DriftInheriting unbounded Chi request contexts or applying static outbound timeouts exceeding parent context deadlinesCritical
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 inspect the incoming request context via ctx.Deadline() before initiating downstream network operations.

Engineers MUST ALWAYS inspect the incoming request context via ctx.Deadline() before initiating downstream network operations.

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 calculate remaining deadline budget (time.Until(deadline)) and allocate explicit fractional quotas (e.g., 40% DB, 40% downstream HTTP, 20% slack/serialization) rather than applying uncoordinated static timeouts.

Engineers MUST calculate remaining deadline budget (time.Until(deadline)) and allocate explicit fractional quotas (e.g., 40% DB, 40% downstream HTTP, 20% slack/serialization) rather than applying uncoordinated static timeouts.

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 create outbound contexts using context.WithTimeout with a duration greater than the parent context's remaining duration without clamping to the parent deadline.

Engineers MUST NOT create outbound contexts using context.WithTimeout with a duration greater than the parent context's remaining duration without clamping to the parent deadline.

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

Code SHOULD abort execution immediately and return http.StatusGatewayTimeout (504) if remaining context budget falls below a defined operational threshold (e.g., 20ms).

Code SHOULD abort execution immediately and return http.StatusGatewayTimeout (504) if remaining context budget falls below a defined operational threshold (e.g., 20ms).

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 invoke the context.CancelFunc in a defer statement immediately upon deriving any context.WithTimeout or context.WithDeadline to guarantee resource reclamation.

Services MUST invoke the context.CancelFunc in a defer statement immediately upon deriving any context.WithTimeout or context.WithDeadline to guarantee resource reclamation.

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

Components NEVER use context.Background() or context.TODO() to initiate secondary network calls inside a Chi request-response lifecycle.

Components NEVER use context.Background() or context.TODO() to initiate secondary network calls inside a Chi request-response lifecycle.

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 Chi v5 Context Sub-Deadline Budget Allocation Guardrail critical for AI coding assistants?

Enforces deterministic context deadline budgeting and sub-deadline allocation across sequential and parallel outbound operations within Go Chi v5 HTTP handlers. Prevents cascade connection exhaustion and thread starvation caused by static timeouts that ignore remaining request lifetime budgets or lack defensive deadline propagation. 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 (Inheriting unbounded Chi request contexts or applying static outbound timeouts exceeding parent context deadlines) 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