Skip to main content
Back to all articles
AI Engineering 9 min read

If Replica B Can't Handle the Next MCP Request, Your Server Isn't Stateless Yet

MCP 2026-07-28 removed protocol sessions, but horizontal scaling only works when your application stops depending on replica-local state. Design around replica invariance, externalized workflow state, MRTR, idempotency, and header-aware routing.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#MCP#Model Context Protocol#Distributed Systems#Horizontal Scaling#MRTR#TypeScript#Python#AI Agents#Reliability
On this page

The easiest way to tell whether an MCP server is actually ready to scale is not to inspect its Kubernetes manifest.

Send one request to replica A.

Send the next one to replica B.

Then kill replica A.

If the workflow still behaves correctly, you are getting close.

If the second request says “unknown session,” loses a pending interaction, forgets who the client is, or repeats a side effect, the deployment may have multiple pods but the application is still stateful in the place that matters.

That distinction became much more important with the 2026-07-28 Model Context Protocol specification. The protocol removed the old initialize / initialized exchange and the Mcp-Session-Id transport session. Requests are now self-describing, and the MCP maintainers explicitly designed the new core so a request can land on any instance behind ordinary round-robin load balancing.

That is a protocol capability, not an automatic property of your server.

I use a simpler invariant when reviewing an MCP service:

Replica invariance: no request should require knowledge that exists only inside the process that handled a previous request.

Once that invariant is true, autoscaling, rolling deploys, failover, and multi-region routing get dramatically less awkward.

The protocol became stateless. Your application may still have state.

“Stateless MCP” is easy to misunderstand as “the server must never store anything.”

That is not the goal.

A useful MCP server may still need database records, OAuth grants, audit events, long-running jobs, user preferences, or workflow progress. Those are application concerns. The problem is hidden continuity tied to one server process.

I separate state into four buckets:

StateExampleWhere it should live
Request stateparsed arguments, auth context, trace idcurrent request only
Durable application statecustomer record, workflow, job, artifactdatabase / durable store
Coordination stateidempotency key, lease, dedupe recordshared store with explicit semantics
Optimization stateparsed schema cache, connection pool, local memoizationreplica-local, but never required for correctness

The last row is important.

A replica can absolutely have memory. Database connection pools are local. Compiled validators are local. A hot cache can be local.

What I do not want is this:

Text
correctness = request payload + whatever replica A happens to remember

Correctness should survive a cold replica.

The stateful pattern usually hides in innocent code

A lot of stateful MCP implementations do not look like distributed systems code. They look like a harmless Map added when there was only one server process.

type PendingExport = {  accountId: string;  format: "csv" | "json";};​const pendingExports = new Map<string, PendingExport>();​export function beginExport(accountId: string) {  const operationId = crypto.randomUUID();​  pendingExports.set(operationId, {    accountId,    format: "csv",  });​  return { operationId };}​export function continueExport(operationId: string) {  const pending = pendingExports.get(operationId);​  if (!pending) {    throw new Error("Unknown export operation");  }​  return runExport(pending);}

It works perfectly in local development.

It also works in production while the load balancer happens to keep hitting the same instance.

Then autoscaling adds replica B and the assumption becomes visible.

The fix is not automatically “put the map in Redis.” Sometimes that is appropriate, but I first ask a more basic question:

Does this continuity belong to the transport, or is it actually application state?

If it is application state, model it that way.

Make continuity explicit

The 2026-07-28 MCP design intentionally moves away from transport sessions. If a workflow needs continuity across calls, I prefer an explicit application-level handle.

The tool returns an operationId. The next call sends that ID back. Any replica can load the operation from the system of record.

type ExportOperation = {  id: string;  accountId: string;  format: "csv" | "json";  status: "awaiting_format" | "ready" | "completed";};​interface ExportOperationStore {  create(operation: ExportOperation): Promise<void>;  get(id: string): Promise<ExportOperation | null>;  update(operation: ExportOperation): Promise<void>;}​export async function continueExport(  store: ExportOperationStore,  operationId: string,  format: "csv" | "json",) {  const operation = await store.get(operationId);​  if (!operation) {    throw new Error("Unknown export operation");  }​  operation.format = format;  operation.status = "ready";  await store.update(operation);​  return runExport(operation);}

Now replica A can create the operation and replica B can continue it.

More importantly, the state has a name, schema, lifetime, and ownership model. I can audit it, expire it, migrate it, and reason about it without pretending it is a transport session.

For very small continuation state, a signed client-carried token can also work. For larger, sensitive, revocable, or frequently updated state, I generally prefer an opaque ID pointing at server-side durable state. Stateless transport does not require stateless business logic.

