DEV Community

Mustafa Güngör
Mustafa Güngör

Posted on

My latency table was measuring the wrong thing. Fixing it showed I was 2.5x over budget.

For two releases, my docs said the bot detector stays under 1 ms per request. The table had medians, 95th percentiles and a nice bold number.

All of it was true, but it measured the wrong thing.

The table timed one function: the behavioural scoring step. A real request does a lot more than that. It verifies a signed token, burns a single-use nonce in SQLite, computes a replay fingerprint and writes session history. None of that was in the number.

When I finally timed the whole request, the 300-point case wasn't 1.2 ms. It was 2.5 ms.

This post covers how I found that, what it took to cut it in half, and the five AI-written patches I threw out along the way.


🤔 Quick context: what is Synapse Shield?

It's a self-hosted replacement for CAPTCHAs. A small browser SDK records how a visitor moves, taps and types. It never records what they type. Your server scores the session and then allows it, blocks it, or asks the browser for an invisible proof-of-work.

A human-like cursor path is allowed, a Bézier-curve bot is blocked

It's written in Python with a Rust core, has SDKs for React, Vue and plain JS, and is MIT licensed.


📏 Step 1: measure the thing users actually wait for

I extended the benchmark script with a --full-path mode. It calls the real decision function with a valid signed token, an isolated temporary database and a fresh client IP on every run, so rate limits and session history can't skew the timings. A --breakdown mode times each stage on the same inputs.

The result at 300 cursor points (the SDK maximum), median, on a quiet machine:

Stage Time
Whole request 2,456 µs
Behavioural scoring (the old table) 997 µs
↳ trajectory shape hash (Python) 239 µs
↳ tokenizer for the shadow CNN 236 µs
↳ CNN inference 111 µs
Replay fingerprint 458 µs
Token decode + verify + nonce 451 µs
Storage writes 141 µs

Even at 60 points the whole request took 1.15 ms. My budget was blown at every size, and the docs didn't show it.

💡 Lesson: a benchmark has to measure what the user waits for, not the part you're proud of.


⚡ Step 2: cut it in half (without changing a single output)

The rule for every optimisation was simple: the outputs must not change. Two of these values are stored in the database and compared against values written by older versions, so "almost the same" would silently break replay detection.

1. Two hashes moved to Rust. The shape hash and the replay fingerprint went from Python/NumPy to the Rust core. The output had to be bit-identical, which meant reproducing np.interp edge cases, rounding behaviour and integer overflow exactly. A property test runs 5,000+ traces, and my own fuzz run added 20,000 traces with random keys from 0 to 200 bytes. There were zero mismatches.

At 300 points the shape hash went from 239 to 28 µs, and the fingerprint from 458 to 34 µs.

2. Tokenizer and CNN vectorised. I replaced per-point Python loops with NumPy array operations. On 4,000 traces the CNN score is exactly the same as before.

3. Token path. Profiling showed why token verification grew with the trace length. It decoded the payload, concatenated four event lists, then checked four timestamp fields on every event. The new version uses one pass, no concatenation and an IPv4 fast path. The single-use nonce write stays synchronous and atomic. That is non-negotiable.

4. Small engine fast paths, checked against a frozen snapshot of 3,200 cases. They are bit-identical too.

The result, whole request, p50 / p95:

Cursor points Before After
60 1.15 / 1.87 ms 0.65 / 1.11 ms
150 1.68 / 2.48 ms 0.85 / 1.38 ms
300 2.46 / 3.39 ms 1.19 / 1.88 ms

What still isn't good enough: the median is under 1 ms up to 150 points, but the 95th percentile is still above 1 ms at every size. At 300 points most of the remaining time is in token decoding (~0.38 ms) and Rust feature extraction (~0.15 ms). That's the next release, and the docs say so.


🚫 The five patches I rejected

This release was written by AI coding agents. My job was to review each patch as if it had come from a stranger. Every agent reported "done, all tests pass." Five first attempts were still wrong:

1. A hand-rolled SHA-256. The Rust port of the fingerprint was correct and fast, and my fuzz run found zero mismatches. But it implemented SHA-256 and HMAC from scratch, round constants and all, inside a security product. I sent it back to use the audited RustCrypto sha2 and hmac crates. Correct is not enough when every future reader has to re-verify the crypto by hand.

