Skip to content

feat(backendtrafficpolicy): support targeting Service, ServiceImport, or Backend directly (merged clusters only) - #9816

Merged
zhaohuabing merged 66 commits into
envoyproxy:mainfrom
muwaqar:backend-target-btp-phase2
Oct 9, 2026
Merged

zhaohuabing merged 66 commits into
envoyproxy:mainfrom
muwaqar:backend-target-btp-phase2

Conversation

@muwaqar-cflt

@muwaqar-cflt muwaqar-cflt commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it:

BackendTrafficPolicy can now target a Service, ServiceImport, or Backend directly, instead of only a Gateway, Listener, or route.

Today, applying a setting like a circuit breaker or health check to every route that talks to a given backend means attaching (and keeping in sync) the same BackendTrafficPolicy on every route that references it, or setting it broadly at the Gateway level and accepting that it applies to everything else too. With this change, you attach the policy once, directly to the backend, and it applies wherever that backend resolves to a merged Envoy cluster (via the MergeBackends feature) - no matter how many routes or gateways reference it - without touching the routes themselves.

What you get:

  • Target a Service, ServiceImport, or Backend with spec.targetRefs.
  • Set the usual cluster-scoped fields once - load balancing, circuit breakers, health checks, timeouts, TCP keepalive, proxy protocol, HTTP/2 settings, DNS, and admission control.
  • ConsistentHash load balancing is rejected for backend-targeted policies: Envoy's hash policy for weighted-cluster selection is route-scoped and singular, so it doesn't make sense for different backends in the same weighted route to each request a different hash input.

Scope note: this policy applies only to backends that actually resolve into a shared, merged Envoy cluster. A backend that never merges for any reason (a fallback backend, session persistence, per-listener ClusterSettings divergence, a dynamic resolver, etc.) silently does not get the policy applied - no error, no warning. An earlier iteration of this PR also supported applying the policy to non-merged/inline backends, plus a route-vs-backend precedence resolution for that case; that inline path kept surfacing correctness hazards (most recently, a route-scoped ConsistentHash policy demerging via a mechanism a same-day guard had already missed once), so it was removed in favor of this smaller, unconditionally-correct surface. See muwaqar#12 for a reference-only copy of the removed inline work.

Requires mergeType to be set on the policy, and the MergeBackends feature enabled on the EnvoyProxy resource for the Gateway(s) involved.

Which issue(s) this PR fixes:

Fixes #8844


PR Checklist

  • Authorship & ownership: Coding agents / AI assistants are welcome, but I have reviewed every change, understand how and why it works, can explain and maintain it, and take full responsibility for this PR. I have not submitted generated output I do not understand.
  • DCO: All commits are signed off (git commit -s).
  • API agreed first: This PR adds fields under /api (backend-targeting support on BackendTrafficPolicy, plus a CEL rule rejecting ConsistentHash for backend targets). Tracked by Backend-level policy for CDS configuration #8844; not otherwise pre-agreed with maintainers beyond that issue.
  • Required checks pass: make generate gen-check, go build ./..., go vet ./..., go test ./..., and make go.test.cel all pass locally.
  • Tests added/updated: Golden fixture coverage across internal/gatewayapi and internal/xds/translator, plus CEL validation test cases.
  • Docs: No site/ docs update included in this PR yet.
  • Release notes: Added under release-notes/current/new_features/.
  • Generated files committed: make gen-check clean.
  • Scope & compatibility: Additive only, no breaking changes.
  • Codex review: Fixed.
  • Copilot review: Not yet requested.

@muwaqar-cflt
muwaqar-cflt requested a review from a team as a code owner August 21, 2026 16:46
@netlify

netlify Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

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

Name Link
🔨 Latest commit 874e078
🔍 Latest deploy log https://app.netlify.com/projects/cerulean-figolla-1f9435/deploys/6ac72d3cce3b260008f2cf1d
😎 Deploy Preview https://deploy-preview-9816--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.

@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: 676d0b3446

ℹ️ 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".

@codecov

codecov Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.97531% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.54%. Comparing base (9570ff0) to head (874e078).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
internal/gatewayapi/backendtrafficpolicy.go 91.21% 13 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9816      +/-   ##
==========================================
+ Coverage   81.49%   81.54%   +0.05%     
==========================================
  Files         266      266              
  Lines       41390    41568     +178     
==========================================
+ Hits        33729    33897     +168     
- Misses       7660     7670      +10     
  Partials        1        1              

☔ 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.

@zhaohuabing
zhaohuabing requested review from arkodg and kkk777-7 August 22, 2026 12:46
@zirain

