diff --git a/docs/docs/CHANGELOG.md b/docs/docs/CHANGELOG.md index cf766d4e..645369fd 100644 --- a/docs/docs/CHANGELOG.md +++ b/docs/docs/CHANGELOG.md @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix a race in the bbolt store where the asynchronous cleanup scheduled by an expired read could delete a value that had just been refreshed; the delete now only fires when the key still carries the same expired generation it observed. - Marginally increase the performances of requests processing - Marginally improve the performances of PoW validation +- Significantly improve the performances of the gzip middleware ## v1.25.0: Necron diff --git a/internal/gzip.go b/internal/gzip.go index c83a0edf..e9ecdb9d 100644 --- a/internal/gzip.go +++ b/internal/gzip.go @@ -2,11 +2,28 @@ package internal import ( "compress/gzip" + "io" "net/http" "strings" + "sync" ) func GzipMiddleware(level int, next http.Handler) http.Handler { + // Validate the level once at setup; gzip.NewWriterLevel only fails for + // invalid levels and we'd rather panic now than mid-request. + if _, err := gzip.NewWriterLevel(io.Discard, level); err != nil { + panic(err) + } + + // Per-middleware pool of *gzip.Writer. Each entry carries ~40 KiB of + // deflate buffers; reusing them avoids that allocation on every request. + pool := sync.Pool{ + New: func() any { + gz, _ := gzip.NewWriterLevel(io.Discard, level) + return gz + }, + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { next.ServeHTTP(w, r) @@ -14,11 +31,13 @@ func GzipMiddleware(level int, next http.Handler) http.Handler { } w.Header().Set("Content-Encoding", "gzip") - gz, err := gzip.NewWriterLevel(w, level) - if err != nil { - panic(err) - } - defer gz.Close() + gz := pool.Get().(*gzip.Writer) + gz.Reset(w) + defer func() { + gz.Close() + gz.Reset(io.Discard) + pool.Put(gz) + }() grw := gzipResponseWriter{ResponseWriter: w, sink: gz} next.ServeHTTP(grw, r)