MRTR changes the way mid-call interaction works

Removing a held-open session creates an obvious question: what happens when a tool needs more information from the client before it can finish?

The current MCP answer is Multi Round-Trip Requests (MRTR).

Under MCP 2026-07-28, server-to-client interactions such as elicitation are redesigned around a request/response pattern. When the server cannot finish yet, it can return an input_required result describing the input it needs. The client obtains that input and retries the original request with inputResponses.

The architectural change matters more than the JSON shape:

Text
old mental modelclient request ───────────────► replica A               replica A waitsclient response ◄─────────────► same live interaction​MRTR mental modelclient request ───────────────► replica Aclient ◄──── input_required ─── replica A​client gathers input​client retry + responses ─────► replica Bclient ◄────── result ───────── replica B

Replica B must be able to continue.

That means the information required to resume cannot exist only in replica A's memory.

For an application workflow, I like returning a small opaque operation handle rather than serializing half the world into a continuation token.

type InputRequiredResult = {  resultType: "input_required";  requestState: string;  inputRequests: Record<string, unknown>;};​async function requestExportFormat(  store: ExportOperationStore,  accountId: string,): Promise<InputRequiredResult> {  const operationId = crypto.randomUUID();​  await store.create({    id: operationId,    accountId,    format: "csv",    status: "awaiting_format",  });​  return {    resultType: "input_required",    requestState: operationId,    inputRequests: {      format: {        type: "elicitation",        message: "Export as CSV or JSON?",      },    },  };}

The exact SDK types will evolve with the SDK you use, so I keep protocol plumbing at the adapter boundary. The application service should care about “pause this operation and resume it later,” not about which transport revision delivered the input.

That separation also makes protocol migrations less invasive.

Stateless retries make idempotency non-negotiable

Once a request can be retried independently, side effects need an identity.

Consider a tool that charges an invoice, creates a cloud resource, sends an email, or writes a calendar event. A timeout does not tell the client whether the side effect failed or succeeded and the response was lost.

If the client retries and the tool simply runs again, horizontal scaling has turned a network problem into duplicate business operations.

I want an idempotency record shared by all replicas.

type IdempotencyRecord<T> = {  key: string;  status: "running" | "completed";  result?: T;};​interface IdempotencyStore<T> {  claim(key: string): Promise<"claimed" | "exists">;  get(key: string): Promise<IdempotencyRecord<T> | null>;  complete(key: string, result: T): Promise<void>;}​async function runOnce<T>(  store: IdempotencyStore<T>,  key: string,  action: () => Promise<T>,): Promise<T> {  const claim = await store.claim(key);​  if (claim === "exists") {    const existing = await store.get(key);    if (existing?.status === "completed") return existing.result as T;    throw new Error("Operation already in progress");  }​  const result = await action();  await store.complete(key, result);  return result;}

The claim operation must be atomic. In practice that could be a unique database constraint, a transactional insert, or an appropriate Redis primitive depending on the durability requirements.

The important design property is that two replicas racing on the same logical operation do not both execute the side effect.

Header-aware routing is useful, but it should not become hidden affinity

MCP 2026-07-28 also gives infrastructure more information at the HTTP layer. Streamable HTTP requests carry Mcp-Method and Mcp-Name, allowing gateways to route, meter, or authorize requests without parsing the JSON body.

That unlocks useful infrastructure policies:

Text
Mcp-Method: tools/list→ cheap read pool​Mcp-Method: tools/callMcp-Name: render_video→ compute-heavy pool​Mcp-Method: tools/callMcp-Name: delete_workspace→ stricter rate limit + authorization policy

I still avoid using those headers to recreate accidental session affinity.

Routing render_video to a compute pool is a capability decision.

Routing “client 123 must always return to pod 7 because pod 7 remembers something” is the old problem wearing a new load-balancer configuration.

The test remains the same: if the chosen replica disappears, can another eligible replica correctly handle the request?

Local caches are fine when a cache miss is boring

Stateless services do not need to ban local caches.

I use this rule:

If deleting the cache changes correctness, it is not just a cache.

A replica-local cache for parsed schemas is fine because a miss simply recompiles the schema.

A local map containing “which approval step this customer reached” is not fine because a miss changes the workflow.

The same rule works for warm model clients, database pools, DNS caches, feature metadata, and precomputed tool descriptions. Keep local state when it improves performance; do not make it part of the correctness proof.

Test replica invariance deliberately

A normal integration test can accidentally hide state coupling because every request hits the same in-process server.

I add a test that makes the replica switch explicit.

