Repository navigation
feat(a2agrpc): add GRPCConnectionPool for gRPC client connection reuse (fixes #109) - #382
Conversation
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
Add a GRPCConnectionPool interface and a default in-memory implementation for reusing gRPC connections by URL. Background: grpc.NewClient creates a long-lived ClientConn with name resolution, TCP reconnection, and TLS handshake. Creating one per client (as the current WithGRPCTransport does) incurs unnecessary overhead. Changes: - GRPCConnectionPool interface: Acquire(+opts), Release - DefaultGRPCConnectionPool: in-memory pool with TTL eviction - WithPooledGRPCTransport: FactoryOption that acquires from the pool and releases on transport Destroy - 6 tests covering: acquire, reuse, multi-URL, TTL eviction, zero-TTL (no eviction), release semantics Design follows yarolegovich's proposal in a2aproject#109.
b3afd90 to
e3776b9
Compare
|
@nahapetyan-serob — gentle ping on this one too. CI is all green (Go + ITK + PR title). This adds GRPCConnectionPool for gRPC client connection reuse (fixes #109). Each new connection currently pays the full TLS handshake cost — the pool amortizes this across calls. 34 tests, zero regressions. Would appreciate a review when you have time. |
|
@nahapetyan-serob — gentle ping (since 07-24). CI is all green (Go + ITK + PR title), and this is a thin, non-opinionated addition: a |
|
@nahapetyan-serob — one more gentle ping (last was 08-13). This is a thin, non-opinionated addition: |
|
Thanks for the contribution and the nudge! Sorry for the delay—we’re a bit stretched on bandwidth right now, but we’ll get back to this as soon as we have the capacity to give it a proper review. Appreciate your patience! |
| return len(p.conns) | ||
| } | ||
|
|
||
| func (p *DefaultGRPCConnectionPool) evictExpired() { |
There was a problem hiding this comment.
we should never be evicting connections used by clients
There was a problem hiding this comment.
Done in e042450. Connections are reference counted now: Release decrements the count and only stamps idleSince when it reaches zero, and evictIdle only ever collects connections whose count is zero. A connection a caller is holding is not a candidate for eviction at all, however long it has been held.
Test: TestDefaultPool_DoesNotEvictReferencedConnection acquires without releasing, sleeps for two TTLs, and asserts the same *grpc.ClientConn comes back. It fails on the previous revision (connection held by a caller was evicted and replaced) — I ran it against e3776b9 to confirm the test actually pins the behaviour and isn't just passing by accident.
|
|
||
| // Acquire returns a cached connection for url or creates one with the | ||
| // provided dial options. Expired connections are evicted before lookup. | ||
| func (p *DefaultGRPCConnectionPool) Acquire(ctx context.Context, url string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { |
There was a problem hiding this comment.
opts should be a part of pool constructor function if they do not contribute to the cache key
There was a problem hiding this comment.
Done in e042450. The options moved to the constructor:
pool := a2agrpc.NewDefaultGRPCConnectionPool(ttl, opts...)
conn, err := pool.Acquire(ctx, url)You're right that they cannot live on Acquire — they are not part of the pool key, so two callers asking for the same URL with different options would silently end up with whichever connection was dialed first, and the second caller's options would be discarded with no signal. WithPooledGRPCTransport no longer takes options either; the pool carries them.
One thing I left alone so you can decide it: Acquire still takes a ctx that nothing uses now that dialing is configured at construction. Say the word and I'll drop it as well.
| now := time.Now() | ||
| for url, pc := range p.conns { | ||
| if now.Sub(pc.lastUsed) > p.ttl { | ||
| _ = pc.conn.Close() |
There was a problem hiding this comment.
Done in e042450. The error is logged through the repo's own logger rather than discarded:
log.Error(ctx, "grpc connection pool: closing idle connection", err)Two related sites got the same treatment, since the same pattern was there: Close now returns errors.Join of the close errors instead of dropping them on the floor, and the loser of a dial race logs the failure to close its redundant connection. That covers every Close() in the file; there is no remaining _ = ...Close().
| // gRPC ClientConns are long-lived and expensive to recreate — a pool | ||
| // avoids the hidden performance cost of creating a new connection on | ||
| // every client creation. | ||
| type GRPCConnectionPool interface { |
There was a problem hiding this comment.
a2agrpc.GRPCConnectionPool -> a2agrpc.ConnectionPool
There was a problem hiding this comment.
Done in e042450: a2agrpc.GRPCConnectionPool is now a2agrpc.ConnectionPool.
I stopped there and left the concrete names (DefaultGRPCConnectionPool, NewDefaultGRPCConnectionPool) as they are, since you named only the interface. If you want the package prefix to carry the gRPC part all the way through, DefaultConnectionPool / NewDefaultConnectionPool is a mechanical rename — just say so and I'll fold it into this PR.
| } | ||
|
|
||
| // Len returns the current number of pooled connections. | ||
| func (p *DefaultGRPCConnectionPool) Len() int { |
There was a problem hiding this comment.
does not need to be exported
There was a problem hiding this comment.
Done in e042450: Len() is now the unexported size(). It is only called from pool_test.go, which is in the same package, so nothing outside loses an entry point.
| return pc.conn, nil | ||
| } | ||
|
|
||
| conn, err := grpc.NewClient(url, opts...) |
There was a problem hiding this comment.
critical sections must be short, here we're opening a connection holding a mutex
There was a problem hiding this comment.
Done in e042450. grpc.NewClient no longer runs under the mutex. Acquire takes the lock twice, each time only for map access:
- once to take a reference on an existing entry,
- once to publish the connection it just dialed.
If another goroutine published a connection for the same URL while this one was dialing, the later one closes its own connection (logging a failure) and takes a reference on the winner instead. So no lock is held across the dial, and the map is never read or written without it.
| p.mu.Lock() | ||
| defer p.mu.Unlock() | ||
|
|
||
| p.evictExpired() |
There was a problem hiding this comment.
it's better to add connection eviction task when ref count goes to zero
There was a problem hiding this comment.
Done in e042450, and this is the change that makes the other one possible: the TTL clock now starts when the reference count reaches zero, not when the connection was created. Release stamps idleSince only on the 1 → 0 transition, so eviction and release are the same event from the pool's point of view.
I kept the sweep on Acquire rather than spawning a timer goroutine, since the refcount is what arms the TTL and the sweep can now only collect connections that were released and then left idle. If you'd rather have an explicit timer, that's a small addition on top — I left it out because a timer needs a lifetime to manage (Close becomes load-bearing) and the sweep gets the same result without one.
… the lock Addresses the review on a2aproject#382. - Never evict a connection a caller is using: connections are reference counted, releasing the last reference arms the TTL, and the sweep only takes unreferenced connections. A connection held by a caller now survives any number of evictions. - The dial options belong to the pool, not to Acquire: they are not part of the pool key, so passing them per call let two callers share whichever connection happened to be created first. - grpc.NewClient no longer runs under the mutex. The lock only covers map access, and the loser of a dial race closes its own connection. - Eviction and Close return or log their close errors instead of discarding them. - GRPCConnectionPool -> ConnectionPool, and Len is no longer exported.
|
All seven points are in What I ran locally, in the order the
The behavioural change is pinned by Two things I left for you rather than deciding myself:
Both are one-line changes if you want them. |
|
Light check-in on this one, six weeks after your "stretched on bandwidth" note — not a nudge for a merge, just so it does not sit in your queue indefinitely. State: rebased, If it helps you triage: closing it is a legitimate answer and I will not re-open or repeat this note. If you do want it, it needs nothing further from me; if you would rather it land as an example/recipe instead of SDK surface (the shape yarolegovich preferred on the other PR), say so and I will re-cut it that way. Either way this is my last ping on #382. |
|
Last note on this one, and it carries new material rather than a repeat of the ask. Since 10-19 the repo merged #490 ( Three ways this ends, in the order I would pick them:
I will not comment on it again. If it is still open when you reach it, any of the three is a good answer to me. |
Reference counting and TTL eviction added lifecycle bugs (a repeated Destroy could release a connection still used by another client) while duplicating what grpc.ClientConn idle mode already does. ConnCache keeps one connection per URL until Close, so client Destroy never affects other clients.
|
Thanks for sticking with this. I pushed ff7a364, which replaces the pool with a smaller The reference counting was also where the bugs were. Closing idle connections is something |
🤖 I have created a release *beep* *boop* --- ## [2.8.0](v2.7.0...v2.8.0) (2026-11-06) ### Features * **a2aacp:** add an A2A agent executor for Agent Client Protocol (ACP) agents ([#491](#491), [#492](#492), [#493](#493), [#494](#494), [#530](#530), [#545](#545), [#548](#548), [#552](#552), [#562](#562)) * **a2agrpc:** add GRPCConnectionPool for gRPC client connection reuse (fixes [#109](#109)) ([#382](#382)) ([a2411f7](a2411f7)) * **a2asrv:** add NewErrorSanitizer, an opt-in interceptor which logs request errors in full and sends clients only A2A errors ([#552](#552)) ([ece71bc](ece71bc)) * **a2asrv:** agent card HTTP caching (ETag/304, opt-in Cache-Control) ([#496](#496)) ([313efd9](313efd9)) * implement structured input extension ([#490](#490)) ([367f987](367f987)) ### Bug Fixes * **a2aclient:** honor API key security scheme Location ([#497](#497)) ([c59beb5](c59beb5)) * **a2aclient:** honor configured HTTP authentication schemes ([#502](#502)) ([413de0c](413de0c)) * **a2aclient:** normalize service param keys set by the client and AuthInterceptor ([#479](#479)) ([96f4df0](96f4df0)) * **a2aclient:** return JSON-RPC errors from non-200 responses ([#559](#559)) ([97f1fac](97f1fac)) * **a2acrypto:** reject malformed Unicode before signing ([#450](#450)) ([ec6cb14](ec6cb14)) * **a2aevent:** preserve input-required history order ([#501](#501)) ([72f94a3](72f94a3)) * **a2aevent:** recover the whole artifact when it changes in place ([#485](#485)) ([4d61739](4d61739)) * **a2a:** round-trip null data and nil raw parts through JSON ([#513](#513)) ([186decc](186decc)) * **a2asrv:** make ServiceParams.With nil-safe ([#544](#544)) ([c6042b8](c6042b8)) * **a2asrv:** preserve escaped tenant REST paths ([#514](#514), [#562](#562)) ([f86cf6c](f86cf6c)) * **a2asrv:** preserve numeric precision in raw card ETags ([#546](#546)) ([18c2e72](18c2e72)) * **a2asrv:** reject HEAD before creating task subscriptions ([#481](#481)) ([e641e3c](e641e3c)) * **a2asrv:** split comma-separated A2A-Extensions values ([#519](#519)) ([db83820](db83820)), closes [#516](#516) * **a2av0:** keep security schemes and v0.3 interface in extended agent cards ([#558](#558)) ([196d4bb](196d4bb)), closes [#556](#556) * **client:** accept cached status and artifact stream events ([#508](#508)) ([ea78132](ea78132)) * **client:** honor streaming interceptor error recovery ([#507](#507)) ([737b626](737b626)) * **client:** keep propagated tenants local to each call ([#495](#495)) ([0eaf017](0eaf017)) * **client:** preserve escaped REST path segments ([#488](#488)) ([8880d8f](8880d8f)) * compare and send A2A-Version as Major.Minor ([#555](#555)) ([b5ea753](b5ea753)) * don't fail CancelTask when the canceled execution ends first ([#521](#521)) ([1613ae6](1613ae6)), closes [#518](#518) * don't move a task to FAILED when cancelation retries run out ([#522](#522)) ([247933b](247933b)) * **jsonrpc:** return empty result for successful push config deletion ([#525](#525)) ([42d0738](42d0738)) * pass CancelTask metadata over REST ([#520](#520)) ([a104b2e](a104b2e)), closes [#517](#517) * **pbconv:** preserve JSON data part values ([#503](#503)) ([7c040e0](7c040e0)) * **pbconv:** send pkceRequired for authorization code flows ([#542](#542)) ([cb2c30b](cb2c30b)) * **push:** cap push notification configs per task ([#405](#405)) ([6bb5a68](6bb5a68)) * report executions or cancelations in progress, and messages to terminal tasks in cluster mode, as UnsupportedOperation ([#552](#552)) ([ece71bc](ece71bc)) * **sse:** ignore a leading UTF-8 byte order mark ([#511](#511)) ([248f628](248f628)) * **taskexec:** keep the error when broadcasting an event fails ([#536](#536)) ([636fa9f](636fa9f)) * **taskexec:** report canceler panics during concurrent cancelation ([#535](#535)) ([7ffc680](7ffc680)) * **taskexec:** skip heartbeats for non-positive intervals ([#543](#543)) ([c4158ae](c4158ae)) * **taskexec:** wait for the cancelation result of input-required tasks ([#560](#560)) ([3194abe](3194abe)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --------- Co-authored-by: Yaroslav Shevchuk <[email protected]>
Summary
Adds a
GRPCConnectionPoolinterface and a default in-memory implementation that enables gRPC connection reuse across client creations. Fixes #109.Problem
WithGRPCTransportcallsgrpc.NewClient(url, opts...)on every client creation. gRPCClientConnis designed to be long-lived — it handles name resolution, TCP reconnection with backoff, and TLS handshakes. Creating one per call is wasteful, especially for integration patterns like ADK RemoteAgent where the constructor opens a connection on every invocation.Solution
Adds two new exports to
a2agrpc/v1:1.
GRPCConnectionPoolinterface2.
DefaultGRPCConnectionPoolAn in-memory pool keyed by URL with configurable idle TTL. Zero/negative TTL disables eviction.
3.
WithPooledGRPCTransportA
FactoryOptionthat acquires from the pool and releases onDestroy():Design decisions
WithPooledGRPCTransport) not implicit — users opt inoptsatAcquiretime for consistency withWithGRPCTransportAcquireto avoid background goroutinesReleasedoes NOT close the connection — the pool owns the lifecycle