How to Scale MCP Servers?
From the publisher’s feed, collected in the ZeroLabs newsroom.
MCPs are gradually becoming more and more popular. And as it becomes popular so does the need for scaling MCP servers.MCP by its nature is transport independent, meaning it can work over any known transport protocol as long as the message structure remains intact. But for simplicity and practicality only two transports are majorly used: STDIO for local MCP communication and HTTP for remote MCP servers.How to setup a simple MCP Server?Before we learn to scale a MCP server, let’s learn how a basic MCP server works and set up a simple one.MCP by itself is a protocol that works on top of JSON-RPC. It defines how AI agents communicate with external tools and services. This protocol is widely supported by many modern LLM Agents and chatbots to call tools in a standardized way.An MCP server gives the agents a description of the tool and what it is capable of, it also gives you a streamable response which is very useful for LLM applications. Agents can use these descriptions to understand what tool to call and when to call.More info about MCPs hereSimple MCP Serverimport express from "express";import { randomUUID } from "node:crypto";import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";import { InMemoryEventStore } from "@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js";import { z } from 'zod';import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"const PORT = process.env.PORT || 3000;const server = new McpServer({ name: "streamable-mcp-server", version: "1.0.0",}, { capabilities: { tools: {}, logging: {} }});// Register a simple greeting toolserver.tool( 'greet', 'A simple greeting tool', { name: z.string().describe('Name to greet'), }, async ({ name }, extra) => { // First send the greeting as a notification await server.sendLoggingMessage({ level: 'info', data: `Hello, ${name}!`, }, extra.sessionId); // Send ping text for 10 seconds (one per second) const startTime = Date.now(); let pingCount = 0; while (Date.now() - startTime await new Promise(resolve => setTimeout(resolve, 1000)); pingCount++; await server.sendLoggingMessage({ level: 'info', data: 'pings text', }, extra.sessionId); } // Return final result return { content: [ { type: 'text', text: `Greeted ${name} and sent ${pingCount} pings`, }, ], }; });const app = express();app.use(express.json());const transports = {};// Handle POST requestsapp.post('/mcp', async (req, res) => { try { const sessionId = req.headers['mcp-session-id']; let transport; if (sessionId && transports[sessionId]) { transport = transports[sessionId]; } else if (!sessionId && isInitializeRequest(req.body)) { const eventStore = new InMemoryEventStore(); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), enableJsonResponse: true, eventStore, onsessioninitialized: (sessionId) => { transports[sessionId] = transport; } }); transport.onclose = () => { const sid = transport.sessionId; if (sid && transports[sid]) { delete transports[sid]; } }; await server.connect(transport); await transport.handleRequest(req, res, req.body); return; } else { res.status(400).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Bad Request: No valid session ID provided', }, id: null, }); return; } await transport.handleRequest(req, res, req.body); } catch (error) { console.error('Error handling MCP request:', error); if (!res.headersSent) { res.status(500).json({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error', }, id: null, }); } }});// Handle GET requests for SSEapp.get('/mcp', async (req, res) => { try { const sessionId = req.headers['mcp-session-id']; if (!sessionId || !transports[sessionId]) { res.status(400).send('Invalid or missing session ID'); return; } const transport = transports[sessionId]; await transport.handleRequest(req, res); } catch (error) { console.error('Error handling GET request:', error); if (!res.headersSent) { res.status(500).send('Internal server error'); } }});// Handle DELETE requestsapp.delete('/mcp', async (req, res) => { try { const sessionId = req.headers['mcp-session-id']; if (!sessionId || !transports[sessionId]) { res.status(400).send('Invalid or missing session ID'); return; } const transport = transports[sessionId]; await transport.handleRequest(req, res); } catch (error) { console.error('Error handling DELETE request:', error); if (!res.headersSent) { res.status(500).send('Error processing session termination'); } }});const httpServer = app.listen(PORT, () => { console.log(`MCP Server listening on port ${PORT}`);});httpServer.on('error', (error) => { console.error('Server error:', error); process.exit(1);});process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason);});process.on('uncaughtException', (error) => { console.error('Uncaught Exception:', error); process.exit(1);});This code snippet is a minimal implementation of a MCP server. Here we are exposing a greet tool via Streamable HTTP.This has the capabilities to maintain client sessions, and stream messages back to the client while a tool is running.But this is also stateful, session transports and event stores are kept in memory on the server. While this is very good in a single server implementation, it is very hard to scale with traditional horizontal methods. The same is also true for SSE as a transport.What Makes MCP Servers Hard to Scale?Unlike traditional APIs, MCPs use long-lived connections and maintain session state. These two things are almost like kryptonite to horizontal scaling.To start, earlier MCP implementations focused on SSE (Server-Sent Events), while newer approaches use Streamable HTTP. Both approaches rely on persistent connections, so request-based load balancing does not work well here. The server that accepts the connection must remain responsible for streaming responses.Second, some tools can be long-running tasks that continuously stream updates back to the client.Third, MCP servers may depend on session context, especially when they act as AI agents or maintain conversation history.Because of these factors, simply adding more servers behind a load balancer is not always sufficient.How to scale MCP ServersNow let’s look at how we can scale MCP servers. Each approach comes with different tradeoffs and is suitable for different types of workloads. Because of this, the final decision depends on what tradeoffs you are willing to accept in your system.Sticky SessionsSticky sessions are the simplest solution to scale any stateful service. They reduce a lot of the complexity that normally comes with scaling distributed systems. Just like other horizontal scaling systems, this also needs a load balancer.The catch is that a client connects to a specific server, the load balancer has to ensure all the future requests from that client are routed to the same server. This guarantees that the server holding the session state continues to handle that connection.This will work well for MCP servers as shown earlier, no code changes are necessary, and we can easily scale any standard MCP server.If you already have a working MCP server like the example above and need to scale it quickly, sticky sessions can be a very practical solution. You simply run multiple instances of the server and place a load balancer in front of them.MCP Server Scaling with Load BalancerMost modern load balancers support sticky sessions out of the box. They usually implement this using cookies or by hashing request attributes such as headers or IP addresses.NginxUses ip_hash to achieve sticky sessionsupstream mcp_servers { ip_hash; server server1:3000; server server2:3000;}AWS Load BalancerAWS Application Load Balancer (ALB) supports session affinity via target group stickiness. Once enabled, the load balancer issues a cookie that keeps routing the client to the same backend instance.You can also use a Network Load Balancer (NLB). Since it operates at the TCP level, long lived connections remain pinned to the same backend instance for the lifetime of the connection, which works well for streaming based MCP transports.HAProxyIn HAProxy, sticky sessions can be enabled using stick tables or by hashing the client IP so that requests from the same client are always routed to the same backend server.External StoresExternal Stores are a way to decouple the state from the worker(server) itself. If your MCP server depends on previous context, this can be useful.A use-case for this approach is when your MCP server is another AI agent and is storing the conversation history. In such cases, the server may need access to previous messages or intermediate tool outputs in order to generate the next response.In this approach you will need to use an external store like Redis or Valkey to store the session history or other details for fast retrieval. This allows the servers to be completely stateless and can fetch the required state on-demand from the store.MCP Server scaling with External StoreAnother advantage of using an external store is when you have idempotent tools. You can cache the results for repeated requests, this helps save compute and reuses previously computed results.Exampleimport Redis from "ioredis";import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { z } from "zod";const redis = new Redis();const server = new McpServer({ name: "external-store-example", version: "1.0.0",});// Tool that uses stored conversation historyserver.tool( "context_reply", "Replies using previous conversation context", { sessionId: z.string(), message: z.string(), }, async ({ sessionId, message }) => { const key = `session:${sessionId}`; const history = JSON.parse(await redis.get(key) || "[]"); history.push(message); // simple logic using context const lastTwo = history.slice(-2).join(" | "); await redis.set(key, JSON.stringify(history)); return { content: [ { type: "text", text: `Using context: ${lastTwo}`, }, ], }; });// Idempotent cached toolserver.tool( "square_number", "Returns the square of a number (cached)", { number: z.number(), }, async ({ number }) => { const key = `square:${number}`; const cached = await redis.get(key); if (cached) { return { content: [ { type: "text", text: `Cached result: ${cached}`, }, ], }; } const result = number * number; await redis.set(key, result); return { content: [ { type: "text", text: `Computed result: ${result}`, }, ], }; });Gateway + Worker PoolSeparation of concerns is a pretty common pattern is scalable distributed systems. We can use it to scale MCPs as well.In this architecture, connection management and actual execution is separated. A gateway is responsible for handling the client connections while the actual execution is done by a pool of workers.The gateway and workers are decoupled. Workers execute tasks and push results or intermediate updates to a shared system such as a stream, queue, or centralized store. The gateway reads these updates and streams or sends them back to the client.MCP Server scaling using Gateway and Worker PoolWith this approach, the workers can scale independently based on workload. Workers can also be specialized for particular tasks. For example, some workers may run on GPU machines such as H100 instances for model inference, while others may handle lighter tasks like API calls or data processing.import Redis from "ioredis";import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { z } from "zod";const redis = new Redis();const server = new McpServer({ name: "gateway", version: "1.0.0",});server.tool( "generate_text", "Delegates work to worker pool", { prompt: z.string(), }, async ({ prompt }) => { const jobId = `job:${Date.now()}`; // push job to queue await redis.lpush("job_queue", JSON.stringify({ jobId, prompt })); // wait for worker result const result = await redis.blpop(`result:${jobId}`, 30); return { content: [ { type: "text", text: result ? result[1] : "Worker timeout", }, ], }; });import Redis from "ioredis";const redis = new Redis();async function startWorker() { while (true) { const job = await redis.brpop("job_queue", 0); const { jobId, prompt } = JSON.parse(job[1]); // simulate heavy work (AI inference, API calls, etc.) const output = `Processed prompt: ${prompt}`; // push result back await redis.lpush(`result:${jobId}`, output); }}startWorker();Choosing the Right Scaling ApproachSo what approach to choose? Just like everything in life the answer is: it depends!Each scaling approach solves a different problem.Sticky sessions are best when you already have a working MCP server and need a quick way to scale without modifying the application.External stores are useful when multiple servers need access to shared context or cached results.Gateway and worker pool architectures are better suited for larger systems where connection handling and tool execution need to scale independently.How to Scale MCP Servers? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.