Skip to content

feat: add MergeBackends option for backend cluster deduplication - #9477

Merged
arkodg merged 12 commits into
envoyproxy:mainfrom
muwaqar:backend-cluster-dedup-rebase
Jul 30, 2026
Merged

arkodg merged 12 commits into
envoyproxy:mainfrom
muwaqar:backend-cluster-dedup-rebase

Conversation

@muwaqar-cflt

@muwaqar-cflt muwaqar-cflt commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it:

Adds an opt-in EnvoyProxy.spec.mergeBackends option: routes referencing the identical backend can share a single Envoy cluster instead of Envoy Gateway generating one cluster per route rule. This reduces xDS size, active health-check traffic, and stats cardinality on gateways with many routes fanning out to a small set of shared backends. Disabled by default and marked experimental.

Cluster sharing is skipped wherever it would be unsafe:

  • multi-backendRef rules using session persistence, ConsistentHash load balancing, or a fallback backend (all need the full backend pool kept together in one cluster, not split per identity)
  • dynamic-resolver/custom (extension-provided) backends
  • a backendRef carrying any per-backendRef filter (e.g. CredentialInjection, header modification) or a UseClientProtocol override, both of which are baked into the shared cluster rather than the per-route destination
  • a route-rule/route/listener-level BackendTrafficPolicy setting a cluster-scoped field
  • a listener-level ClientTrafficPolicy setting a cluster-affecting field (e.g. HTTP/1 settings)
  • a RoutingType diverging from the gateway's baseline
  • TCP/UDP/TLS rules with more than one backendRef, since those route types have no way to represent a rule split across more than one cluster

mergeGateways and mergeBackends cannot both be enabled (CEL-enforced) — supporting that combination added complexity around a mode that may eventually be deprecated in favor of ListenerSet.

Gateway-level BackendTrafficPolicy Traffic features (circuit breaker, health check, timeout, etc.) now apply correctly to merged BackendClusters too — previously they were silently dropped for any merged cluster.

Approach: enabling this required restructuring how a route's backend data is stored. Previously, every RouteDestination embedded its own copy of the resolved DestinationSettings, so two routes sharing a backend could never share anything at the IR level - deduplication had nowhere to attach. This PR introduces a per-gateway backend cluster registry (ir.Xds.BackendClusters, ir.BackendCluster): each distinct, merge-eligible backend is resolved once, and its RouteDestination holds a BackendClusterRef (a name) into that registry instead of its own settings. A single rule's backendRefs can be a mix of both — some merge-eligible (via BackendClusterRefs), others not (kept in Settings) — merge eligibility is decided per-backendRef, not per-rule.

Beyond enabling MergeBackends, this registry is what makes a future backend-level BackendTrafficPolicy straightforward: since a backend's settings now live in exactly one place instead of being copied into every route that references it, a policy targeting the backend directly can be applied once at the registry entry, rather than needing to be threaded through and reconciled across every route-level copy.

Reviewer notes: this is a large diff; start here:

  • api/v1alpha1/envoyproxy_types.go - the new user-facing MergeBackends/MergeBackendsConfig field
  • internal/ir/xds.go - the BackendCluster/BackendClusterRef types, the Xds.BackendClusters registry, and BackendCluster.Traffic
  • internal/gatewayapi/route.go - processBackendRef is the single entry point every route type (and the RequestMirror filter) uses to resolve a backendRef's destination and cluster assignment together. It wraps shouldMergeBackend/mergeIncompatibleForWeightedRule/mergeIncompatibleForSingleClusterRule (own the full eligibility decision, split by whether the route type supports weighted-cluster route actions), backendClusterKey/backendClusterKeyForGateway (build the registry cache key), and getOrCreateBackendCluster (the find-or-create registry lookup)
  • internal/gatewayapi/backendtrafficpolicy.go / clienttrafficpolicy.go - BuildBTPIndexes/BuildCTPIndexes (build the per-target eligibility indexes used by the checks above) and translateBackendTrafficPolicyForGateway (populates BackendCluster.Traffic from the accepted whole-gateway policy)
  • internal/xds/translator/backend_registry.go - registry resolution (resolveBackendClusters, routeDestinationSettings, needsRouteCluster) consumed by the HTTP/GRPC route-action and TCP/UDP listener builders, and cluster.go's cluster-per-setting/weight logic and BackendClusterTranslator