zirain commented Aug 25, 2026

Copy link
Copy Markdown
Member

Requires mergeType to be set on the policy, and the MergeBackends feature enabled on the EnvoyProxy resource for the Gateway(s) involved.

could we support this without MergeBackends enabled?
BTP1: target to HTTPRoute
BTP2: target to Gateway
BTP3: target to Service

BTP3 could be used across Gateway/GatewayClass, and could be merged/replaced by BTP1 or BTP2 if exists.

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

could we support this without MergeBackends enabled?

yes, and its also my preference, this feature is independently useful regardless of mergebackends. there was a discussion a few months ago to couple them but i do not remember the details off the top of my head. if the reviewers agree, i can relax this restriction, it would not be a big change on this pull request.

@zirain

zirain commented Aug 27, 2026

Copy link
Copy Markdown
Member

could we support this without MergeBackends enabled?

yes, and its also my preference, this feature is independently useful regardless of mergebackends. there was a discussion a few months ago to couple them but i do not remember the details off the top of my head. if the reviewers agree, i can relax this restriction, it would not be a big change on this pull request.

could we support this without MergeBackends enabled?

yes, and its also my preference, this feature is independently useful regardless of mergebackends. there was a discussion a few months ago to couple them but i do not remember the details off the top of my head. if the reviewers agree, i can relax this restriction, it would not be a big change on this pull request.

cc @envoyproxy/gateway-maintainers

@zhaohuabing

zhaohuabing commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

could we support this without MergeBackends enabled?

I recall @arkodg had some concerns on this.

Users may naturally attach traffic policies to a Backend when they opt to create one cluster per Backend, since that Cluster is shared across multiple route rules. However, if Envoy Gateway creates a separate cluster for each route rule, attaching traffic policies to Routes may feel more intuitive.

@zirain

zirain commented Aug 28, 2026

Copy link
Copy Markdown
Member

could we support this without MergeBackends enabled?

I recall @arkodg had some concerns on this.

Users may naturally attach traffic policies to a Backend when they opt to create one cluster per Backend, since that Cluster is shared across multiple route rules. However, if Envoy Gateway creates a separate cluster for each route rule, attaching traffic policies to Routes may feel more intuitive.

traffic policies attach to Routes take precedence over policies attach to Service.

One benififit I could image for this, is we didn't need to expose ClusterSettings to the clusters used by non-Routes(thought we already do these a lot in the past).

@zhaohuabing

zhaohuabing commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

A backend-targeted policy's settings take precedence over a route-level policy's settings for the same backend and the same fields; everything else the route already configured is left alone.

For the following policies at different levels:

# Platform team — conservative org-wide default
btp-gateway   → Gateway/gateway-1        circuitBreaker.maxConnections: 100

# App team — this route is high-traffic, deliberately raised
btp-route     → HTTPRoute/http-route-1   circuitBreaker.maxConnections: 5000
                mergeType: StrategicMerge

# Someone later — unrelated keepalive tuning for one backend
btp-backend   → Service/service-1        tcpKeepalive.probes: 3
                mergeType: StrategicMerge

Note btp-backend says nothing about circuit breakers.

The result

        traffic:                      # route level — the app team's override held
          circuitBreaker:
            maxConnections: 5000
...
            traffic:                  # what service-1's cluster actually gets
              circuitBreaker:
                maxConnections: 100   # <-- back to the platform default
              tcpKeepalive:
                probes: 3

The result contradicts the intended behavior described in the PR.

@zirain

zirain commented Sep 2, 2026

Copy link
Copy Markdown
Member

A backend-targeted policy's settings take precedence over a route-level policy's settings for the same backend and the same fields; everything else the route already configured is left alone.

with MergeBackend=false, we're excepted BTP-route > BTP-gateway > BTP-service.

One more question: What will happen if I have a BTP target to the service used by accesslog(with backendSettings configed), merge or replace?

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@zhaohuabing Thanks for flagging this — you found a real bug in how backend-targeted policy interacted with gateway-level policy on the inline (non-merged-cluster) path. It's fixed now, with a golden test (mergebackends-btp-backend-target-route-precedence-preserves-route-override) covering your exact scenario so it can't regress.

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@zirain On precedence: the implemented and agreed order, from most specific to least specific, is Backend, then Route, then Gateway — Backend overrides Route, and Route overrides Gateway. This was confirmed with @arkodg, @zhaohuabing, and @guydc in a community meeting on June 25. It also matches Gateway API's own GEP-713 attachment hierarchy, which places Backend as the lowest/most-specific node in the DAG (GatewayClass → Gateway → Route → Backend) — meaning Backend-scoped policy is expected to override Route- and Gateway-scoped policy for whatever fields it sets. Happy to link the exact GEP wording if that's useful for the thread.