2. A latency panel that repeated my own mistake. The new Grafana panel was titled "Requests under 1 ms latency budget", but it was fed by the metric that only times the scoring step. It was the exact bug I was fixing in the docs, now in a dashboard. Round two added synapse_request_duration_seconds, which times the whole decision on every return path. Round three got rid of a 200-line re-indent that had come along with it.

3. A "fix" that broke require(). I asked for npm package metadata fixes. The agent also converted the React package from CommonJS to ESM with an import-only exports map. That would break everyone using Jest's default config or an older Next.js setup, in a patch release. React didn't even have the ESM problem; only the Vue package did.

4. A backward-compatibility break in Litestar. The fix for "Litestar returns 403 instead of 503" swapped Litestar's PermissionDeniedException for a new class. Any app with a handler registered for that exception would stop catching our 403s. The second version subclasses both.

5. Rewriting security logic for 1.4 µs. One optimisation rewrote the session-invariance check, the code that protects against session-history poisoning, into a single pass. The output was identical. The measured gain was 1.4 microseconds. I reverted it, because that risk isn't worth 1.4 µs.

None of these failed a test. Every one of them would have shipped if "tests pass" had been the bar.

💡 Lesson: an agent's tests prove the agent's idea of the task. Someone still has to ask whether the idea was right.


🤖 Bonus: the short-bot gap is closed

Since v0.12.0 the docs listed a known gap: 8.5% of short (3 to 10 point) synthetic bots got through with no challenge at all. Every one of them came from a single generator that fires events at a perfectly constant interval.

The fix sends those short-trace signals into the existing capped "insufficient evidence" path, which triggers a proof-of-work instead of a block. Measured on real people (the SapiMouse dataset, 120 users) with an isolated database per run:

Before After
Short synthetic bots let through without a challenge 8.5% 0%
Real short mouse movements blocked 1.67% 1.18%
Real short mouse movements challenged 61.0% 61.8%

Fewer real people get blocked. The cost is a slightly higher challenge rate, and I'd rather say that out loud than hide it.


🧪 And then CI went red

I tagged the release, the wheels built and PyPI published. Then the main test job failed on all four Python versions.

Two new tests passed on my Windows machine and failed on Linux:

  • One assumed pyproject.toml had CRLF line endings. Git gives you CRLF on Windows and LF on Linux.
  • One compared floats with an absolute tolerance of 1e-9. NumPy on Linux sums in a different order, and the result was off by 1.4e-9.

No product code was wrong, but the release still wasn't done. Both tests now build their own fixtures and use a relative tolerance. "Wait for the Linux CI to be green" is on the review checklist now.


🚀 Try it


bash
pip install -U "synapse-shield[server]"
npm install synapse-shield-react   # or synapse-shield-vue
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
reidmarlow profile image
Reid Marlow •

The dashboard repeating the benchmark mistake is a useful catch. I'd keep the scoring timer as a diagnostic, but put the full decision-path p95 on the budget panel, including nonce-store failures and early returns. That way an improvement in one stage can't hide a regression elsewhere.

Collapse
 
0xstoic_bit profile image
Mustafa Güngör •

Agreed, and that's how v0.12.2 ended up. The budget panel now reads synapse_request_duration_seconds, which wraps the whole decision: token check, nonce, scoring, fingerprint and storage. It's observed exactly once per request on every return path, including early 403 / 429 and the 503 nonce-store path. The panel shows p50 / p95 / p99 plus the share of requests under 1 ms. The scoring timer stays, but on its own panel labelled as a diagnostic.

Thinking about your point, two things I'd add:

Fast failures can flatter the budget. When the nonce store is down, requests return 503 quickly, so the p95 can improve during an outage. That's why the 503 rate panel sits next to the latency panel. An outcome label on the request histogram (allow / challenge / block / error) would make it explicit, and it's on my list.

Middle stages are still only visible indirectly. In production you can see "total" and "scoring", so a regression in token verification or storage shows up only as a gap between the two. The per-stage breakdown exists in the benchmark script (--full-path --breakdown) but not as metrics yet.

Thanks, this is exactly the kind of review I was hoping for.

Collapse
 
0xstoic_bit profile image
Mustafa Güngör •

New in this release: a Grafana dashboard for request latency, nonce-store outages and native fallbacks, all with PII-free labels.

👉 GitHub: 0xStoic-bit/Synapse_Shield