Skip to content

feat(grpc-gcp): add built-in channel_load metric for client library pools - #14985

Merged
uditdasari merged 3 commits into
mainfrom
channel-pool-metrics-load
Nov 12, 2026
Merged

uditdasari merged 3 commits into
mainfrom
channel-pool-metrics-load

Conversation

@uditdasari

@uditdasari uditdasari commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Adds the second built-in channel pool metric, channel_pool.channel_load.
Spanner will report it as
spanner.googleapis.com/internal/client/channel_pool/channel_load.

Each time a call starts on a channel, the pool records the number of calls in
flight on that channel, including the new call, in a histogram.

Nothing changes unless built-in metrics are configured with
GcpMetricsOptions.Builder#withBuiltInMetrics (added in #14947). No client
library sets it yet. The Spanner change that turns it on is a follow-up.

How it works:

  • Both call paths in GcpClientCall record the value right after the
    underlying call is created, so a call that cannot be created is not
    recorded. ChannelRef#activeStreamsCountIncr() now returns the channel's
    new count, which is the recorded value. Error penalties are not included.
    If recording throws, the error is logged at FINE and the call goes on as
    normal.
  • Attributes are the pool attributes passed to withBuiltInMetrics (for
    example lane) plus pool_mode. state is left out, and so is the value
    set with withBuiltInMetricsPoolIndex. A histogram series is never removed,
    so a series per pool index would keep being exported after its pool is
    closed.
  • A new @InternalApi call option,
    GcpManagedChannel.BUILT_IN_METRICS_ATTRIBUTES_KEY, lets a client library
    add attributes per call. Spanner will use it for database. The pool's own
    attributes take precedence over call attributes with the same key. Each pool
    caches the combined attributes for up to 100 different call attribute sets.
    Calls with other sets are still recorded, and their attributes are combined
    on each call.
  • Buckets: 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200.
    They are finer at the low end, where most pools run, and the step between
    boundaries never gets smaller. The value is always at least 1, because it
    includes the new call.
  • Pools that use the same meter record into the same series for the same
    attributes.

Measured per call (JMH, 2 forks x 8 x 1s, -prof gc, n2-standard-8 GCE VM,
JDK 17), fake channels, so client CPU only. Each channel_load row is the extra
cost compared with the same run without built-in metrics:

                                         1 thread            8 threads
channel_load, 10 databases               +38 ns, 0 B         +141 ns, 0 B
channel_load, 1,000 databases            +312 ns, +281 B     +353 ns, +281 B
channel_load, no database attribute      +34 ns, 0 B         +991 ns, 0 B
existing Spanner built-in metrics        4,850 ns, 5,400 B   9,932 ns, 5,400 B
  • 10 databases: all attribute sets are cached.
  • 1,000 databases: only 100 sets fit in the cache, so most calls combine the
    attributes again.
  • No database attribute: all 8 threads record into one series, and they wait
    for each other on the lock that every OpenTelemetry histogram series takes
    on each record.
  • The last row is what a successful unary Spanner RPC records today (attempt
    and operation latency and count, GFE latency) in the same setup.

Tests: 25 new tests in GcpChannelPoolChannelLoadTest, covering the recorded
value, buckets and unit, attributes (pool_mode, no pool_index or state,
per-call attributes that cannot override pool attributes), the attribute
cache limit (also under concurrency), every call path (least busy, sticky,
affinity config, draining channel, on-demand channel, call that cannot be
created), a failing record that must not fail the call or leave the channel's
count raised, error penalties not included, the load going down after calls
finish, 8 x 1,000 concurrent calls, DirectPath fallback moving the load to the
cloudpath lane, and the application's metrics staying separate.

…ools

Adds the second built-in channel pool metric, `channel_pool.channel_load`.
Spanner will report it as
`spanner.googleapis.com/internal/client/channel_pool/channel_load`.

Each time a call starts on a channel, the pool records the number of calls in
flight on that channel, including the new call, in a histogram.

