Skip to content

Optimize memory usage and fix concurrency issues in middlewares#11

Open
bernardoforcillo wants to merge 4 commits into
mainfrom
deadlock-fix-11866689832695415924
Open

Optimize memory usage and fix concurrency issues in middlewares#11
bernardoforcillo wants to merge 4 commits into
mainfrom
deadlock-fix-11866689832695415924

Conversation

@bernardoforcillo
Copy link
Copy Markdown
Contributor

This PR addresses memory usage and concurrency issues across the framework.

Key changes:

  1. Memory Optimization: Context.Reset now reuses the Keys map, significantly reducing allocations for high-throughput applications.
  2. Concurrency Safety: Fixed a critical data race in the Timeout middleware where the handler could write to the response after a timeout. Introduced BufferedResponseWriter and Context.Clone() to isolate the timed-out handler.
  3. Deadlock Prevention: Refactored RateLimiter to use sync.RWMutex and atomic operations, preventing the cleanup loop from blocking all requests (potential deadlock/starvation).
  4. Robustness: Added panic recovery to Timeout middleware's background goroutine to prevent server crashes.

Verified with go test -race and benchmarks showing 0 allocs/op for Context.Reset.


PR created automatically by Jules for task 11866689832695415924 started by @bernardoforcillo

- `Context.Reset`: Use `clear()` to reuse `Keys` map instead of reallocation, reducing garbage collection pressure.
- `Context.Clone`: Implement deep copy for thread-safe context usage in goroutines.
- `Timeout` Middleware:
    - Fix data race by implementing `bufferedWriter` and cloning the context.
    - Use `sync.Pool` for buffers to minimize allocation.
    - Add panic recovery and safe error handling (discard buffer on error).
- `RateLimiter` Middleware:
    - Switch to `sync.RWMutex` to allow concurrent checks.
    - Use `atomic.Int64` for `lastSeen` timestamp (fixes 32-bit alignment and reduces lock contention).
    - Optimize cleanup loop to use snapshots and avoid holding global lock.
- Tests: Added comprehensive tests for race conditions, timeouts, panics, and concurrency.

Co-authored-by: bernardoforcillo <28314446+bernardoforcillo@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

google-labs-jules Bot and others added 3 commits February 20, 2026 23:42
- `amaro.go`: Configured default `ReadTimeout`, `WriteTimeout`, `IdleTimeout`, and `ReadHeaderTimeout` on `http.Server` to prevent resource exhaustion attacks.
- `routers/trie.go`: Added `sync.RWMutex` to `TrieRouter` to ensure thread-safe concurrent route registration and lookup.
- `routers/concurrency_test.go`: Added tests to verify concurrent route additions and lookups do not race.

Co-authored-by: bernardoforcillo <28314446+bernardoforcillo@users.noreply.github.com>
- `amaro.go`:
    - Introduced `ServerConfig` struct to hold HTTP server configuration.
    - Updated `App` to store `ServerConfig`.
    - Implemented `WithServerConfig` option for bulk configuration.
    - Implemented granular options: `WithReadTimeout`, `WithWriteTimeout`, `WithIdleTimeout`, `WithReadHeaderTimeout`, `WithMaxHeaderBytes`.
    - Updated `New` to initialize with `DefaultServerConfig`.
    - Updated `startServer` to use the configured values.
- `config_test.go`: Added tests to verify configuration initialization.

Co-authored-by: bernardoforcillo <28314446+bernardoforcillo@users.noreply.github.com>
- `amaro.go`:
    - Added `EnableH2C` to `ServerConfig` and `WithH2C` option.
    - Updated `startServer` to wrap the handler with `h2c.NewHandler` if `EnableH2C` is true.
    - Updated `go.mod` to include `golang.org/x/net/http2`.
- `h2c_test.go`: Added test to verify H2C option can be set.

Co-authored-by: bernardoforcillo <28314446+bernardoforcillo@users.noreply.github.com>
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