Skip to content

Optimize throttle middleware by avoiding unnecessary timer creation#1011

Merged
VojtechVitek merged 1 commit into
go-chi:masterfrom
vasayxtx:throttle-middleware-optimization
Aug 26, 2025
Merged

Optimize throttle middleware by avoiding unnecessary timer creation#1011
VojtechVitek merged 1 commit into
go-chi:masterfrom
vasayxtx:throttle-middleware-optimization

Conversation

@vasayxtx

@vasayxtx vasayxtx commented Aug 1, 2025

Copy link
Copy Markdown
Contributor
  • Only create time.NewTimer() when actually needed to wait
  • Reduces allocations from 7 to 4 and memory usage by ~54%
  • Improves performance by ~50% in high-throughput scenarios

Benchmark results:

Before:

goos: darwin
goarch: arm64
pkg: github.com/go-chi/chi/v5/middleware
cpu: Apple M1 Max
BenchmarkThrottle
BenchmarkThrottle-10    	 3349486	       382.3 ns/op	     456 B/op	       7 allocs/op
PASS

After:

goos: darwin
goarch: arm64
pkg: github.com/go-chi/chi/v5/middleware
cpu: Apple M1 Max
BenchmarkThrottle
BenchmarkThrottle-10    	 6310284	       186.9 ns/op	     208 B/op	       4 allocs/op
PASS

- Only create time.NewTimer() when actually needed to wait
- Reduces allocations from 7 to 4 and memory usage by ~54%
- Improves performance by ~50% in high-throughput scenarios

@VojtechVitek VojtechVitek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you!

I'll wait few more days before merging to allow more 👀 reviews

@VojtechVitek VojtechVitek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@VojtechVitek VojtechVitek merged commit cf537d4 into go-chi:master Aug 26, 2025
10 checks passed
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.

2 participants