Skip to content

feat(a2agrpc): add GRPCConnectionPool for gRPC client connection reuse (fixes #109) - #382

Merged
yarolegovich merged 5 commits into
a2aproject:mainfrom
kuangmi-bit:feat/grpc-connection-pool
Nov 2, 2026
Merged

yarolegovich merged 5 commits into
a2aproject:mainfrom
kuangmi-bit:feat/grpc-connection-pool

Conversation

@kuangmi-bit

Copy link
Copy Markdown
Contributor

Summary

Adds a GRPCConnectionPool interface and a default in-memory implementation that enables gRPC connection reuse across client creations. Fixes #109.

Problem

WithGRPCTransport calls grpc.NewClient(url, opts...) on every client creation. gRPC ClientConn is 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. GRPCConnectionPool interface

type GRPCConnectionPool interface {
    Acquire(ctx context.Context, url string, opts ...grpc.DialOption) (*grpc.ClientConn, error)
    Release(*grpc.ClientConn) error
}

2. DefaultGRPCConnectionPool

An in-memory pool keyed by URL with configurable idle TTL. Zero/negative TTL disables eviction.

pool := NewDefaultGRPCConnectionPool(5 * time.Minute)

3. WithPooledGRPCTransport

A FactoryOption that acquires from the pool and releases on Destroy():

pool := a2agrpc.NewDefaultGRPCConnectionPool(5 * time.Minute)
defer pool.Close()

client := a2aclient.NewFromCard(ctx, card,
    a2agrpc.WithPooledGRPCTransport(pool, grpc.WithTransportCredentials(...)),
)

Design decisions

  • Pool is explicit (WithPooledGRPCTransport) not implicit — users opt in
  • Accepts opts at Acquire time for consistency with WithGRPCTransport
  • TTL eviction runs on Acquire to avoid background goroutines
  • Release does NOT close the connection — the pool owns the lifecycle
  • 6 tests: acquire, reuse, multi-URL, TTL eviction, zero-TTL, release

@gemini-code-assist

Copy link
Copy Markdown
Contributor

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.
@kuangmi-bit
kuangmi-bit force-pushed the feat/grpc-connection-pool branch from b3afd90 to e3776b9 Compare July 22, 2026 22:01
@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

@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.

@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

@nahapetyan-serob — gentle ping (since 07-24). CI is all green (Go + ITK + PR title), and this is a thin, non-opinionated addition: a GRPCConnectionPool for gRPC client connection reuse, mirroring the existing HTTP client pooling pattern. No change to the public API beyond the new pool type. Happy to adjust anything the review would like.

@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

@nahapetyan-serob — one more gentle ping (last was 08-13). This is a thin, non-opinionated addition: GRPCConnectionPool for gRPC client connection reuse (fixes #109), CI green since July (Go + ITK + PR title). If the shape isn't right or you'd prefer it as a separate package, say the word and I'll adjust — otherwise a review (or a close with direction) would be appreciated so it doesn't sit stale for another month.

@nahapetyan-serob

Copy link
Copy Markdown
Contributor

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!

Comment thread a2agrpc/v1/pool.go Outdated
return len(p.conns)
}

func (p *DefaultGRPCConnectionPool) evictExpired() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we should never be evicting connections used by clients

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread a2agrpc/v1/pool.go Outdated

// 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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

opts should be a part of pool constructor function if they do not contribute to the cache key

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread a2agrpc/v1/pool.go Outdated
now := time.Now()
for url, pc := range p.conns {
if now.Sub(pc.lastUsed) > p.ttl {
_ = pc.conn.Close()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

let's log

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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().

Comment thread a2agrpc/v1/pool.go Outdated
// 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 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

a2agrpc.GRPCConnectionPool -> a2agrpc.ConnectionPool

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread a2agrpc/v1/pool.go Outdated
}

// Len returns the current number of pooled connections.
func (p *DefaultGRPCConnectionPool) Len() int {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

does not need to be exported

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread a2agrpc/v1/pool.go Outdated
return pc.conn, nil
}

conn, err := grpc.NewClient(url, opts...)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

critical sections must be short, here we're opening a connection holding a mutex

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread a2agrpc/v1/pool.go Outdated
p.mu.Lock()
defer p.mu.Unlock()

p.evictExpired()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

it's better to add connection eviction task when ref count goes to zero

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

All seven points are in e042450, with a reply in each thread above.

What I ran locally, in the order the Go workflow runs it:

step result
go mod tidy -diff no diff
go build -mod=readonly -v ./... ok
go test -race -mod=readonly -count=1 -shuffle=on ./... all packages ok
golangci-lint run ./... (v2.11.4, the version the lint workflow pins) 0 issues
golangci-lint fmt --diff no diff

The behavioural change is pinned by TestDefaultPool_DoesNotEvictReferencedConnection: it acquires a connection, never releases it, waits two TTLs, and requires the same *grpc.ClientConn back. On the parent revision that assertion fails with connection held by a caller was evicted and replaced; on e042450 it passes. TestDefaultPool_ReferenceCount covers the other direction — the connection survives while one reference is outstanding, and is replaced once the last reference is released and the TTL elapses.

Two things I left for you rather than deciding myself:

  1. Acquire still takes a ctx that nothing uses now that the dial options live on the pool.
  2. Only the interface got the shorter name you asked for; the concrete DefaultGRPCConnectionPool / NewDefaultGRPCConnectionPool are unchanged.

Both are one-line changes if you want them.

@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

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, MERGEABLE, all seven review points answered in-thread (e042450), the pool is opt-in and touches only the gRPC client path — no new dependency, no change to existing behaviour.

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.

@kuangmi-bit

Copy link
Copy Markdown
Contributor Author

Last note on this one, and it carries new material rather than a repeat of the ask.

Since 10-19 the repo merged #490 (a2aext/structuredinput/) and #491–#494 (acp agent executor, four parts), all on 10-27. That is useful for triage: this project now accepts packages outside the core client path, so the shape I proposed is not the only shape that could land.

Three ways this ends, in the order I would pick them:

  1. Move GRPCConnectionPool into a2aext/ and take it as an opt-in package, the way structuredinput arrived.
  2. Or cut it down to the pool's own unit tests plus one call-site test and drop the client wiring — smaller surface, same regression coverage for #109.
  3. Or close it. Five green checks and MERGEABLE are not a reason to keep a PR alive, and no reviewer for an optional component is a fine reason to drop it.

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.
@yarolegovich

Copy link
Copy Markdown
Member

Thanks for sticking with this. I pushed ff7a364, which replaces the pool with a smaller ConnCache and WithCachedGRPCTransport. The useful part of the pool is sharing one grpc.ClientConn per agent URL between clients; the reference counting and TTL eviction on top of it added API surface and complexity for marginal value.

The reference counting was also where the bugs were. Release runs on every Destroy() and only clamps at zero, so destroying the same client twice drops another client's reference and lets its connection be evicted and closed while still in use. Eviction also only ran inside Acquire, so idle connections stayed open until the next client happened to be created.

Closing idle connections is something grpc.ClientConn already does: after 30 minutes without RPCs it enters idle mode, shuts down its resolver and load balancer, tears down its connections, and reconnects on the next call (see grpc.WithIdleTimeout). ConnCache therefore keeps each connection until Close(), so a client's Destroy() can never affect other clients. Could you update the PR title and description to match the new API?

@yarolegovich
yarolegovich merged commit a2411f7 into a2aproject:main Nov 2, 2026
5 checks passed
yarolegovich added a commit that referenced this pull request Nov 6, 2026
🤖 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]>
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.

[Feature] Add an extension point for client connection pooling

3 participants