@muwaqar-cflt
muwaqar-cflt force-pushed the backend-target-btp-phase2 branch from 79bacdf to 06eba4b Compare September 3, 2026 15:28
@zirain

zirain commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

@zirain On precedence: the implemented and agreed order, from most specific to least specific, is Backend, then Route, then Gateway — Backend overrides Route, and Route overrides Gateway. This was confirmed with @arkodg, @zhaohuabing, and @guydc in a community meeting on June 25. It also matches Gateway API's own GEP-713 attachment hierarchy, which places Backend as the lowest/most-specific node in the DAG (GatewayClass → Gateway → Route → Backend) — meaning Backend-scoped policy is expected to override Route- and Gateway-scoped policy for whatever fields it sets. Happy to link the exact GEP wording if that's useful for the thread.

this's OK for MergeBackend=true, what will happen for telemetry and ratelimit service, the Backend BTP take precedence?

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

what will happen for telemetry and ratelimit service, the Backend BTP take precedence?

i know we did not support those code paths for MergeBackends feature, i am unsure their status for Backend-BTP, will have to trace the code next week and confirm. but either they are not supported for Backend-BTP or most likely if they are then there is no route there and Backend-BTP just combines with Gateway-BTP for them. but this is just a top off the head response.

@zirain

zirain commented Sep 4, 2026

Copy link
Copy Markdown
Member

/retest

muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 9, 2026
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 9, 2026
…e target backend

processBackendTrafficPolicyForBackend iterated every gateway and reported a
Disabled ancestor for any of them with mergeBackends off, regardless of
whether that gateway's IR referenced the policy's target backend at all. In
a cluster with many gateways this could displace real ancestor entries once
the 16-ancestor cap kicks in. Add gatewayReferencesBackend and only check it
inside the mergeBackends-disabled branch, so the common (enabled) path
doesn't pay for a second walk over the same IR the walks below it already
traverse.

Found by Codex review on envoyproxy#9816.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt and others added 3 commits October 7, 2026 23:12
…rotocol

processBackendTrafficPolicyForBackend copied the full ClusterTrafficFeatures
onto every matching merged cluster regardless of its protocol, so HTTP-only
fields (healthCheck, http2, admissionControl, ...) could leak onto a
udp_proxy/tcp_proxy cluster. Reuse applyGatewayPolicyToMergedCluster, which
already subsets correctly per protocol for the whole-gateway BTP path (added
in envoyproxy#10016 for the same bug class).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
…icy's targets

A multi-targetRefs backend-targeted BackendTrafficPolicy had each target
write Accepted/Conflicted/Disabled status directly and independently to the
same policy.Status, with no coordination between targets sharing an
ancestor. SetResolveErrorForPolicyAncestors (used for Conflicted/Disabled/
Invalid) has no guard against overwriting an already-set Accepted
condition, unlike SetAcceptedForPolicyAncestor - so whichever target was
processed last for a shared ancestor won, and in the worst order a
genuinely Accepted result could be silently clobbered by an unrelated
target's Conflicted/Disabled/error outcome for the same ancestor.

Split processBackendTrafficPolicyForBackend into a pure per-target resolver
(now returns a backendTargetOutcome instead of writing status) and a new
processBackendTargetedPolicies wrapper that owns the per-policy loop over
targets, aggregates accepted/merged/failed outcomes across all of a
policy's targets, then commits one status entry per ancestor - walking
gateways in their given order for a deterministic result, and never
regressing an ancestor another target already got accepted for.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
…eded

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
…us message

Per envoyproxy#9816 (comment):
backend targeting only resolves targetRef/targetRefs
(resolvePolicyTargetsFromReferences), so a BackendTrafficPolicy using
targetSelectors with kind Service/ServiceImport/Backend was previously
accepted by the API and then silently had no effect, with no status
feedback.

Rejects it in Go instead of CEL, avoiding the CEL cost-budget problem a
dedicated rejection rule would hit (api/v1alpha1/backendtrafficpolicy_types.go
already has two rules traversing the shared TargetSelectors field, and a
third pushes the CRD over budget). Resolves the selector against live
Service/ServiceImport/Backend objects purely to find which ancestor
Gateways to report a resolve error to - the same resolvePolicyTargetsFromSelectors
function already used for Gateway/ListenerSet selector targeting elsewhere,
not a new mechanism - the match is never applied.

Real selector support is tracked as a follow-up:
envoyproxy#10212

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-08T07:40:59.616663Z 874e078 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…pattern

The multi-targetRefs status aggregation added in 892a4fd was not one of
zirain's three blocking comments (protocol subsetting, MergeGateways,
targetSelectors) - it was a secondary comment this session chose to fix
proactively. On reflection, it introduced bespoke behavior found nowhere
else in this file: all six other BackendTrafficPolicy target-kind sections
(RouteRule, Route, ListenerSet Listener, ListenerSet, Gateway Listener,
Gateway) write status directly per-target with no aggregation across a
policy's multiple targets, accepting the same "last processed wins"
ordering this aggregation tried to fix only for backend targeting.

