Skip to content

feat(sync): configurable gRPC keepalive enforcement on sync server - #1999

Merged
toddbaert merged 4 commits into
open-feature:mainfrom
jabenedicic:1998-feat-sync-keepalive-enforcement
Jul 16, 2026
Merged

toddbaert merged 4 commits into
open-feature:mainfrom
jabenedicic:1998-feat-sync-keepalive-enforcement

Conversation

@jabenedicic

Copy link
Copy Markdown
Contributor

This PR

Sets a streaming-appropriate gRPC keepalive enforcement policy on the flag-sync server, configurable via two new flags, so in-process providers stop being disconnected with GOAWAY ENHANCE_YOUR_CALM (too_many_pings).

Closes #1998.

Problem

The flag-sync service exposes a long-lived SyncFlags gRPC stream that in-process providers keep alive with periodic keepalive pings. The sync server is created with a bare grpc.NewServer(...) and no KeepaliveEnforcementPolicy, so it inherits grpc-go's defaults — MinTime: 5m, PermitWithoutStream: false — which are tuned for short unary RPC, not a long-lived, often-idle stream.

Any client pinging more often than every 5 minutes (or pinging during an idle gap with no active stream) accrues ping strikes, and the server responds with GOAWAY ENHANCE_YOUR_CALM and closes the connection. Provider SDKs choose their own cadence; the Go provider's in-process resolver pings every 30s with PermitWithoutStream: true and no override, so it is disconnected roughly every 60–90s. This is a server-side default mismatch that affects every client language, and there is no server-side setting to correct it today.

Why fix it on the server

Keepalive enforcement is the server's contract — the server decides how often a client may ping. Adjusting each provider's client keepalive instead would need coordinated releases across every provider repo, wouldn't help third-party or future clients, and would leave the server rejecting reasonable keepalives by default. One server-side change fixes every client, in every language, at the correct layer.

Change

New flags on flagd start (env vars auto-derived), applied to the flag-sync gRPC server:

Flag Env Type Default
--keep-alive-min-time FLAGD_KEEP_ALIVE_MIN_TIME duration 30s
--keep-alive-permit-without-stream FLAGD_KEEP_ALIVE_PERMIT_WITHOUT_STREAM bool true

The defaults are strictly more permissive than grpc-go's, so no client that works against flagd today regresses; clients that were being disconnected stop being disconnected. Because these are flags/env vars, deployments (including operator-managed flagd via container env/args) can tune keepalive tolerance for every consumer from one place, without editing any gRPC client.

An ADR is included at docs/architecture-decisions/sync-server-keepalive-enforcement.md.

Validation