Nothing changes unless built-in metrics are configured with
`GcpMetricsOptions.Builder#withBuiltInMetrics` (added in #14947). No client
library sets it yet. The Spanner change that turns it on is a follow-up.

How it works:
- Both call paths in `GcpClientCall` record the value right after the
  underlying call is created, so a call that cannot be created is not
  recorded. `ChannelRef#activeStreamsCountIncr()` now returns the channel's
  new count, which is the recorded value. Error penalties are not included.
- Attributes are the pool attributes passed to `withBuiltInMetrics` (for
  example `lane`) plus `pool_mode`. `pool_index` and `state` are left out. A
  pool index would leave a frozen series behind for every closed pool.
- A new `@InternalApi` call option,
  `GcpManagedChannel.BUILT_IN_METRICS_ATTRIBUTES_KEY`, lets a client library
  add attributes per call. Spanner will use it for `database`. The pool's own
  attributes take precedence over call attributes with the same key. Each pool
  caches the combined attributes for up to 100 different call attribute sets.
  Calls with other sets are still recorded.
- Buckets: 0, 1, 2, 4, 8, 12, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200.
- Pools that use the same meter record into the same series for the same
  attributes.

Measured per call (JMH, 2 forks x 8 x 1s, -prof gc, n2-standard-8 GCE VM,
JDK 17), fake channels, so client CPU only:

```
                                     1 thread            8 threads
channel_load record                  +38 ns, 0 B         +141 ns, 0 B
existing Spanner built-in metrics    4,850 ns, 5,400 B   9,932 ns, 5,400 B
```

The existing built-in metrics row is what a successful unary Spanner RPC
records today (attempt and operation latency and count, GFE latency) in the
same setup. With 8 threads recording to a single attribute set, the OpenTelemetry
histogram's per-series lock raises one channel_load record to about 1.6 µs
(the existing built-in metrics take about 9.9 µs in the same case).

Tests: 25 new tests in `GcpChannelPoolChannelLoadTest`, covering the recorded
value, buckets and unit, attributes (`pool_mode`, no `pool_index` or `state`,
per-call attributes that cannot override pool attributes), the attribute
cache limit (also under concurrency), every call path (least busy, sticky,
affinity config, draining channel, on-demand channel, call that cannot be
created), error penalties not included, the load going down after calls
finish, 8 x 1,000 concurrent calls, DirectPath fallback moving the load to the
cloudpath lane, and the application's metrics staying separate.
@uditdasari
uditdasari requested review from a team as code owners November 12, 2026 13:43
@uditdasari
uditdasari requested a review from olavloite November 12, 2026 13:43

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new built-in metric, channel_pool.channel_load, to track the number of in-flight requests on a channel when a request starts. It updates GcpClientCall and GcpManagedChannel to capture and record this load, and adds support for custom per-call attributes via BUILT_IN_METRICS_ATTRIBUTES_KEY with a bounded cache to prevent memory leaks. Additionally, a comprehensive test suite GcpChannelPoolChannelLoadTest has been added to verify the metric recording, attribute merging, and caching behavior. There are no review comments to address, and the implementation looks solid.

- Catch and log (FINE) a failure to record channel_load, so it cannot fail
  the call or leave the channel's active stream count raised.
- Remove the empty 0 bucket. The recorded value is always at least 1.
- Stop removing a pool_index attribute from the pool attributes of
  channel_load. The pool index is set with withBuiltInMetricsPoolIndex.
- Say "calls" in the histogram description, and rename the method that
  builds the attributes so it no longer shares a name with a field.
- Javadoc: say "100" instead of linking a package-private constant.
- Tests: add a failing-record test, share helpers, add timeouts to
  future.get and rename the bucket test.
}
try {
builtInMetrics.recordChannelLoad(load, callOptions);
} catch (RuntimeException e) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: It is safer to catch Throwable here.

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.

static final String METRIC_CHANNEL_POOL_CHANNEL_LOAD = "channel_pool.channel_load";
static final List<Long> CHANNEL_LOAD_BUCKETS =
Collections.unmodifiableList(
Arrays.asList(1L, 2L, 4L, 8L, 12L, 15L, 20L, 25L, 30L, 40L, 50L, 75L, 100L, 150L, 200L));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we consider using a 'Fibonacci-inspired' series instead in order to keep the steps monotonically increasing? I think that very many channel pools will operate at low load (so in the range 0 to 10 concurrent calls). The current series also has a weird step size between 12 and 15. So maybe rather something like this:

Arrays.asList(
    1L, 2L, 3L, 5L, 8L, 12L, 16L, 20L, 25L, 30L, 40L, 50L, 75L, 100L, 150L, 200L);

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, switched to this list.

- Catch Throwable when recording channel_load.
- Use the buckets 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200.
@uditdasari
uditdasari merged commit 9f87888 into main Nov 12, 2026
212 checks passed
@uditdasari
uditdasari deleted the channel-pool-metrics-load branch November 12, 2026 17:53
whowes pushed a commit that referenced this pull request Nov 13, 2026
🤖 I have created a release *beep* *boop*
---


<details><summary>1.97.0</summary>

##
[1.97.0](v1.96.0...v1.97.0)
(2026-11-12)


### ⚠ BREAKING CHANGES

* **shopping-merchant:** remove discontinued Merchant API v1beta
([#14942](#14942))

### Features

* **bigquery-jdbc:** adds BigQuery graph integration to DatabaseMetadata
methods
([#14930](#14930))
([950b81b](950b81b))
* **gax:** implement resumable upload session resumption
([#14677](#14677))
([24728d6](24728d6))
* **grpc-gcp:** add built-in channel_count metric for client library
pools
([#14947](#14947))
([712f043](712f043))
* **grpc-gcp:** add built-in channel_load metric for client library
pools
([#14985](#14985))
([9f87888](9f87888))
* **shopping-merchant:** remove discontinued Merchant API v1beta
([#14942](#14942))
([2947dfd](2947dfd))
* **storage:** add StorageErrorTypeMapper for standard metrics
([#14694](#14694))
([a9ac393](a9ac393))
* **storage:** add StorageMetricsContext for operation metrics state
([#14728](#14728))
([edea395](edea395))
* **storage:** wire logical operation metrics in Retrying and
StorageOptions
([#14695](#14695))
([589c66c](589c66c))
* update API sources and regenerate
([#14958](#14958))
([75944f3](75944f3))


### Bug Fixes

* **auth:** verify public/private key match with retries in mTLS
keystore loading
([#14829](#14829))
([096dbd6](096dbd6))
* **bigquery:** set QueryResultsFormat.ARROW in QueryArrow sample
([#14960](#14960))
([c98e7c3](c98e7c3))
* **bigtable:** avoid triggering per-RPC credential session fallback on
default call context
([#14961](#14961))
([eb06d2c](eb06d2c))
* **bigtable:** copy Metadata per GetClientConfiguration call
([#14950](#14950))
([278fe2f](278fe2f))
* **bigtable:** disable SwitchingChannelPool when
ChannelPoolConfiguration is empty
([#14911](#14911))
([fa24702](fa24702))
* **bigtable:** handle empty SessionPoolConfiguration in SessionPoolImpl
and PoolSizer
([#14912](#14912))
([cc7b235](cc7b235))
* **bigtable:** replace SessionPoolImpl Watchdog with per-session
closeTimeout
([#14977](#14977))
([a15acfb](a15acfb))
* **spanner-jdbc:** report database default isolation level
([#14929](#14929))
([7e7595a](7e7595a))
* **spanner:** fix PG SHOW isolation level statements
([#14904](#14904))
([bc917ed](bc917ed))


### Dependencies

* bump grpc to 1.85.1, opentelemetry to 1.67.0, and guava to 33.7.2-jre
([#14957](#14957))
([1a27a00](1a27a00))
* bump guava to 33.7.1-jre and jspecify to 1.0.1
([#14937](#14937))
([1441527](1441527))


### Documentation

* **spanner:** update CHANGELOG.md for java spanner releases
([#14935](#14935))
([956681e](956681e))
* **storage:** add Rapid Cache samples
([#14886](#14886))
([e714f62](e714f62))
</details>

---
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: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com>
uditdasari added a commit that referenced this pull request Nov 17, 2026
This turns on the two channel pool metrics that grpc-gcp gained in
#14947 and #14985 and sends them to Cloud Monitoring as Spanner built-in
metrics.

## What is reported

- `channel_pool/channel_count`: the number of channels in the data pool
per state (`active`, `draining`), with the labels `lane`, `pool_mode`
and `pool_index`. The instance is reported as `unknown` because one pool
serves many databases and instances, the same as the existing eef
metrics. The project is the built-in metrics fallback project.
- `channel_pool/channel_load`: for each call, the number of calls that
are open on the chosen channel, as a histogram with the boundaries 1, 2,
3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200. `project_id`,
`instance_id` and `database` come from the resource name of the request,
`lane` and `pool_mode` come from the pool.

## Which pools report

- Only the main data pool. The instance admin and database admin stubs
now get their own channel provider with these metrics off. They already
had their own pools, so this does not add channels.
- With DirectPath fallback, the DirectPath pool and the CloudPath pool
both report under one `pool_index` and are told apart by `lane`.
- The experimental fallback recovery layout reports without `lane`,
because its channels switch between the two paths.

## When nothing is reported

- The application sets its own channel provider, grpc-gcp is disabled,
built-in metrics are disabled, the client uses no credentials, the
emulator is used, or
`SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true`.
- Application settings cannot change these metrics. Spanner always
overwrites the built-in metrics settings in the grpc-gcp options and
adds the per-call labels after the `CallContextConfigurator`s of the
application.

## Cost

- `channel_count` adds nothing per call.
- `channel_load` adds one cached lookup of the resource name per call
and carries the labels in the call options. Recording the value was
measured in #14985 at about 38 ns per call with one thread, and up to
about 1 µs per call when 8 threads write the same series at the same
time.

## Testing

- `GapicSpannerRpcTest` and `SpannerMetadataProviderTest` for the
options and the resource name parsing. `ChannelPoolBuiltInMetricsTest`
runs a client against the mock server and checks that only the data pool
reports, the lanes of the DirectPath fallback pools, the fallback
recovery layout without `lane`, the switches that turn the metrics off,
that application settings cannot change the metrics, and the labels and
boundaries of `channel_load`.
- End to end on a GCE VM against a real database, with the exported data
checked afterwards: CloudPath and DirectPath clients, a static pool, a
dynamic pool that scaled up from 4 to 8 channels and down from 8 to 6
(with 2 draining), two clients in one process (`pool_index` 1 and 2),
two databases, and the long-term series.
uditdasari added a commit to googleapis/google-cloud-go that referenced this pull request Nov 23, 2026
…r the dynamic channel pool (#20923)

## Summary

The dynamic channel pool now reports two metrics to Spanner's built-in
Cloud Monitoring pipeline: how many channels it has, and how busy a
channel is when a call starts on it.

`channel_count`
- Metric:
`spanner.googleapis.com/internal/client/channel_pool/channel_count`
(INT64, sent as a GAUGE)
- Two points per pool: `state=active` (channels in the pool) and
`state=draining` (channels being removed after a scale-down)
- Labels: `pool_mode=dynamic` and `lane`

`channel_load`
- Metric:
`spanner.googleapis.com/internal/client/channel_pool/channel_load`
(DISTRIBUTION, cumulative)
- One value per call attempt (a retry is recorded again): the number of
calls in flight on the channel the call starts on, including that call
- Buckets: 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200
- Labels: `pool_mode=dynamic` and `lane`

`lane` is `directpath` when DirectPath is enabled, else `cloudpath`.
With DirectPath fallback enabled (#20651), it changes to `cloudpath`
once the pool has switched to CloudPath.

For both metrics the exporter adds `client_uid`, `client_name` and
`database` as it does for every built-in metric. The Monarch and Cloud
Monitoring metric descriptors are already live. Java reports the same
metrics (googleapis/google-cloud-java#14947,
googleapis/google-cloud-java#14985).

## How it works

- `channel_count`: an observable up-down counter on the built-in meter
provider (meter `gax-go`). It is registered once the pool has been
created. A callback reads the pool's active channel count and draining
counter once per export (every 60 s).
- `channel_load`: a histogram on the same meter. The pool core lives in
`internal/transport` (#20919), so this PR adds an optional `OnCallStart`
hook to `transport.DCPHooks`. The pool calls it right after it adds a
call to a channel's in-flight count, in the four places where it does
that (pool `Invoke` and `NewStream`, and the entry's unary and streaming
starts), with that channel's in-flight count. The Spanner side sets the
hook only when the histogram was created. Fixed-mode pools return before
that point, so they never call it.
- `lane`: both label sets are built once per pool. If the pool has a
DirectPath fallback, each export and each recording checks the fallback
state and uses the `cloudpath` set after the switch. This adds no
allocations.
- The two metrics are set up independently, so a failure to create one
does not disable the other.
- The callback is unregistered when the pool closes, in the pool's
`OnClose` hook next to closing the fallback state. `Client.Close`
flushes the built-in metrics before it closes the pool, so the final
values are still sent. As for every built-in metric, this last flush is
skipped if the previous export was 30 s ago or less.
- The metrics are only sent to Cloud Monitoring. They are not recorded
on `OpenTelemetryMeterProvider` or `ClientMetricsProvider`.
- `pool_mode`, `state` and `lane` are added to the exporter's label
allow-list.

## When it is not reported

- Built-in metrics are off (emulator, `DisableNativeMetrics`,
`SPANNER_DISABLE_BUILTIN_METRICS=true`, Omni, experimental host)
- `SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true` (same switch name
as Java, turns off both metrics)
- The dynamic channel pool is not turned on. Since #20669, these clients
run on the same pool code in fixed mode (a fixed number of channels, no
scaling up or down). Fixed-mode pools do not report these metrics yet. A
follow-up will add them with `pool_mode=static`.

## Tests

- `internal/transport/dcp_test.go`: `OnCallStart` is called with the
right in-flight count on each of the four call paths, under concurrent
calls, and never on a fixed-mode pool.
- `channel_pool_metrics_test.go`: active and draining counts, scale-up,
the DirectPath lane, `lane` switching to `cloudpath` after a DirectPath
fallback switch, the off switch, built-in metrics being off,
registration errors (each metric still works when the other fails),
collecting while the pool scales, no allocations when recording
`channel_load`, and the wiring through `newDynamicChannelPool` (both
metrics reported, `channel_count` unregistered when the pool closes).
- An end-to-end export through a fake Cloud Monitoring server checks the
metric kind, value type, buckets and labels, that existing built-in
metrics are still exported, that nothing is sent to the customer meter
providers, and that a default (fixed-mode) client sends neither metric.
- The full `spanner` and `internal/transport` packages pass with
`-race`.

## End-to-end test

Ran on a GCE VM (n2-standard-8, us-central1-a) against a real Spanner
instance, with a test binary built from this branch (commit 001d996).
Five clients ran at the same time for 13 minutes, each on its own
database, then a sixth client ran on its own for 15 minutes.

| Run | Pool | Result |
|---|---|---|
| default | fixed mode, 8 threads | No `channel_count` or
`channel_load`, as expected |
| dcp | dynamic, CloudPath, 150 threads for 3 min then 2 threads for 10
min | `lane=cloudpath`. `active` went 8 → 6 → 4 → 2, `draining=2` at
each scale-down and 0 at the end. Mean load about 19 in the busy
minutes, 1 to 3 in the quiet minutes |
| dp | dynamic, DirectPath, 8 threads | `lane=directpath`. `active` 4,
then 2 after the default scale-down |
| dynamic, new metrics off | dynamic, CloudPath, 8 threads,
`SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true` | No `channel_count`
or `channel_load`, as expected |
| dynamic, new metrics on | dynamic, CloudPath, 8 threads |
`lane=cloudpath`, `active` 4, then 2 after the default scale-down |
| DirectPath fallback | dynamic, DirectPath,
`GOOGLE_SPANNER_ENABLE_GCP_FALLBACK=true`, 8 threads | DirectPath
addresses were blocked on the VM after 4 minutes. The pool switched to
CloudPath 5 minutes later, as the fallback rule expects. Both metrics
reported `lane=directpath` before the block and `lane=cloudpath` after
the switch |

- The number of `channel_load` values matched the number of call
attempts each client made (within 0.23% per minute).
- All existing built-in metrics arrived every minute for every database.
For every client, the `operation_count` total matched the number of
queries the client counted itself.
- About 5.7 million queries. The only failures were the timeouts in the
fallback run between the block and the switch.

## Performance

Measured on the same VM after the end-to-end test: a full `SELECT 1`
through a client with the dynamic pool, against an in-process mock
server.

| | 1 CPU | 8 CPUs |
|---|---|---|
| Time per query, new metrics off | 241.8 µs | 51.3 µs |
| Time per query, new metrics on | 244.0 µs | 51.8 µs |
| **Added by the new metrics** | **2.2 µs (+0.9%)** | **0.5 µs (+0.9%)**
|
| For scale: added by the existing built-in metrics | 25.9 µs | 3.8 µs |

The new metrics add no memory allocations. In a worst-case test with no
network at all, recording one `channel_load` value takes about 210 ns on
1 CPU and about 80 ns on 8 CPUs. The live `lane` check adds no
measurable time.
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.

2 participants