Repository navigation
Description
Problem
When an MCPServer has backendReplicas > 1, the proxy runner stores the ClusterIP service URL (e.g. http://mcp-<name>:8080) as backend_url in session metadata. After a proxy runner restart, it recovers the session from Redis but routes via ClusterIP — kube-proxy may send the request to a backend pod that never handled the initialize for that session.
The backend pod returns HTTP 404 with JSON-RPC -32001 ("session not found") because it has no record of that session. The mcp-go client surfaces this as:
transport error: failed to send request: session terminated (404). need to re-initialize
The session is not actually terminated — it simply doesn't exist on the pod that received the request.
Parent issue: #4484
Failing acceptance test
PR #4574 adds an E2E test that demonstrates this bug. It fails on all 3 Kubernetes versions in CI:
Error from CI (v1.35.1):
[FAILED] Request 1/5 should succeed — session should route to the correct backend
Unexpected error:
transport error: failed to send request: session terminated (404). need to re-initialize
In [It] at: mcpserver_scaling_test.go:382
Test flow
- Deploy MCPServer with
replicas=1,backendReplicas=2, Redis session storage,sessionAffinity=None - Initialize MCP session, call
tools/list— succeeds - Delete the proxy runner pod (Deployment recreates it)
- Send 5
tools/listrequests with the same session ID — fails on request 1
With 2 backends and random routing, P(all 5 hit correct pod) ≈ 3%.
Root cause
-
StatefulSet
serviceNamemismatch:buildStatefulSetSpecsetsserviceNametocontainerName, but the headless service is namedmcp-<containerName>-headless. These must match for Kubernetes to create pod DNS records. -
ClusterIP stored as
backend_url:RoundTripstorestargetURI(ClusterIP) asbackend_url. After restart,Rewriteroutes via ClusterIP withsessionAffinity=None, hitting a random backend.
Proposed fix
Store a pod-specific headless DNS URL (e.g. myserver-0.mcp-myserver-headless.default.svc.cluster.local:8080) as backend_url instead of the ClusterIP:
- Fix StatefulSet
serviceNameto match headless service name - Add
HeadlessServiceConfigtoScalingConfig - Pre-select a random StatefulSet pod on initialize, store its headless DNS as
backend_url - Operator populates config when
backendReplicas > 1 - Backward compatible: when config is nil (single backend), behavior is unchanged
Activity
Route MCP sessions to specific StatefulSet pods via headless DNS
Route MCP sessions to specific StatefulSet pods via headless DNS
Route MCP sessions to specific StatefulSet pods via headless DNS
Route MCP sessions to specific StatefulSet pods via headless DNS
Route MCP sessions to specific StatefulSet pods via headless DNS
JAORMX commentedon Apr 8, 2026
Heads up: while reviewing #4638, we found some fundamental issues with the headless service it builds on top of (wrong selector target, StatefulSet serviceName mismatch, random pod selection after initialize). Opened #4668 to track rethinking the headless service before we add more plumbing on top.
yrobla commentedon Apr 8, 2026
Proposed fix: per-pod ClusterIP services
After reviewing the current approach (headless DNS routing) with the team, we identified a security concern: storing pod-specific headless DNS URLs in Redis leaks internal cluster topology and allows bypassing the proxy's auth middleware from within the cluster. Since the headless service is also going to be removed, here's the proposed replacement.
Approach
The operator creates one ClusterIP service per backend pod ordinal alongside the existing shared service:
Each per-pod service uses the label Kubernetes automatically assigns to StatefulSet pods:
The proxy runner computes the ordinal deterministically from the session ID:
Why this is better
statefulset.kubernetes.io/pod-nameselector are well-supported and widely usedbackendReplicasscales, same as today's shared serviceChanges required
createPerPodServicesthat creates one ClusterIP service per ordinal up tobackendReplicas; delete excess services on scale-downHeadlessServiceConfigwith aBackendServiceConfigcarrying the base service name (mcp-<name>-pod) and replica countfnv32(sessionID) % replicasand store nothing — just forward to the right per-pod serviceJAORMX commentedon Apr 8, 2026
So, I've been looking at this issue and the proposed fixes, and I think we need to take a step back here.
Both proposals (headless DNS routing and per-pod ClusterIP services) share a fundamental problem: they create infrastructure that exposes backend pods outside the proxy runner. The headless DNS approach puts pod-specific addresses in Redis and makes them resolvable from anywhere in the cluster. The per-pod services create addressable endpoints that bypass the proxy's auth/authz/audit middleware entirely. For stdio servers this is a non-starter since the proxy runner IS the only HTTP endpoint... but even for SSE/streamable-http, we should never bypass the proxy runner. That's the whole point of the architecture.
Also, the
fnv32(sessionID) % replicasidea doesn't actually work for the initialize flow. At initialize time there IS no session ID yet. The backend creates it. Per the MCP spec (both 2025-03-26 and 2025-11-25):And:
So you can't deterministically route the initialize to a specific pod based on the session ID. It doesn't exist yet.
Note that the sticky session work we already landed (ClientIP affinity on the backend service via #3992, Redis session storage via #4525) covers most of this. The gap is specifically: when the proxy runner restarts, it gets a new pod IP, so the L4 ClientIP affinity mapping to the backend is lost. The session is in Redis, but
backend_urlpoints to the ClusterIP service URL, which doesn't help route to the right pod.The fix should be way simpler than what's proposed here. The
backend_urlsession metadata mechanism already works perfectly... it just stores the wrong value. Go'snet/http/httptracepackage gives us aGotConncallback that fires after kube-proxy DNAT.info.Conn.RemoteAddr()returns the actual pod IP that handled the connection. So:httptrace.ClientTracewithGotConnto capture the resolved pod IPhttp://<pod-ip>:<port>asbackend_urlinstead of the ClusterIP URLRewritefunction already readsbackend_urland overrides the outbound URLAll traffic still flows through the proxy runner. No new Kubernetes resources. No new bypass vectors. ~30 lines of code in
transparent_proxy.go."But what if the backend pod restarts and gets a new IP?" Well... the backend's in-memory MCP session state is gone too. The client has to re-initialize regardless. The proxy should handle the stale IP gracefully (connection refused or 404 → clear session from Redis → client re-initializes → new pod IP captured). This isn't a new failure mode.
For environments with frequent backend pod churn, we can add an EndpointSlice watcher as a follow-up that maps pod IPs to stable StatefulSet ordinals. But that's an optimization, not the fix.
yrobla commentedon Apr 8, 2026
Reviewed the httptrace approach — it solves the problem cleanly. The proxy runner stays fully in the path: pod IPs are only used on the proxy's outbound leg (inside the
Rewriteclosure), never visible to clients.One thing worth adding on top: when the outbound connection to a stored pod IP fails (connection refused, reset, etc.), the proxy should clear
backend_urlfrom the session — or delete the session entirely — so the client receives a clean 404/503 and knows to reinitialize, rather than retrying against a stale address. Without this, a backend pod restart leaves the session in a permanently broken state in Redis until TTL expiry.yrobla commentedon Apr 8, 2026
in the case of backend restarting, it will loose the ip and get a new one. In this case we do not have to return 404 , but instead reinitialize and create a new session
yrobla commentedon Apr 8, 2026
Final implementation decision
After the discussion above, we are going with JAORMX's
httptraceapproach as the foundation. This section captures the full implementation plan that will be used.Core mechanism —
GotConnpod IP captureUse Go's
net/http/httptracepackage to intercept the resolved pod IP after kube-proxy DNAT completes:initializerequest, attach anhttptrace.ClientTracewith aGotConncallback to the outbound request context.GotConn, readinfo.Conn.RemoteAddr()— this is the actual backend pod IP kube-proxy resolved to.http://<pod-ip>:<port>asbackend_urlin Redis for that session.Rewritefunction already readsbackend_urland overrides the outbound URL — no changes needed there.All traffic continues to flow through the proxy runner. No new Kubernetes resources, no new bypass vectors. ~30 lines of code in
transparent_proxy.go.Backend restart handling — transparent re-initialization instead of 404
This is the key addition on top of JAORMX's approach.
When the proxy attempts to forward a request to a stored pod IP and the connection fails (connection refused, connection reset, TCP timeout), it means the backend pod has been rescheduled and now holds a different IP. In this case:
backend_url).backend_urlfrom the session in Redis, then issues a freshinitializerequest against the ClusterIP service (no pod IP — kube-proxy picks a healthy pod).GotConncallback fires again, capturing the new pod IP, which is stored back into Redis as the updatedbackend_url.This handles the primary failure mode: proxy runner restart causes
backend_urlto still be valid in Redis, but the backend pod that originally served the session has since been replaced.Changes required
pkg/proxy/transparent_proxy.go(or equivalent transport layer)RoundTrip: oninitialize, wrap the request context withhttptrace.NewClientTrace/context.WithValue; in theGotConncallback captureinfo.Conn.RemoteAddr().String()and pass it out (via a pointer or channel) to be stored asbackend_url.Rewrite(or equivalent pre-send hook): detect dial/connection errors against the storedbackend_url; on failure, clearbackend_urlfrom Redis and trigger re-initialization as described above before retrying once.Session storage (Redis)
backend_urlalready exists and is already used. This PR only changes what value is written to it and adds the stale-detection + clear logic.Operator / Kubernetes resources
HeadlessServiceConfig/BackendServiceConfigstructs are all dropped. The operator continues to create only the shared ClusterIP service, as today.Acceptance criteria
tools/listrequest with an existing session ID succeeds without the client needing to reinitialize.backendReplicas=2andsessionAffinity=None, all requests for a given session ID consistently reach the same backend pod (the one that handledinitialize).backendReplicas=1) are unaffected — behavior is unchanged.What is explicitly out of scope
mcp-<name>-pod-N): rejected due to bypass risk.serviceNameissues identified in Remove or rethink the MCP backend headless service #4668.This is the approach we will implement. Closing the headless service track (#4668) is a prerequisite to avoid conflicting work.
Route MCP sessions to the originating backend pod using httptrace
Route MCP sessions to the originating backend pod using httptrace
Route MCP sessions to the originating backend pod using httptrace
Route MCP sessions to the originating backend pod using httptrace (#4673