Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions docs/architecture-decisions/sync-server-keepalive-enforcement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
# Valid statuses: draft | proposed | rejected | accepted | superseded
status: proposed
author: Jason Benedicic (@jabenedicic)
created: 2026-07-14
updated: 2026-07-14
Comment thread
jabenedicic marked this conversation as resolved.
Resolved
---
# gRPC keepalive enforcement on the flag-sync server

The flag-sync gRPC server currently sets no keepalive enforcement policy, so it
inherits grpc-go's defaults, which are tuned for generic request/response RPC
rather than a long-lived streaming sync. Clients that ping to keep the sync
stream alive can be disconnected with `GOAWAY ENHANCE_YOUR_CALM`. This ADR
proposes setting a streaming-appropriate enforcement policy on the server, with
sane defaults and operator-facing overrides.
Tracking issue: [#1998](https://github.com/open-feature/flagd/issues/1998).

## Background

flagd's in-process mode has providers consume a long-lived `SyncFlags` gRPC
stream from the flag-sync server. gRPC clients keep such streams healthy by
sending periodic keepalive pings, especially during idle periods when no flag
changes are flowing.

gRPC servers enforce a *keepalive enforcement policy* that decides how often a
client is allowed to ping. grpc-go's default is `MinTime: 5m` with
`PermitWithoutStream: false`: a client may ping at most once every five minutes,
and only while it has an active stream. A client that exceeds this — pings more
often, or pings during a gap with no active RPC — accrues "ping strikes", and
after a small number the server sends `GOAWAY` with `ENHANCE_YOUR_CALM` /
`too_many_pings` and closes the connection. Those defaults suit short unary RPC
traffic; they are a poor fit for a service whose primary job is a long-lived,
often-idle stream.

The flag-sync server is constructed with a bare `grpc.NewServer(...)` and no
enforcement policy, so it inherits those defaults. Provider SDKs choose their
own keepalive cadence, and several ping far more frequently than every five
minutes to detect dead connections quickly. The Go provider is the clearest
example — it pings every 30s with `PermitWithoutStream: true` and exposes no
override — so it is disconnected roughly every 60–90s and must reconnect. This
is not specific to one provider: any client, in any language, whose keepalive
interval is shorter than five minutes is exposed to the same teardown, and there
is no server-side setting today to widen the tolerance.

## Requirements

* The flag-sync server must tolerate the keepalive cadences that provider SDKs
use in practice, without emitting `GOAWAY ENHANCE_YOUR_CALM`.
* The fix must apply to every client language, not one provider.
* The policy must be operator-configurable (CLI flag and environment variable),
so deployments can tune it without a code change.
* The default must not regress any client that works against flagd today.

## Considered Options

* Set a fixed, streaming-appropriate enforcement policy on the server, exposed
via CLI flags / environment variables (chosen).
* Set a fixed enforcement policy on the server with no configuration surface.
* Change each language provider's client keepalive settings instead of the
server.
* Leave the server on grpc-go's defaults (status quo).

## Proposal

Set a `KeepaliveEnforcementPolicy` on the flag-sync gRPC server, configurable
through two new options with defaults chosen to match how providers actually
keep the stream alive:

* `--keep-alive-min-time` (env `FLAGD_KEEP_ALIVE_MIN_TIME`, duration, default
`30s`) — the minimum interval the server permits between client keepalive
pings.
* `--keep-alive-permit-without-stream` (env
`FLAGD_KEEP_ALIVE_PERMIT_WITHOUT_STREAM`, bool, default `true`) — whether the
server permits pings while the client holds no active stream.

The `30s` default matches the tightest keepalive cadence a shipped provider uses
today; because a ping sent every 30s arrives at the server `30s + RTT` apart, it
clears a 30s minimum with margin. `PermitWithoutStream: true` is required
because providers ping during idle gaps when, transiently, no stream is active.
Both defaults are strictly more permissive than grpc-go's `5m` /
`PermitWithoutStream: false`, so any client that works against flagd today
continues to work; clients that were being disconnected stop being disconnected.

Choosing the server as the point of control is deliberate. Keepalive enforcement
is a property of the server — it is the party that decides how often a client
may ping — so the server is the correct and complete place to fix a
too-aggressive default. The alternative, changing keepalive in each provider,
would require coordinated releases across every provider repository, would not
help third-party or future clients, and would leave the server rejecting
reasonable keepalives out of the box. One server-side change covers every client
in every language.

### API changes

Two new CLI flags on `flagd start`, with matching `FLAGD_`-prefixed environment
variables, documented in the auto-generated CLI reference. No changes to the
gRPC or flag-configuration APIs. No wire-format or schema changes.

### Consequences

* Good, because a single server-side change resolves `ENHANCE_YOUR_CALM`
disconnects for every provider language at once, at the layer that owns the
policy.
* Good, because the defaults are more permissive than grpc-go's, so no
currently-working client regresses.
* Good, because deployments — including operator-managed flagd — can tune the
policy through environment variables or arguments on the flagd container,
giving estate-wide, cross-language keepalive tuning from one place, without
editing any gRPC client in any workload.
* Bad, because it adds two configuration options to the flagd surface that
operators may need to understand.
* Bad, because a misconfigured very-low `--keep-alive-min-time` could let a
misbehaving client ping more aggressively than intended; the default is
conservative and this is opt-in.

### Open questions

* Should the OpenFeature Operator expose these as first-class `Flagd` CRD fields,
or is passing them through container env/args sufficient? (Follow-up; out of
scope for this change.)
Comment thread
jabenedicic marked this conversation as resolved.
Resolved

## More Information

* grpc-go keepalive documentation:
<https://github.com/grpc/grpc-go/blob/master/Documentation/keepalive.md>
* Keepalive enforcement and `ENHANCE_YOUR_CALM`:
<https://github.com/grpc/grpc/blob/master/doc/keepalive.md>
2 changes: 2 additions & 0 deletions docs/reference/flagd-cli/flagd_start.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ flagd start [flags]
-C, --cors-origin strings CORS allowed origins, * will allow all origins
--disable-sync-metadata Disables the getMetadata endpoint of the sync service. Defaults to false, but will default to true in later versions.
-h, --help help for start
--keep-alive-min-time duration Minimum interval the flag sync gRPC server permits between client keepalive pings. Pings arriving more frequently than this are rejected with GOAWAY (ENHANCE_YOUR_CALM). Defaults to 30s. (default 30s)
--keep-alive-permit-without-stream Permit clients of the flag sync gRPC server to send keepalive pings even when there is no active stream. Defaults to true. (default true)
-z, --log-format string Set the logging format, e.g. console or json (default "console")
-m, --management-port int32 Port for management operations (default 8014)
-B, --max-request-body int Maximum allowed request body size in bytes. Requests exceeding this are rejected with HTTP 413 (OFREP) or 429 (connect). Set to 0 to disable. WARNING: disabling this limit may allow memory exhaustion from oversized requests. (default 1000000)
Expand Down
53 changes: 31 additions & 22 deletions flagd/cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ const (
streamDeadlineFlagName = "stream-deadline"
maxRequestBodyFlagName = "max-request-body"
maxRequestHeaderFlagName = "max-request-header"

keepAliveMinTimeFlagName = "keep-alive-min-time"
keepAlivePermitWithoutStreamFlagName = "keep-alive-permit-without-stream"
)

func init() {
Expand Down Expand Up @@ -96,6 +99,8 @@ func init() {
flags.Bool(disableSyncMetadata, false, "Disables the getMetadata endpoint of the sync service. Defaults to false, but will default to true in later versions.")
flags.Int64P(maxRequestBodyFlagName, "B", 1_000_000, "Maximum allowed request body size in bytes. Requests exceeding this are rejected with HTTP 413 (OFREP) or 429 (connect). Set to 0 to disable. WARNING: disabling this limit may allow memory exhaustion from oversized requests.")
flags.Int64P(maxRequestHeaderFlagName, "R", 1_000_000, "Maximum allowed request header size in bytes. Requests exceeding this are rejected with HTTP 431. Set to 0 to use Go's built-in default (1 MiB). WARNING: setting a very large or zero value may allow memory exhaustion from oversized headers.")
flags.Duration(keepAliveMinTimeFlagName, 30*time.Second, "Minimum interval the flag sync gRPC server permits between client keepalive pings. Pings arriving more frequently than this are rejected with GOAWAY (ENHANCE_YOUR_CALM). Defaults to 30s.")
flags.Bool(keepAlivePermitWithoutStreamFlagName, true, "Permit clients of the flag sync gRPC server to send keepalive pings even when there is no active stream. Defaults to true.")

bindFlags(flags)
}
Expand Down Expand Up @@ -124,6 +129,8 @@ func bindFlags(flags *pflag.FlagSet) {
_ = viper.BindPFlag(disableSyncMetadata, flags.Lookup(disableSyncMetadata))
_ = viper.BindPFlag(maxRequestBodyFlagName, flags.Lookup(maxRequestBodyFlagName))
_ = viper.BindPFlag(maxRequestHeaderFlagName, flags.Lookup(maxRequestHeaderFlagName))
_ = viper.BindPFlag(keepAliveMinTimeFlagName, flags.Lookup(keepAliveMinTimeFlagName))
_ = viper.BindPFlag(keepAlivePermitWithoutStreamFlagName, flags.Lookup(keepAlivePermitWithoutStreamFlagName))
}

// startCmd represents the start command
Expand Down Expand Up @@ -190,28 +197,30 @@ var startCmd = &cobra.Command{

// Build Runtime -----------------------------------------------------------
rt, err := runtime.FromConfig(logger, Version, runtime.Config{
CORS: viper.GetStringSlice(corsFlagName),
MetricExporter: viper.GetString(metricsExporter),
ManagementPort: viper.GetUint16(managementPortFlagName),
OfrepServicePort: viper.GetUint16(ofrepPortFlagName),
OtelCollectorURI: viper.GetString(otelCollectorURI),
OtelCertPath: viper.GetString(otelCertPathFlagName),
OtelKeyPath: viper.GetString(otelKeyPathFlagName),
OtelReloadInterval: viper.GetDuration(otelReloadIntervalFlagName),
OtelCAPath: viper.GetString(otelCAPathFlagName),
ServiceCertPath: viper.GetString(serverCertPathFlagName),
ServiceKeyPath: viper.GetString(serverKeyPathFlagName),
ServicePort: viper.GetUint16(portFlagName),
ServiceSocketPath: viper.GetString(socketPathFlagName),
SyncServicePort: viper.GetUint16(syncPortFlagName),
SyncServiceSocketPath: viper.GetString(syncSocketPathFlagName),
StreamDeadline: viper.GetDuration(streamDeadlineFlagName),
DisableSyncMetadata: viper.GetBool(disableSyncMetadata),
SyncProviders: syncProviders,
ContextValues: contextValuesToMap,
HeaderToContextKeyMappings: headerToContextKeyMappings,
MaxRequestBodyBytes: maxRequestBodyBytes,
MaxRequestHeaderBytes: maxRequestHeaderBytes,
CORS: viper.GetStringSlice(corsFlagName),
MetricExporter: viper.GetString(metricsExporter),
ManagementPort: viper.GetUint16(managementPortFlagName),
OfrepServicePort: viper.GetUint16(ofrepPortFlagName),
OtelCollectorURI: viper.GetString(otelCollectorURI),
OtelCertPath: viper.GetString(otelCertPathFlagName),
OtelKeyPath: viper.GetString(otelKeyPathFlagName),
OtelReloadInterval: viper.GetDuration(otelReloadIntervalFlagName),
OtelCAPath: viper.GetString(otelCAPathFlagName),
ServiceCertPath: viper.GetString(serverCertPathFlagName),
ServiceKeyPath: viper.GetString(serverKeyPathFlagName),
ServicePort: viper.GetUint16(portFlagName),
ServiceSocketPath: viper.GetString(socketPathFlagName),
SyncServicePort: viper.GetUint16(syncPortFlagName),
SyncServiceSocketPath: viper.GetString(syncSocketPathFlagName),
StreamDeadline: viper.GetDuration(streamDeadlineFlagName),
DisableSyncMetadata: viper.GetBool(disableSyncMetadata),
KeepAliveMinTime: viper.GetDuration(keepAliveMinTimeFlagName),
KeepAlivePermitWithoutStream: viper.GetBool(keepAlivePermitWithoutStreamFlagName),
SyncProviders: syncProviders,
ContextValues: contextValuesToMap,
HeaderToContextKeyMappings: headerToContextKeyMappings,
MaxRequestBodyBytes: maxRequestBodyBytes,
MaxRequestHeaderBytes: maxRequestHeaderBytes,
})
if err != nil {
rtLogger.Fatal(err.Error())
Expand Down
6 changes: 6 additions & 0 deletions flagd/pkg/runtime/from_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ type Config struct {
StreamDeadline time.Duration
DisableSyncMetadata bool

KeepAliveMinTime time.Duration
KeepAlivePermitWithoutStream bool

SyncProviders []sync.SourceConfig
CORS []string

Expand Down Expand Up @@ -137,6 +140,9 @@ func FromConfig(logger *logger.Logger, version string, config Config) (*Runtime,
StreamDeadline: config.StreamDeadline,
DisableSyncMetadata: config.DisableSyncMetadata,
MetricsRecorder: recorder,

KeepAliveMinTime: config.KeepAliveMinTime,
KeepAlivePermitWithoutStream: config.KeepAlivePermitWithoutStream,
})
if err != nil {
return nil, fmt.Errorf("error creating sync service: %w", err)
Expand Down
52 changes: 32 additions & 20 deletions flagd/pkg/service/flag-sync/sync_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
)

type ISyncService interface {
Expand All @@ -27,17 +28,19 @@ type ISyncService interface {
}

type SvcConfigurations struct {
Logger *logger.Logger
Port uint16
Sources []string
Store store.IStore
ContextValues map[string]any
CertPath string
KeyPath string
SocketPath string
StreamDeadline time.Duration
DisableSyncMetadata bool
MetricsRecorder telemetry.IMetricsRecorder
Logger *logger.Logger
Port uint16
Sources []string
Store store.IStore
ContextValues map[string]any
CertPath string
KeyPath string
SocketPath string
StreamDeadline time.Duration
DisableSyncMetadata bool
MetricsRecorder telemetry.IMetricsRecorder
KeepAliveMinTime time.Duration
KeepAlivePermitWithoutStream bool
}

type Service struct {
Expand Down Expand Up @@ -65,26 +68,35 @@ func loadTLSCredentials(certPath string, keyPath string) (credentials.TransportC
return credentials.NewTLS(config), nil
}

// keepAliveEnforcementPolicy builds the gRPC keepalive enforcement policy so
// provider keepalive pings on the long-lived SyncFlags stream aren't rejected
// with GOAWAY ENHANCE_YOUR_CALM.
func keepAliveEnforcementPolicy(cfg SvcConfigurations) keepalive.EnforcementPolicy {
return keepalive.EnforcementPolicy{
MinTime: cfg.KeepAliveMinTime,
PermitWithoutStream: cfg.KeepAlivePermitWithoutStream,
}
}

func NewSyncService(cfg SvcConfigurations) (*Service, error) {
var err error
l := cfg.Logger

var server *grpc.Server
serverOpts := []grpc.ServerOption{
grpc.StatsHandler(otelgrpc.NewServerHandler()),
grpc.KeepaliveEnforcementPolicy(keepAliveEnforcementPolicy(cfg)),
}

if cfg.CertPath != "" && cfg.KeyPath != "" {
tlsCredentials, err := loadTLSCredentials(cfg.CertPath, cfg.KeyPath)
if err != nil {
return nil, fmt.Errorf("failed to load TLS cert and key: %w", err)
}
server = grpc.NewServer(
grpc.Creds(tlsCredentials),
grpc.StatsHandler(otelgrpc.NewServerHandler()),
)
} else {
server = grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()),
)
serverOpts = append(serverOpts, grpc.Creds(tlsCredentials))
}

server := grpc.NewServer(serverOpts...)

metricsRecorder := cfg.MetricsRecorder
if metricsRecorder == nil {
metricsRecorder = &telemetry.NoopMetricsRecorder{}
Expand Down
Loading
Loading