it("continues an MCP workflow on another replica", async () => {  const store = createSharedTestStore();  const replicaA = createServer({ replicaId: "a", store });  const replicaB = createServer({ replicaId: "b", store });​  const first = await replicaA.callTool("export_account", {    accountId: "acct_42",  });​  expect(first.resultType).toBe("input_required");​  // Deliberately resume on a different process boundary.  const second = await replicaB.callTool("export_account", {    accountId: "acct_42",    requestState: first.requestState,    inputResponses: { format: "json" },  });​  expect(second.resultType).toBe("complete");});

Then I make the test meaner.

Kill replica A between calls. Clear all local caches. Retry the second request twice. Run two copies concurrently. Roll the server version between steps.

Those cases find architecture bugs that a happy-path MCP client test will never expose.

Rolling deployments are where fake statelessness shows up

Horizontal scaling is often discussed as a traffic-spike feature, but I care just as much about deployments.

A truly replaceable replica makes a rollout ordinary:

Text
1. stop sending new requests to replica A2. let its current request finish3. terminate A4. start the new version5. route the next independent request wherever capacity exists

There is no protocol session to migrate.

There should also be no hidden application session to migrate.

Long-running work is a separate concern. If a tool starts a job that lasts minutes, I do not keep the HTTP worker alive and hope the pod survives. I enqueue durable work, return an application or Task handle, and let a worker system own execution. A web replica should be disposable even while business work continues elsewhere.

Observability should prove that requests move between replicas

Once I deploy multiple replicas, I want traces that make replica movement obvious rather than frightening.

A useful request event includes fields such as:

type McpRequestEvent = {  traceId: string;  replicaId: string;  protocolVersion: string;  method: string;  name?: string;  operationId?: string;  idempotencyStatus?: "claimed" | "replayed" | "in_progress";  durationMs: number;  outcome: "success" | "input_required" | "error";};

I do not want user prompts, access tokens, tool arguments, or MRTR responses automatically dumped into metric labels. High-cardinality and sensitive data belong in appropriately protected traces, not in every monitoring dimension.

A healthy distributed trace may show:

Text
request 1 → replica a → input_requiredrequest 2 → replica c → completedrequest 3 → replica b → replayed idempotent result

That is not instability. That is evidence the architecture is working.

What I would check before removing sticky sessions

Before switching a production MCP server to ordinary round-robin routing, I search the codebase for anything that assumes process continuity:

  • session maps and connection registries;
  • pending promises waiting for client input;
  • per-process workflow state;
  • side effects without idempotency protection;
  • authorization decisions cached as authoritative state;
  • local job queues;
  • WebSocket or SSE assumptions inherited from an older MCP transport;
  • cleanup hooks whose correctness depends on a specific pod seeing the next request.

Then I run the replica-invariance test against each multi-step tool.

Sticky sessions can be useful temporarily during a migration, and affinity can still be a performance optimization. I just do not want correctness to depend on them. If losing affinity breaks the tool, the migration is not finished.

A practical migration order

For an existing MCP server, I would migrate in this order:

First, separate application state from transport state. Name the workflows that genuinely need continuity and give them durable IDs.

Then remove replica-local correctness dependencies. Local caches can stay; local authoritative workflow maps cannot.

Make side effects idempotent before introducing aggressive retries. Otherwise the more resilient transport can make the business behavior less reliable.

Move interactive flows to MRTR. Treat input_required as a pause boundary that may resume on another server instance.

Route on the new MCP headers only for capability, policy, metering, or cost. Do not use them to reconstruct hidden sessions.

Finally, turn on round-robin distribution and actively kill replicas during tests. A stateless architecture should become easier to trust as instances disappear, not harder.

The part that matters

MCP 2026-07-28 removed a major source of protocol-level coupling. There is no longer a handshake-created transport session that forces a chain of requests back to the same server instance, and MRTR gives interactive flows a request/response shape that works with that stateless model.

But the protocol cannot delete your Map.

It cannot add idempotency to a tool that charges a credit card twice.

It cannot move a pending workflow out of pod memory.

It cannot tell Kubernetes that your “stateless” deployment secretly needs the same replica for the next call.

That part is architecture.

The production invariant I would keep is simple:

The next valid MCP request should be able to land on any eligible replica, including a replica that has never seen this client before.

When that is true, horizontal scaling stops being an MCP-specific trick. Your server starts behaving like a well-designed HTTP service: replicas are replaceable, state is explicit, retries are deliberate, and deployment topology becomes an operational choice instead of part of application correctness.

That is the real benefit of MCP going stateless.

References

KEEP READING

Related engineering notes