Skip to content

fix: avoid double handling counter errors - #63

Open
lprnmns wants to merge 1 commit into
go-chi:masterfrom
lprnmns:fix/respond-on-limit-counter-error
Open

lprnmns wants to merge 1 commit into
go-chi:masterfrom
lprnmns:fix/respond-on-limit-counter-error

Conversation

@lprnmns

@lprnmns lprnmns commented Aug 31, 2026

Copy link
Copy Markdown

Problem

When a custom LimitCounter returns an error, RespondOnLimit invokes the configured error handler and then invokes the configured rate-limit handler as if the request had exceeded its limit. This can append a second response body and misrepresent a backend failure as HTTP 429.

Fix

Route the shared limit check through a private result that distinguishes a limit decision from a counter error. On counter errors, call only WithErrorHandler; preserve the existing boolean behavior and normal rate-limit response path.

Tests

  • go test -run TestRespondOnLimit_CounterErrorUsesErrorHandlerOnly -count=1 — passed
  • go test -v ./... — passed
  • go test -race -count=1 ./... — passed
  • go vet ./... — passed
  • go build -v ./ — passed
  • go test -run '^$' -bench=. -count=1 ./... — passed
  • _example: go build -v ./, go test -v ./..., and go test -race -count=1 ./... — passed
  • gofmt -d limiter.go limiter_error_test.go and git diff --check — clean

Validated with the repository-requested Go 1.24.1 toolchain.

Compatibility

The public OnLimit and RespondOnLimit signatures and return behavior are unchanged. Only counter-error handling is separated from the normal rate-limit response path; the local backend and normal 429 behavior are unchanged.

Related issue

Independent reproduction; no exact current issue or pull request was found.

@github-actions

Copy link
Copy Markdown

Benchmark Results

goos: linux
goarch: amd64
pkg: github.com/go-chi/httprate
cpu: AMD EPYC 9V74 80-Core Processor                
               │ master.txt  │               pr.txt               │
               │   sec/op    │   sec/op     vs base               │
LocalCounter-4   20.34m ± 1%   20.45m ± 0%  +0.53% (p=0.001 n=10)

               │  master.txt  │             pr.txt             │
               │     B/op     │     B/op      vs base          │
LocalCounter-4   2.843Mi ± 0%   2.843Mi ± 0%  ~ (p=0.481 n=10)

               │ master.txt  │            pr.txt             │
               │  allocs/op  │  allocs/op   vs base          │
LocalCounter-4   121.5k ± 0%   121.5k ± 0%  ~ (p=0.481 n=10)

@lprnmns
lprnmns marked this pull request as ready for review August 31, 2026 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant