Skip to content

perf(telemetry, circuit-breaker): record less per call on the cache path - #280

Merged
loks0n merged 2 commits into
mainfrom
perf/telemetry-per-call-cost
Sep 16, 2026
Merged

loks0n merged 2 commits into
mainfrom
perf/telemetry-per-call-cost

Conversation

@loks0n

@loks0n loks0n commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Why

Profiling the cloud API (appwrite-labs/cloud#5861) showed the OpenTelemetry metrics SDK at 11% of busy CPU (MetricAggregator::record, AttributesBuilder, FilteredReservoir::offer). Every cache load behind it emitted eight metric records: the circuit breaker wrote its state, failure and success gauges and an in-flight up/down counter on each call, on top of the call counter, the cache wrote its duration histogram and hit/miss counter, and the SDK walked an exemplar reservoir for each of them. A single record costs about 1.3 µs on PHP 8.5.

What

circuit-breaker: breaker.state, breaker.failures, breaker.successes and breaker.active_calls are now observable gauges read when the adapter collects, not written on every call. The per-call cost drops to one counter add (breaker.calls). Metric names and attributes are unchanged, so the Circuit Breaker dashboard keeps working. Two behaviour changes worth knowing:

  • A breaker that receives no calls still reports its state on every collection. With per-call gauges the series went stale after five minutes of no traffic.
  • breaker.active_calls was an up/down counter summed from ±1 writes and is now a gauge sampled at collection. Same name, same meaning, but a collection between increment and decrement is what it reports. It is not used on any dashboard.

testActiveCallTelemetryUsesPostUpdateState becomes testStateObservedDuringACallIsThePostUpdateState: the state observed while the half-open probe runs is the post-update one, with the probe in flight. A new test checks that gauges are observable without any call and that a call in flight is visible while it runs. The package's PHPStan ignore for the Utopia\Telemetry\Adapter\Test double's runtime properties is extended to ObservableGauge::$callbacks, the same shape it already ignores for $values.

telemetry: the meter provider declares NoneExemplarFilter. Nothing that uses this adapter starts traces, so the SDK's default WithSampledTraceExemplarFilter accepted nothing, but each record still walked the reservoir to find that out. The new test records under a sampled span and asserts the export carries no exemplars; it fails on main.

Measured

Warm-cache Database::getDocument through Cache + CircuitBreaker + OpenTelemetry with a discarding transport, PHP 8.5, 5k iterations, CPU µs per operation. Telemetry overhead is the OpenTelemetry-on minus telemetry-off cost of one Cache::load:

before after
telemetry overhead per Cache::load 15.7 8.0
Cache::load (OpenTelemetry on, with #279) 72.9 22.8
Database::getCollection (OpenTelemetry on, with #279) 104.8 61.8
one histogram record() 1.31 1.26

The exemplar change alone is small per record; the record count is what moves the number. Pairs with #279 (cache decoded-envelope memo) for the second and third rows.

Checks

bin/monorepo check telemetry and bin/monorepo check circuit-breaker pass. bin/monorepo test circuit-breaker passes. bin/monorepo test telemetry exits with code 139 in the Swoole transport tests on this host (macOS, PHP 8.5.10) on unchanged main as well; the whole telemetry suite passes when run with the root vendor/bin/phpunit against the package's vendor/autoload.php (24 tests), with and without this change.

🤖 Generated with Claude Code

Profiling the cloud API showed the OpenTelemetry metrics SDK at 11% of busy
CPU, with every cache load behind it emitting eight metric records: the
circuit breaker wrote its state, failure and success gauges and an in-flight
up/down counter on each call, on top of the call counter, and the SDK
walked an exemplar reservoir for each of them.

circuit-breaker: state, failures, successes and active calls are now
observable gauges read when the adapter collects, not written on every
call. A breaker that receives no calls still reports its state on every
collection, which the per-call gauges did not. The per-call cost drops to
one counter add; metric names and attributes are unchanged.

telemetry: the meter provider declares no exemplars. Nothing that uses the
adapter starts traces, so the SDK's default filter accepted nothing, but it
still cost a reservoir offer on every record.

Measured on a warm-cache Database::getDocument through Cache + CircuitBreaker
+ OpenTelemetry (5k iterations, PHP 8.5, telemetry overhead per cache load):
15.7 µs before, 8.0 µs after (together with the cache memo change this
brings a cache load from 72.9 µs to 22.8 µs CPU).

Refs appwrite-labs/cloud#5861.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@loks0n

loks0n commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Review of e199838:

  • [P2] Release observation callbacks when a breaker is discarded or telemetry is replaced. CircuitBreaker.php:127–137: the new closures strongly capture $this; both telemetry adapters retain and accumulate callbacks by instrument name. With a long-lived adapter, constructing and dropping breakers therefore retains every breaker and its cache adapter and executes all historical observations on every collection. Repeated setTelemetry() also adds registrations, and changing adapters leaves the old adapter observing the breaker. Reproduced with WeakReference: the breaker survives unset() + GC on this head, but is released on the parent; 1,001 discarded instances leave 1,001 callbacks per gauge. Add a registration lifecycle that removes obsolete observations and avoids retaining dead breakers; a weak reference alone would still leave the callback list growing.

  • [P2] Refresh shared state before publishing idle observations. CircuitBreaker.php:129–137: these callbacks read only the local fields, whereas shared state is refreshed by syncFromCache() on calls/inspection. If another worker trips or recovers a shared circuit while this instance is idle, every collection now publishes its old verdict as a fresh sample indefinitely. Reproduced with two breakers sharing one adapter/key: after the active breaker calls trip(), the idle breaker's state callback reports 0 (closed), while getState() correctly returns open and changes the next observation to 1. Refresh the shared snapshot at collection before observing state/successes, without triggering timeout transitions merely to collect telemetry. The previous per-call gauge stopped receiving updates while idle, allowing stale series to expire.

Validation: circuit-breaker unit suite passed (34 tests, 106 assertions); non-Swoole telemetry tests passed (8 tests, 53 assertions), including the new sampled-span exemplar test. Used the existing PHP 8.5.10 dependency/toolchain installation with a temporary autoloader pointing at this PR's sources. The full telemetry suite exited 139 in transport tests; this matches the limitation described in the PR, but I did not independently rerun the full suite on main. No source changes made.

…refreshed at collection

Review of the observable gauges found two holes. The closures captured the
breaker strongly and both telemetry adapters accumulate callbacks per
instrument, so every discarded breaker stayed alive and kept reporting, and
rebinding an adapter registered again without releasing the old one. And the
callbacks read the local snapshot, so an idle breaker kept reporting a
verdict another process had since changed.

One observation per adapter and metric prefix now walks a WeakMap of the
breakers bound to it: a discarded breaker drops out of collection and is not
retained, a breaker bound twice reports once, and moving to another adapter
removes it from the first. The state, failures and successes callbacks
refresh the shared snapshot from the cache adapter before reporting, without
applying the open timeout, so collecting telemetry never moves the circuit.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@loks0n

loks0n commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Both points addressed in 55837b1.

Callback lifecycle. The breaker no longer registers closures over $this. One observation per telemetry adapter and metric prefix is registered the first time a breaker binds to that adapter, and it walks a WeakMap of the breakers bound to it. A discarded breaker drops out of collection and is not retained (asserted with WeakReference after unset + GC), setTelemetry() twice on the same adapter leaves one callback and one series, and rebinding to another adapter removes the breaker from the first. Covered by testObservationsFollowTheBreakerLifecycle.

Shared state at collection. The state, failures and successes callbacks call syncFromCache() before reporting, so an idle breaker publishes a circuit another process tripped or recovered. updateState() is not run there, so collection never applies the open timeout and moves the circuit. Covered by testIdleBreakerObservesTheSharedState with two breakers on one array adapter: the idle one reports 1 after the other calls trip(), and stays open.

Side note from writing the test: Rector's unused-variable rule dropped $idle and the breaker was collected before the first observation, which is the lifecycle working as intended, so the test now holds it and asserts isOpen() at the end.

bin/monorepo check circuit-breaker and bin/monorepo test circuit-breaker pass.

@loks0n
loks0n merged commit d18c75c into main Sep 16, 2026
20 of 21 checks passed

This branch had an error being deployed

1 failed deployment
vcs — 55837b1c Deployed Sep 16, 2026 by loks0n via test (vcs, linked) #984
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