Opening: 941 Requests per Second, Almost All of Them Rejected
Before deploying, I wanted to know how fast the server was. I wrote a small load test that sent search_content calls to a local copy and printed the latency. The first result looked great:
n=2000 conc=1 rps=941 p50=0.9ms p95=1.8ms p99=6.1ms
941 requests per second at under a millisecond. Then I remembered that the server has a rate limit of 120 requests per minute per client IP, and that my load test was one client. Almost every one of those 2,000 requests had been answered with 429 Too Many Requests, and a 429 is very fast to produce. I had measured my own rate limiter.
The load test did not count status codes. After I added that, and raised the limit for the test, the real numbers were about a third of that throughput. Section 5 has them.
That mistake sums up this part: a number you did not check is not a measurement. Part 3 fixed a bug in more_like_this. This part covers what keeps fixes like that safe: tests with a real MCP client, the MCP Inspector, structured logs, and a load test that measures the right thing.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. Why do my MCP tests call the server through the SDK's Client over HTTP instead of calling the tool handler functions directly?
- A. Handler functions cannot be imported
- B. The real path includes the transport, JSON-RPC, schema validation and
Acceptrules. A direct call skips all of them - C. The SDK requires it
Show the answer to question 1
B. Most of what can break in an MCP server sits between the HTTP request and the handler. A test through a real client catches it. Section 1 shows how.
Question 2. Why does my logger write one JSON object per line with a severity field?
- A. JSON is smaller than plain text
- B. Cloud Logging reads
severityandmessagefrom JSON on stdout, so logs can be filtered by level and by any field without extra setup - C. PM2 refuses plain text
Show the answer to question 2
B. On App Engine, a JSON line on stdout becomes a structured log entry. On a VPS, the same line stays readable with jq. Section 3 has examples.
Question 3. In a load test, throughput stays near 350 requests per second while concurrency goes from 10 to 40, and p50 latency grows from 24 ms to 98 ms. What is happening?
- A. The network is slow
- B. The server is saturated. Extra concurrent requests only wait in the queue, so latency grows while throughput stays flat
- C. The test is broken
Show the answer to question 3
B. This is Little's Law: requests in flight = throughput × latency. If throughput cannot grow, more requests in flight means more time waiting.
Question 4. Why should a query string be cleaned before it is logged?
- A. To save disk space only
- B. A query is user input. Control characters can forge new log lines, and very long values make logs expensive and hard to read
- C. Cloud Logging rejects strings with spaces
Show the answer to question 4
B. My logger replaces control characters with spaces and cuts values at 200 characters. Section 3 shows the code.
Question 5. What is the cheapest signal that the search is failing users?
- A. CPU usage
- B. The zero-result rate: how many searches return nothing, and which queries they are
- C. The number of deploys per week
Show the answer to question 5
B. Every search_content call is logged with its query and result count. A list of queries with zero results is a to-do list for content and relevance.
1. Tests Through a Real MCP Client
The server has 17 tests, run with Node's built-in test runner and tsx, no extra framework:
$ npm test
...
# tests 17
# pass 17
# fail 0
# duration_ms 2195.722435
They come in two groups.
Search tests (10) load the real index from data/articles.json, not a fixture. That is deliberate: if a change to an article or to the build script breaks search, the tests notice.
test("tolerates typos in longer words", () => {
const { hits } = search.search("firestor ofset", { lang: "id" });
assert.equal(hits[0]?.slug, "firestore-cache-search-part-2-firestore-queries-limits");
});
test("falls back to any-word matching when no article has every word", () => {
const response = search.search("firestore zzzyyyxxx");
assert.equal(response.matchMode, "any");
assert.ok(response.hits.length > 0);
});
MCP tests (7) start the real Express app on a random port and talk to it with the SDK's own client, exactly as Claude would:
before(async () => {
const app = createApp({ search, log, rateLimitPerMinute: 1000, clientIpHeader: "x-real-ip" });
const server = app.listen(0, "127.0.0.1");
await new Promise((resolve) => server.once("listening", resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
async function connect() {
const client = new Client({ name: "test", version: "1.0.0" });
await client.connect(new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`)));
return client;
}
What the MCP tests check:
| Test | What would break without it |
|---|---|
| Lists five tools with schemas and read-only hints | A renamed tool, a missing required, or send_event losing readOnlyHint: false |
search_content returns text and structured content, and logs the call | Text and JSON drifting apart, or the log line losing its fields |
| Invalid arguments are rejected by the schema | A limit removed from the schema |
get_article cuts long articles and explains a wrong language | The "call it with lang id" hint from Part 2 |
more_like_this, list_series, send_event | Any of the smaller tools |
| Plain HTTP: health, 405, parse errors, CORS preflight | The non-MCP edges of the server |
Rate limit per IP answers 429 with Retry-After, and another IP is not affected | The limiter blocking everyone instead of one client |
The logger is injected, so a test can read what was logged:
const logs: { severity: string; message: string; fields: Record<string, unknown> }[] = [];
const log: Logger = (severity, message, fields = {}) => void logs.push({ severity, message, fields });
That makes the log line part of the contract. If someone removes ms from the tool log, the dashboards built on it would break silently. The test breaks loudly instead.
2. The MCP Inspector and Plain curl
The MCP Inspector is the official tool for poking at a server by hand. Version 1 is deprecated, so use the current one with @latest. It has a browser UI and a CLI mode, and the CLI is handy for quick checks:
npx @modelcontextprotocol/inspector@latest --cli http://localhost:3400/mcp \
--transport http --method tools/list
npx @modelcontextprotocol/inspector@latest --cli http://localhost:3400/mcp \
--transport http --method tools/call --tool-name search_content \
--tool-arg query="outbox pattern" --tool-arg limit=2
The second command printed the same thing Claude receives, text and structured content together:
{
"content": [{ "type": "text", "text": "10 article(s) for \"outbox pattern\":\n1. Firestore, Caching & Search Part 5: Keeping a Search Index in Sync ..." }],
"structuredContent": { "query": "outbox pattern", "total": 10, "matchMode": "all", "nextOffset": 2, "results": [ ... ] }
}
For the edges that a well-behaved client never reaches, plain curl is better, because I can send exactly the wrong thing:
| Request | Answer |
|---|---|
GET /mcp | 405 with JSON-RPC error -32000 "Method not allowed. Send JSON-RPC requests with POST." |
| Broken JSON body | 400 with -32700 "Parse error" |
Accept: application/json only | 406 "Client must accept both application/json and text/event-stream" |
| Fourth request in a minute with a limit of 3 | 429, Retry-After: 59, "Too many requests, slow down." |
Every error on /mcp is a JSON-RPC error object, and no stack trace ever leaves the server. (Paths outside /mcp, /health and / get Express's small default 404 page, which is fine for scanners.)
3. Logs: One JSON Line per Tool Call
Every tool call writes exactly one log line, from the timed() wrapper shown in Part 2:
{"severity":"INFO","message":"tool call","time":"2026-11-30T10:51:32.828Z","tool":"search_content","ms":2,"results":3,"ok":true,"query":"idempotensi","lang":"id"}
{"severity":"INFO","message":"tool call","time":"2026-11-30T10:51:32.899Z","tool":"get_article","ms":0,"results":1,"ok":true,"slug":"node-ts-backend-part-12-idempotency","lang":"en"}
The logger is twenty lines:
const clean = (value: unknown): unknown => {
if (typeof value !== "string") return value;
// No control characters (no forged log lines) and no huge values.
const text = value.replace(/[\u0000-\u001f\u007f]/g, " ").trim();
return text.length > 200 ? `${text.slice(0, 200)}…` : text;
};
export const jsonLogger: Logger = (severity, message, fields = {}) => {
const entry: Record<string, unknown> = { severity, message, time: new Date().toISOString() };
for (const [key, value] of Object.entries(fields)) if (value !== undefined) entry[key] = clean(value);
console.log(JSON.stringify(entry));
};
Why this shape:
severityandmessageare the field names Cloud Logging looks for in JSON on stdout. On App Engine, these lines become structured entries that can be filtered by level and by any field, for examplejsonPayload.tool="search_content" AND jsonPayload.results=0.- One line per call means the logs are also the metrics. From these fields alone:
| Question | From which fields |
|---|---|
| p95 latency per tool | tool, ms |
| Error rate | ok |
| Zero-result rate, and which queries | tool="search_content", results=0, query |
| Most read articles | tool="get_article", slug |
- Cleaning protects the logs from the input. A query is text written by a user and passed on by a model. Without cleaning, a newline inside it could produce a line that looks like a different log entry, and a 10,000-character query would be stored in full.
One thing to be careful about: queries are user input, and a user can type anything into a chat. I log them because they are the most useful signal for search quality, but they are cut at 200 characters, and send_event's description tells the model not to send personal information. If this server handled private data, I would log a hash or a category instead of the raw query.
4. Health Check: /health, Not /healthz
The server has a small health endpoint:
$ curl -s http://localhost:3400/health
{"ok":true,"articles":194,"generatedAt":"2026-11-30T10:51:18.121Z","version":"0.1.0"}
It returns the article count and when the index was built, so after a deploy I can see at a glance that the new index went out.
It was called /healthz at first, the Kubernetes habit. On App Engine, that path never reached my app. Part 5 tells that story.
5. A Load Test That Measures the Right Thing
After the 941-rps mistake, the load test counts every non-200 answer, and the server runs with the rate limit raised for the test. Each run sends search_content calls with 15 different queries in rotation. Real numbers, on a 2 vCPU Linux machine with Node.js 22:
| Requests | Concurrency | Throughput | p50 | p95 | p99 | Non-200 |
|---|---|---|---|---|---|---|
| 2,000 | 1 | 261 rps | 3.0 ms | 8.4 ms | 13.2 ms | 0 |
| 2,000 | 10 | 351 rps | 23.6 ms | 51.0 ms | 75.8 ms | 0 |
| 2,000 | 40 | 380 rps | 97.8 ms | 186.0 ms | 213.3 ms | 0 |
Reading this table:
- Throughput hardly grows after concurrency 10. Node.js runs JavaScript on one thread, and that thread is busy.
- Latency grows instead. Going from 10 to 40 concurrent requests barely adds throughput and quadruples p50. This is Little's Law: requests in flight = throughput × latency. With throughput stuck near 380 rps, 40 requests in flight means about 100 ms each.
- The search itself is not the bottleneck. In-process,
search()takes 0.34 ms and creating the per-request server takes 0.42 ms. The rest of the ~3 ms is HTTP, JSON parsing and serialization, and the SDK's transport.
Two honest limits of this test:
- It ran on my machine, not on App Engine. An F1 instance has a 600 MHz CPU limit, far less than the machine above, so its numbers will be lower. I did not load test the deployed version, because a load test against a public load balancer costs money and looks exactly like the abuse I am trying to block.
- It tests one tool.
more_like_thisis about forty times slower in-process (Part 3), so a mix that uses it heavily would saturate sooner.
The test also showed something about memory:
| Moment | Resident memory (RSS) |
|---|---|
| Right after startup, index loaded | 149 MB |
| After 6,200 requests at up to 40 concurrent | 293 MB |
The F1 instance class has a 384 MB memory limit. Most of the growth is V8 being lazy about garbage collection, not a leak, but 293 MB leaves little room. Two cheap protections: cap the heap with node --max-old-space-size so the garbage collector works harder before the limit, or use the next instance class up. For my traffic, which was a handful of calls from my own chats, F1 was fine. Under real load, this is the first thing I would watch.
6. What the Rate Limiter Can and Cannot Do
The limiter is the simplest one that works: a fixed one-minute window and a Map of counts per client IP.
function rateLimiter(limit: number, clientIp: (req: Request) => string) {
let windowStart = Date.now();
let counts = new Map<string, number>();
return (req: Request, res: Response, next: () => void) => {
const now = Date.now();
if (now - windowStart >= 60_000) {
windowStart = now;
counts = new Map();
}
const ip = clientIp(req);
const count = (counts.get(ip) ?? 0) + 1;
counts.set(ip, count);
if (count > limit) {
res.setHeader("Retry-After", String(Math.ceil((windowStart + 60_000 - now) / 1000)));
return jsonRpcError(res, 429, -32000, "Too many requests, slow down.");
}
next();
};
}
What it does well: one noisy client gets 429 with a Retry-After, and other clients are not affected (a test checks exactly that).
What it cannot do:
- It is per instance. With two App Engine instances, a client can get up to twice the limit. The real limit belongs at the edge, in Cloud Armor or Nginx, which see all traffic. Part 6 explains why I could not use Cloud Armor on a trial account.
- It depends on the right IP header. Behind a proxy, the TCP peer is the proxy. The server reads the client IP from a configured header:
x-real-ipbehind Nginx,x-appengine-user-ipon App Engine. With the wrong header, every user shares one counter. - A fixed window allows bursts at the boundary. A client can send the full limit at the end of one minute and again at the start of the next. For a blog search, that is acceptable.
7. Three Testing and Observability Traps
Trap one: load tests that do not count status codes. My first benchmark measured 429s. Count non-200 answers in every run, and treat a run with errors as a failed run.
Trap two: testing handlers instead of the protocol. A handler test passes while the schema, the transport or the Accept rule is broken. Test through a real client at least once per tool.
Trap three: logs that are not data. Free-text log lines need regexes to answer "what is the p95 of get_article". One JSON line per call, with fixed field names, answers it with a filter.
Summary
- 17 tests with
node:testandtsx: 10 on the real index, 7 through the SDK'sClientover HTTP, including schemas, annotations, errors, CORS and the rate limit. The injected logger makes the log line part of the contract. - MCP Inspector (
@latest, v1 is deprecated) for manual checks, with a CLI mode. Plaincurlfor wrong requests: 405,-32700, 406 and 429 all come back as JSON-RPC errors. - Logs: one JSON line per tool call with
severity,tool,ms,results,ok. Cloud Logging reads it as structured data, and it doubles as metrics: p95 per tool, error rate, zero-result queries. Input is cleaned and cut at 200 characters. - Load test: 261 rps at p50 3.0 ms with one client, flat near 380 rps at higher concurrency while p50 grows to 98 ms. Measured locally on 2 vCPUs, not on F1. Memory 149 → 293 MB against F1's 384 MB limit.
- Rate limiter: per IP, per instance, fixed window. Useful, but the real limit belongs at the edge.
Next
Everything so far ran on my machine. In Part 5, we deploy to App Engine Standard: app.yaml line by line, building outside the platform, scaling to zero, getting the real client IP, and the two surprises that cost me the most time: a health check path that Google answers itself, and a build tool that refused to run because its binary came from another operating system.

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.