Reverts processBackendTrafficPolicyForBackend to writing status directly
(keeping the unrelated protocol-subsetting fix from 557e4d7), removes
processBackendTargetedPolicies/backendTargetOutcome/backendTargetFailure,
and restores the plain per-target loop in ProcessBackendTrafficPolicies -
matching the other six sections' exact shape. rejectBackendTargetSelectors
now writes status directly too, for the same reason.

Tracked as a cross-cutting follow-up covering all seven sections, not a
backend-targeting-specific fix: envoyproxy#10214

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
Fixes a prealloc lint failure in CI.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>
@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

@zirain @zhaohuabing This should be ready for re-review now:

  • Protocol subsetting, MergeGateways, and targetSelectors (your three blockers) are addressed — see the resolved threads above for details on each.
  • The multi-targetRefs status aggregation I'd added was reverted after further discussion — it introduced behavior inconsistent with how the other six BackendTrafficPolicy target-kind sections in this file already work, so it's tracked as a cross-cutting follow-up instead: BackendTrafficPolicy multi-target status can clobber another target's result for a shared ancestor #10214
  • All other review comments are either resolved, or filed as tracked follow-ups (linked in their respective threads) where non-blocking and out of scope for this PR.
  • CI is green aside from two confirmed-flaky conformance jobs unrelated to this diff (cluster-provisioning timeout fetching GatewayClass, and an unrelated BackendTLSPolicy SAN test timeout).
  • Codex review couldn't complete — it's erroring internally on its own side ("An unknown error occurred") on every retry, not flagging anything about the PR itself.

Would appreciate a re-review and +1 when you get a chance. Thanks for your patience on this one!

@zirain

zirain commented Oct 8, 2026

Copy link
Copy Markdown
Member

/retest

@zhaohuabing
zhaohuabing requested a review from zirain October 8, 2026 08:58

@guydc guydc 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 for this fantastic work!

@zhaohuabing
zhaohuabing merged commit b7653dd into envoyproxy:main Oct 9, 2026
75 of 78 checks passed
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Oct 19, 2026
…-scoped field errors

A BackendTrafficPolicy's cluster-scoped settings (circuit breaker, load
balancer, timeout, etc.) failed to apply to a merged backend cluster
whenever any route-scoped field (e.g. a broken rateLimit) failed to
translate, even though the cluster-scoped fields themselves were valid.
This affected both the whole-Gateway BTP path and the backend-targeted
BTP merge path added in envoyproxy#9816.

Extract buildClusterTrafficFeatures to build and error on only the
cluster-scoped subset, and gate cluster application on that error
instead of the combined one.

Fixes envoyproxy#10210

Signed-off-by: Muhammad Waqar <[email protected]>
zhaohuabing pushed a commit that referenced this pull request Oct 20, 2026
…-scoped field errors (#10234)

* fix(backendtrafficpolicy): isolate cluster-scoped settings from route-scoped field errors

A BackendTrafficPolicy's cluster-scoped settings (circuit breaker, load
balancer, timeout, etc.) failed to apply to a merged backend cluster
whenever any route-scoped field (e.g. a broken rateLimit) failed to
translate, even though the cluster-scoped fields themselves were valid.
This affected both the whole-Gateway BTP path and the backend-targeted
BTP merge path added in #9816.

Extract buildClusterTrafficFeatures to build and error on only the
cluster-scoped subset, and gate cluster application on that error
instead of the combined one.

Fixes #10210

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

* gatewayapi: generalize comment to route-scoped field, not just RateLimit

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

---------

Signed-off-by: Muhammad Waqar <[email protected]>
Co-authored-by: zirain <[email protected]>
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.

Backend-level policy for CDS configuration

4 participants