add per-client concurrency limiter interceptor for gRPC clients#552
Open
k4leung4 wants to merge 3 commits into
Open
add per-client concurrency limiter interceptor for gRPC clients#552k4leung4 wants to merge 3 commits into
k4leung4 wants to merge 3 commits into
Conversation
1be93ca to
867dec4
Compare
Bug fix: - Replace bool released + manual check with sync.Once in releasingStream to prevent double semaphore release under concurrent RecvMsg calls Tests: - Fix LimitsConcurrency: use server-side srv.serving counter instead of sampling InFlight() before the interceptor is entered (was a race) - Add TestLimiter_StreamReleasesSlotOnRecvError: verifies stream holds slot, releases on RecvMsg error, and slot is reusable afterward Docs: - InFlight(): note value is approximate under contention - StreamClientInterceptor: document that callers must drain RecvMsg to release the slot - releasingStream: document the drain-to-EOF requirement Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2ffa3c0 to
c617fdb
Compare
Add a goroutine in newReleasingStream that watches the stream context and releases the semaphore slot when the context is cancelled. This prevents permanent slot leaks from abandoned streams where RecvMsg is never drained (e.g., caller gives up, context cancelled before recv). The slot is still released via RecvMsg on the normal path; the goroutine is a safety net using sync.Once to ensure exactly-once release regardless of which path fires first. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Signed-off-by: Kenny Leung <kleung@chainguard.dev>
c617fdb to
3a42f38
Compare
eslerm
approved these changes
Mar 27, 2026
eslerm
left a comment
There was a problem hiding this comment.
🤖: Clean implementation — buffered-channel semaphore is idiomatic, sync.Once handles dual-path release correctly, context errors properly mapped to gRPC status codes.
| // StreamClientInterceptor returns a gRPC stream client interceptor that | ||
| // acquires a concurrency slot before establishing the stream. The slot is | ||
| // released when RecvMsg returns an error (including io.EOF). Callers must | ||
| // drain RecvMsg to completion to avoid leaking slots. |
There was a problem hiding this comment.
🤖: This comment says callers must drain RecvMsg to completion to avoid leaking slots — but the safety-net goroutine added in the third commit releases the slot on context cancellation too. The godoc should reflect both release paths to avoid misleading callers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add a new
pkg/interceptors/concurrencypackage that provides gRPCclient interceptors to cap the number of concurrent in-flight RPCs per
connection. When the limit is reached, new calls block until a slot
opens or the context is cancelled.
Motivation
Addresses CUS-237 /
CUS-172 /
chainguard-dev/internal-dev#18988.
During INC-44, uncapped concurrency allowed individual API server
instances to exhaust the load balancer's 250 connection limit. A
per-client concurrency limiter throttles each instance's contribution
to downstream load, providing backpressure before the downstream is
overwhelmed.
Package API
Behavior
Stream slot lifecycle
The stream interceptor acquires a slot before stream establishment and
releases it on the first of:
RecvMsgreturns an error (includingio.EOF)Release uses
sync.Oncefor thread-safe exactly-once semantics. If thestream establishment itself fails, the slot is released immediately.
A background goroutine watches
stream.Context().Done()to preventpermanent slot leaks from abandoned streams where
RecvMsgis neverdrained (e.g., caller gives up, context cancelled before recv).
Observability
limiter.InFlight()— current number of in-flight RPCs (approximateunder contention)
limiter.Capacity()— configured maximumThese can be exported as Prometheus gauges by the caller if needed.
Design decisions
Semaphore over token bucket: A semaphore caps concurrent load (the
direct cause of INC-44), while a token bucket caps request rate. Under
normal conditions with fast responses, a semaphore allows high throughput.
Under degraded conditions with slow responses, it naturally throttles
because slots aren't released — exactly the behavior we want.
Opt-in per client: Not added to the default
GRPCDialOptions()sincethe right limit varies by service (IAM needs more headroom than the
recommender). Callers enable it explicitly when dialing.
Tests
TestLimiter_LimitsConcurrency— 5 concurrent calls with limit 2,verifies server-side serving count never exceeds 2
TestLimiter_RespectsContextCancellation— slot full + short context→ DeadlineExceeded/Canceled
TestLimiter_DisabledWithZero— limit 0 is a no-op passthroughTestLimiter_StreamReleasesSlotOnRecvError— stream holds slot,releases on RecvMsg error, slot is reusable for subsequent calls
TestLimiter_StreamReleasesSlotOnContextCancel— stream holds slot,context cancelled without draining RecvMsg, safety net goroutine
releases slot, slot is reusable for subsequent calls
TestLimiter_Capacity— verifies Capacity() returns configured valueFollow-up in mono
After bumping go-grpc-kit, enable per-client in
api-impl/cmd/backend/main.go'sconfigureClients():Test plan
go test ./pkg/interceptors/concurrency/ -v -race— 6/6 passgolangci-lint run ./pkg/interceptors/concurrency/— 0 issues🤖 Generated with Claude Code