A good portion of the remaining diff is golden testdata: internal/gatewayapi/testdata/*.out.yaml fixtures re-derived to reflect destinations serializing as backendClusterRefs + a top-level backendClusters: registry instead of inline settings:, plus new fixtures (mergebackends-* in internal/gatewayapi/testdata, merge-backends-* in internal/xds/translator/testdata) covering the merge-eligibility rules above at both the IR-building layer and the xDS translation layer - several of the latter are derived directly from the former's real output, tracing a single Gateway API resource all the way through to the generated Envoy config.

Known, accepted limitations (discussed in review, tracked separately):

  • A merged cluster's active HTTP health check falls back to Envoy's default (cluster name) as its Host header when the health check has no explicit hostname — merging never applies a route's own hostname to a shared cluster, since it isn't necessarily invariant across the routes sharing it.
  • EnvoyProxy.spec.telemetry.metrics.clusterStatName (alt_stat_name) is dropped for merged clusters rather than applied, since it's a single per-route pattern with no way to express merged-cluster behavior. Tracked in Merging backends drops alt_stat_name (EnvoyProxy clusterStatName) for merged clusters #9570.
  • A route-rule/route-level BackendTrafficPolicy that leaves mergeType unset is not currently treated as a merge-disqualifying signal by itself — only an explicit cluster-scoped field is checked. Since an unset mergeType discards its resolved parent's settings entirely, a sibling route inheriting from that same parent can end up with different resolved Traffic settings than this one, even though neither route's own policy sets a cluster-scoped field directly. Fix is in progress on a separate branch, staged behind BackendTrafficPolicy RoutingType ignores MergeType, always inherits from broader-scoped policies #9541.

Which issue(s) this PR fixes:
Fixes #5307, #9541

@netlify

netlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for cerulean-figolla-1f9435 ready!

Name Link
🔨 Latest commit f536cd0
🔍 Latest deploy log https://app.netlify.com/projects/cerulean-figolla-1f9435/deploys/6a6b6fc0ca9d3a00087e844a
😎 Deploy Preview https://deploy-preview-9477--cerulean-figolla-1f9435.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

/retest

@codecov

codecov Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.34954% with 43 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.03%. Comparing base (7c3e11b) to head (f536cd0).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
internal/ir/xds.go 81.35% 6 Missing and 5 partials ⚠️
internal/xds/translator/translator.go 83.92% 4 Missing and 5 partials ⚠️
internal/gatewayapi/route.go 97.43% 5 Missing and 3 partials ⚠️
internal/xds/translator/route.go 82.22% 4 Missing and 4 partials ⚠️
internal/gatewayapi/backendtrafficpolicy.go 97.05% 2 Missing and 2 partials ⚠️
internal/gatewayapi/clienttrafficpolicy.go 96.00% 1 Missing and 1 partial ⚠️
internal/gatewayapi/runner/runner.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9477      +/-   ##
==========================================
+ Coverage   75.75%   76.03%   +0.28%     
==========================================
  Files         254      259       +5     
  Lines       42322    43275     +953     
==========================================
+ Hits        32059    32906     +847     
- Misses       8107     8177      +70     
- Partials     2156     2192      +36     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@muwaqar-cflt
muwaqar-cflt force-pushed the backend-cluster-dedup-rebase branch from d5cbd23 to 0f5efab Compare July 13, 2026 00:32
Comment thread internal/gatewayapi/route.go Resolved
@muwaqar-cflt
muwaqar-cflt marked this pull request as ready for review July 13, 2026 09:23
@muwaqar-cflt
muwaqar-cflt requested a review from a team as a code owner July 13, 2026 09:23

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6011972ddb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/xds/translator/route.go Resolved
@zhaohuabing

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 31fbfa0fa5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/gatewayapi/route.go Resolved
Comment thread api/v1alpha1/envoyproxy_types.go Resolved
Comment thread internal/gatewayapi/route.go Resolved
Comment thread api/v1alpha1/envoyproxy_types.go Resolved
Comment thread api/v1alpha1/envoyproxy_types.go Outdated
//
// +optional
// +kubebuilder:default=false
Enabled *bool `json:"enabled,omitempty"`

@zhaohuabing zhaohuabing Jul 17, 2026 •

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 may want to default this to true eventually. The fallback approach won't break current user-facing routing behaviors, and it helps with the Envoy memory issue.

It may be too risky to turn this on by default in 1.9, as it does break EPPs and extension servers, but we could keep it opt-in for the first release and consider flipping the default in 1.10 after we have more coverage and user feedback.

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.

resolving because not seeing an action item for now.

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 keep it unresolved for now, so other reviewer can see and discuss on this. cc @arkodg @guydc

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.

is this flag needed ? mergeBackends: {} should imply we are turning on the feature

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.

yeah, not necessarily. A bool flag is more explicit than mergeBackends: {}, I'm fine with both.

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.

i like an explicit flag, mergeBackends: {} looks odd

@arkodg arkodg Jul 26, 2026 •

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.

our existing APIs already follows the pattern mentioned

ProxyProtocol *ProxyProtocolSettings `json:"proxyProtocol,omitempty"`

  • also http3
  • TLS session resumption similarly uses empty stateless: {} / stateful: {}
    an explicit enabled is not needed 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.

Looking into dropping Enabled entirely (so a present, even empty mergeBackends: {} means enabled, absent means disabled) rather than defaulting it to true later.

One tradeoff to flag before I make the change: today Enabled: false at a more-specific level (a Gateway-level EnvoyProxy override, or GatewayClass-level vs. the config-wide default) lets you explicitly opt back out of an ancestor level's true. Two existing tests exercise exactly that (TestShouldMergeBackend's "enabled globally, but Gateway-level EnvoyProxy disables it" and TestIsMergeBackendsEnabled's "gatewayclass envoyproxy takes precedence over default spec" disable case). Removing Enabled removes that capability too — once presence alone means "on," there's no way to represent "explicitly off" at a level that would otherwise inherit "on" from below.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

mergeBackends: null in the child could solve this ?

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.

null value is indistinguishable from not being set at all. a quick AI lookup says there may be some ways to make it work +kubebuilder:validation:Nullable but I do not have much knowledge there.

either way I am sensing strong opposition to Enabled right now, and potentially add the relevant capability (disablement on a granular scope overriding the broader one) later if a need arises. so I will make changes to remove Enabled.

@zhaohuabing
zhaohuabing requested a review from a team July 17, 2026 08:59
@cnvergence

Copy link
Copy Markdown
Member

lint fails :(

Comment thread internal/gatewayapi/route.go Resolved
@zhaohuabing

Copy link
Copy Markdown
Member

This PR looks good. Great work!

I left a few minor comments.

@muwaqar-cflt Could you please fix the link and check whether all e2e tests pass? I’d like to get this merged before 1.9.0 if possible. Thanks!

…bility rules

Introduces a per-gateway backend cluster registry (BackendClusterMap,
Xds.BackendClusters): each distinct, merge-eligible backend is resolved
once via processBackendRef/getOrCreateBackendCluster, and its
RouteDestination holds a BackendClusterRef into that registry instead of
its own settings. A single rule's backendRefs can be a mix of both - some
merge-eligible, others not - merge eligibility is decided per-backendRef,
not per-rule.

shouldMergeBackend owns the eligibility decision, gated on (in order): the
gateway's effective MergeBackends setting, the backend's kind (custom and
dynamic-resolver backends never merge), per-backendRef filters, and a set
of rule/route/listener-level indexes built once per Translate() call:

  - BTPClusterSettingsIndex / CTPClusterSettingsIndex: whether a
    route-rule/route/listener-level BackendTrafficPolicy or
    ClientTrafficPolicy sets a cluster-scoped field (circuit breaker,
    health check, load balancer, HTTP1 settings, etc.) that would
    incorrectly apply to every route sharing a merged cluster if merged.
    ClientTrafficPolicy targets are resolved against both Gateway and
    ListenerSet objects; gateway-wide/listenerSet-wide settings that apply
    uniformly across everything they cover are exempted, since a merged
    cluster can never see them diverge.
  - BTPRoutingTypeIndex / BTPLoadBalancerIndex: RoutingType divergence
    from the gateway's baseline, and ConsistentHash load balancing on a
    multi-backendRef rule, both of which require the full backend pool
    kept together rather than split per identity.
  - mergeIncompatibleForWeightedRule / mergeIncompatibleForSingleClusterRule:
    session persistence, a fallback backend, and (for TCP/UDP/TLS, which
    have no weighted-clusters mechanism) any rule with more than one
    backendRef.

Gateway-level BackendTrafficPolicy Traffic features (circuit breaker,
health check, timeout, UseClientProtocol, etc.) are applied to every
merged BackendCluster once accepted, since gateway level is the only one
guaranteed uniform across a merged cluster's routes.

Signed-off-by: Muhammad Waqar <[email protected]>
…/SDS building

processMergedBackendClusters builds the Envoy Cluster and client-cert
secrets for each distinct merged backend cluster in xdsIR.BackendClusters,
once. buildXdsRouteAction/buildXdsWeightedRouteAction resolve a route's
BackendClusterRefs against a name-keyed backendClusterIndex alongside its
own Settings, so a single weighted rule can route across a mix of merged
and non-merged clusters. processSDSClusters scans xdsIR.BackendClusters
directly for SDS URLs rather than re-resolving each merged cluster's
settings once per referencing route.

Signed-off-by: Muhammad Waqar <[email protected]>
Two routes referencing the same backend both route correctly, and Envoy
generates a single deduplicated Cluster for that backend instead of one
per route; a third route with its own rule-level BackendTrafficPolicy
setting a cluster-scoped field keeps its own separate Cluster, proving the
demerge direction as well as the merge direction.

Signed-off-by: Muhammad Waqar <[email protected]>
…lvedMetricSinks

Unrelated drive-by fix: iterate by index and take the address instead of
copying each ResolvedMetricSink by value on every loop iteration.

Signed-off-by: Muhammad Waqar <[email protected]>
…envoyproxy#9184/envoyproxy#9030 SDS changes

main's new TLSRoute dynamic-resolver support referenced a destSettings
variable that doesn't exist on this branch, which renamed it to
allDs/backendClusterRefs earlier in this branch's own history. git's 3-way
merge combined the two without a textual conflict, silently producing
code that failed to compile. Adapt the check to use allDs (a dynamic
resolver is never merge-eligible, so it can only appear there) while
counting both allDs and backendClusterRefs for the single-destination
requirement.

Signed-off-by: Muhammad Waqar <[email protected]>
…unset route policies

envoyproxy#9588: a route/rule-targeted BackendTrafficPolicy
with mergeType unset that sets no cluster-scoped field of its own
still incorrectly inherits a shared cluster's gateway-level Traffic,
since merge-eligibility here only checks for an explicit
cluster-scoped field, not whether the policy merges with a parent at
all.

Signed-off-by: Muhammad Waqar <[email protected]>
…ckends

Mirrors the existing MergeGateways *bool precedent: mergeBackends being
set at all (even empty) now enables cluster deduplication, so there is
no separate on/off toggle to get out of sync with field presence. This
also simplifies the mergeGateways/mergeBackends mutual-exclusion CEL
rule to a presence check.

Signed-off-by: Muhammad Waqar <[email protected]>
@muwaqar-cflt
muwaqar-cflt force-pushed the backend-cluster-dedup-rebase branch from 8a29608 to 2cc4d16 Compare July 29, 2026 16:59
arkodg
arkodg previously approved these changes Jul 30, 2026

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

LGTM thanks, this feature should help increase adoption for users who were previously concerned with xDS cluster duplication

@zhaohuabing

Copy link
Copy Markdown
Member

@muwaqar-cflt let's merge instead of rebase when resolving conflicts - it's easier to review after the conflicts are fixed. Thanks!

# Conflicts:
#	internal/gatewayapi/backendtrafficpolicy.go
#	internal/gatewayapi/backendtrafficpolicy_test.go
#	internal/gatewayapi/route.go
#	internal/gatewayapi/runner/runner.go
#	internal/gatewayapi/translator.go
@muwaqar-cflt
muwaqar-cflt dismissed stale reviews from arkodg and zhaohuabing via 3fa3b0d July 30, 2026 14:50
EnvoyGatewayKubernetesInfrastructureConfiguration's introduction (envoyproxy#9027) left
one composite literal missing its closing brace, breaking go vet/go test for
this package.

Signed-off-by: Muhammad Waqar <[email protected]>
…nationToProto

Our BackendClusterRefs field addition to ir.RouteDestination pushed the
struct to 80 bytes, tripping gocritic's hugeParam check on this by-value
param inherited from main's remote-infrastructure-provider work.

Signed-off-by: Muhammad Waqar <[email protected]>
@zhaohuabing

Copy link
Copy Markdown
Member

Hi @muwaqar-cflt Do we need to handle ListenerSet in the indexes? Or do you plan to handle it in a follow-up PR?

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

Hi @muwaqar-cflt Do we need to handle ListenerSet in the indexes? Or do you plan to handle it in a follow-up PR?

ListenerSet feature came in from main pretty late. its too late to handle it for now since we want this merged for 1.9 but I can look into it when fixing #9588

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

Let's merge this and try to fix #9619 and #9588 before 1.9.0 is out.

@arkodg
arkodg merged commit 0e77573 into envoyproxy:main Jul 30, 2026
39 of 44 checks passed
zhaohuabing added a commit to zhaohuabing/gateway that referenced this pull request Jul 30, 2026
Resolved the conflict in internal/gatewayapi/route.go against envoyproxy#9477
(MergeBackends cluster deduplication): kept main's processBackendRef-based
destination handling and re-applied the PathRegex host rewrite guard in both
processHTTPRouteRules and processGRPCRouteRules.

Also adapted the new TestBuildXdsURLRewriteAction_PathRegexHostRewrite case to
buildXdsURLRewriteAction's new backendClusterIndex parameter.

Signed-off-by: Huabing (Robin) Zhao <[email protected]>
zhaohuabing added a commit that referenced this pull request Aug 3, 2026
PR #9532 added initialFetchTimeout to RDS/SDS config sources and regenerated
the testdata present on its branch. PRs #9477 (MergeBackends) and #8836 (CSRF)
were generated before #9532 and added new golden files that lack the field.
Both merged without a textual conflict, leaving main red on gen-check.

Regenerate the affected golden files.

Signed-off-by: Huabing (Robin) Zhao <[email protected]>
@muwaqar-cflt
muwaqar-cflt deleted the backend-cluster-dedup-rebase branch August 5, 2026 14:58
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.

Revisit Kubernetes Services mapping to Envoy v3.Cluster

6 participants