Reproduced end to end with an in-process provider (Go provider v0.6.0, default 30s keepalive) against two builds of the sync server on :8015, identical in every other respect:

  • Before (this repo's main): server logs got too many pings from the client; client receives GoAway ... ENHANCE_YOUR_CALM ... "too_many_pings" at ~105s and the sync stream is torn down and retried.
  • After (this branch, default MinTime 30s): 0 GOAWAYs, 0 sync errors, stream stable for the full 4-minute window (2.4× past the point where main failed).

Test plan

  • make workspace-init && make test — passes (added a unit test for the config→policy mapping and a raw-HTTP/2 behavioural test that drives the server's enforcement directly: strict policy → GOAWAY ENHANCE_YOUR_CALM, permissive policy → healthy, pings-without-stream rejected when not permitted).
  • make lint — clean on the changed packages.
  • make generate-docs — regenerated CLI reference is committed.
  • make markdownlint — clean.

The flag-sync gRPC server was built without a KeepaliveEnforcementPolicy, so it
inherited grpc-go's generic-RPC defaults (MinTime 5m, PermitWithoutStream false).
In-process providers keep the long-lived SyncFlags stream alive with periodic
keepalive pings; any provider pinging more often than every five minutes is torn
down with GOAWAY ENHANCE_YOUR_CALM (too_many_pings). This is a server-side
default mismatch that affects every client language, and there is no server-side
setting to correct it today.

Set a streaming-appropriate enforcement policy on the sync server, configurable
via two new flags with sane, more-permissive defaults so no working client
regresses:

  --keep-alive-min-time (FLAGD_KEEP_ALIVE_MIN_TIME, default 30s)
  --keep-alive-permit-without-stream (FLAGD_KEEP_ALIVE_PERMIT_WITHOUT_STREAM, default true)

Add an ADR documenting the rationale and a raw-HTTP/2 behavioural test proving
the policy takes effect, alongside a unit test for the config-to-policy mapping.

Closes open-feature#1998

Signed-off-by: Jason Benedicic <[email protected]>
@jabenedicic
jabenedicic requested review from a team as code owners July 14, 2026 14:36
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 14, 2026
@netlify

netlify Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for polite-licorice-3db33c canceled.

Name Link
🔨 Latest commit 5ffd844
🔍 Latest deploy log https://app.netlify.com/projects/polite-licorice-3db33c/deploys/6a5926831ec1490008e49a03

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ee6bf077-8720-4bb8-b944-acb38ab173c6

📥 Commits

Reviewing files that changed from the base of the PR and between 6721b1a and 5ffd844.

📒 Files selected for processing (1)
  • flagd/pkg/service/flag-sync/sync_service_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • flagd/pkg/service/flag-sync/sync_service_test.go

📝 Walkthrough

Walkthrough

The flag-sync gRPC server gains configurable keepalive enforcement. New CLI and environment-backed settings flow through runtime configuration into the server, with documentation and HTTP/2 tests covering policy mapping and excessive-ping behavior.

Changes

Flag-sync keepalive enforcement

Layer / File(s) Summary
Keepalive configuration contract
docs/architecture-decisions/sync-server-keepalive-enforcement.md, docs/reference/flagd-cli/flagd_start.md
Documents the server enforcement policy and adds the two flagd start options with their defaults.
CLI to runtime configuration
flagd/cmd/start.go, flagd/pkg/runtime/from_config.go
Registers, binds, and propagates keepalive settings into the flag-sync service configuration.
Server enforcement policy
flagd/pkg/service/flag-sync/sync_service.go
Builds a gRPC keepalive enforcement policy and applies it to the sync server with existing telemetry and optional TLS options.
Policy and protocol validation
flagd/pkg/service/flag-sync/sync_service_test.go
Tests configuration mapping and HTTP/2 keepalive behavior, including detection of GOAWAY ENHANCE_YOUR_CALM.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant FlagdStart
  participant Runtime
  participant SyncService
  participant GRPCServer
  Operator->>FlagdStart: Set keepalive flags or environment variables
  FlagdStart->>Runtime: Populate KeepAliveMinTime and KeepAlivePermitWithoutStream
  Runtime->>SyncService: Pass SvcConfigurations
  SyncService->>GRPCServer: Install keepalive enforcement policy
  GRPCServer-->>SyncService: Enforce client ping behavior
Loading

Possibly related issues

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: configurable gRPC keepalive enforcement on the sync server.
Description check ✅ Passed The description is directly related to the changes and clearly explains the new keepalive enforcement behavior.
Linked Issues check ✅ Passed The changes satisfy #1998 by adding configurable keepalive policy, docs, ADR, and the required tests for the flag-sync server.
Out of Scope Changes check ✅ Passed The diff stays within the sync-server keepalive scope and does not introduce unrelated code changes.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
flagd/pkg/service/flag-sync/sync_service_test.go (1)

366-405: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Write errors in the ping-flood helper are silently swallowed.

The write closure (Line 367-371) discards every error from WriteSettings/WriteSettingsAck/WritePing via _ = fn(). If a write fails early (e.g., connection already torn down for an unrelated reason), the loop keeps “succeeding” silently and the function falls through to the final 2-second timeout, returning false — indistinguishable from a legitimately tolerant server. This can produce a misleading false-negative verdict instead of a clear test failure pointing at the real cause.

Consider surfacing/logging the error, or failing fast when a write errors:

🔧 Proposed fix to surface write failures
 	write := func(fn func() error) {
 		writeMu.Lock()
 		defer writeMu.Unlock()
-		_ = fn()
+		if err := fn(); err != nil {
+			t.Logf("floodKeepalivePings: write failed: %v", err)
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@flagd/pkg/service/flag-sync/sync_service_test.go` around lines 366 - 405,
Update the ping-flood helper’s write closure to surface errors from
framer.WriteSettings, framer.WriteSettingsAck, and framer.WritePing instead of
discarding them. Propagate the error to the surrounding test flow and fail fast
with a clear test failure, preserving the existing GOAWAY detection behavior for
successful writes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@flagd/pkg/service/flag-sync/sync_service_test.go`:
- Around line 275-338: The TestSyncServiceKeepAliveEnforcement subtests reuse
port 18017 without waiting for service.Start to stop after context cancellation.
Track the server goroutine and register cleanup that cancels the context and
waits for Start to exit before the next subtest begins.

---

Nitpick comments:
In `@flagd/pkg/service/flag-sync/sync_service_test.go`:
- Around line 366-405: Update the ping-flood helper’s write closure to surface
errors from framer.WriteSettings, framer.WriteSettingsAck, and framer.WritePing
instead of discarding them. Propagate the error to the surrounding test flow and
fail fast with a clear test failure, preserving the existing GOAWAY detection
behavior for successful writes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5bde5b1d-76ea-4f0a-b291-72d05019e275

📥 Commits

Reviewing files that changed from the base of the PR and between d99a3e3 and 9a9d011.

📒 Files selected for processing (6)
  • docs/architecture-decisions/sync-server-keepalive-enforcement.md
  • docs/reference/flagd-cli/flagd_start.md
  • flagd/cmd/start.go
  • flagd/pkg/runtime/from_config.go
  • flagd/pkg/service/flag-sync/sync_service.go
  • flagd/pkg/service/flag-sync/sync_service_test.go

Address review feedback on the keepalive enforcement tests:

- Wait for the sync server goroutine to exit (t.Cleanup cancels the context
  and waits for Start to return) before the next subtest reuses the port,
  removing a listener shutdown race.
- Extract dialWithRetry and watchForGoAway helpers from floodKeepalivePings to
  reduce its cognitive complexity below the threshold.

Signed-off-by: Jason Benedicic <[email protected]>
@jabenedicic

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 1492ba8 (tests only):

  • Port-reuse race (CodeRabbit): each subtest now waits for the sync server goroutine to exit via t.Cleanup (cancel context + wait for Start to return) before the next subtest reuses the port, removing the listener-shutdown race. Verified with go test -race -count=5.
  • Cognitive complexity (SonarCloud): extracted dialWithRetry and watchForGoAway helpers from floodKeepalivePings to bring it back under the threshold.

Intentionally not changed:

  • Docstring coverage warning: the added functions already carry doc comments; the reported 40% is dominated by table-driven test closures, and I didn't want to add noise comments to hit an arbitrary threshold on a test-heavy diff.
  • uint16(port) narrowing nit: port is a constant 18017, and this matches the existing pattern in the surrounding sync-service tests.

Note: the build workflow is still showing action_required — it looks like it needs a maintainer to approve running Actions for a first-time fork contributor. Happy to rebase or adjust anything else.

jabenedicic and others added 2 commits July 16, 2026 19:42
Trim the six-line doc comment flagged as too verbose in review down to
the essential rationale.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Jason Benedicic <[email protected]>
Move cancelFunc to a defer at the creation site to satisfy Sonar's
context-leak rule; keep the serverDone wait in cleanup so the listener is
released before the next subtest reuses the port. Deferred calls run
before t.Cleanup callbacks, so cancel still precedes the wait.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Jason Benedicic <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@toddbaert toddbaert left a comment

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.

Just for completeness, something we've found is that proxies and service meshes do not forward gRPC/HTTP2 keepalive/PING frames - they are a connection level thing, not a RPC-level thing. Due to this, you can have a healthy connection to an Envoy for instance, but that Envoy has dropped it's upstream connection to flagd, and you have no idea because the keepalives are still happily indicating the connection is healthy. 🙃

One of the recommendations we have is to use the streamDeadlineMs knob as a way to ensure streams are fresh - since new RPCs transit the intermediate proxy and keep the connection health accurate.

@toddbaert
toddbaert merged commit 19e57b9 into open-feature:main Jul 16, 2026
14 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 16, 2026
toddbaert pushed a commit that referenced this pull request Jul 27, 2026
🤖 I have created a release *beep* *boop*
---


<details><summary>flagd: 0.16.1</summary>

##
[0.16.1](flagd/v0.16.0...flagd/v0.16.1)
(2026-07-27)


### 🐛 Bug Fixes

* add server ReadTimeouts, update security deps
([#1980](#1980))
([0e1e8b3](0e1e8b3))
* handle invalid selector errors
([#1976](#1976))
([409a62e](409a62e))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))


### ✨ New Features

* **sync:** configurable gRPC keepalive enforcement on sync server
([#1999](#1999))
([19e57b9](19e57b9))
</details>

<details><summary>flagd-proxy: 0.9.7</summary>

##
[0.9.7](flagd-proxy/v0.9.6...flagd-proxy/v0.9.7)
(2026-07-27)


### 🐛 Bug Fixes

* add server ReadTimeouts, update security deps
([#1980](#1980))
([0e1e8b3](0e1e8b3))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))
</details>

<details><summary>core: 0.16.1</summary>

##
[0.16.1](core/v0.16.0...core/v0.16.1)
(2026-07-27)


### 🐛 Bug Fixes

* **certreloader:** re-check reload condition under write lock
([#1994](#1994))
([86489da](86489da))
* handle invalid selector errors
([#1976](#1976))
([409a62e](409a62e))
* readyz never true of multiple gRPC syncs are used
([#1985](#1985))
([29833e8](29833e8))
* **security:** update module google.golang.org/grpc to v1.82.1
[security] ([#2005](#2005))
([4281adf](4281adf))
* **security:** update vulnerability-updates [security]
([#1984](#1984))
([2a5a6b6](2a5a6b6))
* **sync:** avoid send on closed channel in fileinfo watcher Close
([#1992](#1992))
([a7339ea](a7339ea))
* **sync:** handle non-string YAML map keys in config parsing
([#1990](#1990))
([3c72e6f](3c72e6f))
* **sync:** re-establish file watch after delete and restore
([#2001](#2001))
([d434adf](d434adf))
* **sync:** synchronize readiness state
([#2006](#2006))
([317a7e0](317a7e0))


### ✨ New Features

* improve ETag and body hash support to blob/http sync
([#1991](#1991))
([1e210d4](1e210d4))


### 🧹 Chore

* fix flaky test
([7ff137d](7ff137d))
</details>

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Signed-off-by: OpenFeature Bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Configurable gRPC keepalive enforcement policy on the flag-sync server

2 participants