← Selected systems work

MongoDB query & serialization optimization

Two interventions on the same hot paths — one on the database side, one on the wire format — each measured on its own terms.

Where
9AI — DataReel video-generation platform
Role
Monitored, diagnosed, and implemented
Scale
Growing multi-tenant traffic across enterprise clients on shared infrastructure
Stack
MongoDB, Redis, HTTPX, ORJSON
10x
API response-time improvement from targeted MongoDB query & index changes
5x
latency reduction from switching serialization to ORJSON

Problem

As multi-tenant traffic grew — more enterprise clients on the same shared infrastructure — API response times started degrading on the platform's hot paths. It wasn't one clean cause. Query patterns that had been fine at lower volume were now hitting collections without indexes that matched how they were actually being queried, and on high-throughput endpoints, the cost of serializing responses to JSON was itself showing up as measurable latency. Both problems lived on the same request path and both needed addressing, but they weren't the same problem and didn't have the same fix.

Constraints

What I built

On the database side, I used MongoDB's query analytics to find the queries that were actually slow in production. From that, I added and adjusted indexes matched to the real access patterns those queries showed, and revisited the indexing periodically as demand shifted. Alongside that, MongoDB and Redis connection pooling, plus HTTPX connection pooling, cut the per-request overhead of establishing new connections and TLS/SSL sessions, which compounds with query latency on high-frequency endpoints.

Separately, on serialization: I swapped the default JSON encoder for ORJSON (a Rust-based JSON encoder/decoder) on endpoints where response serialization was a meaningful share of request time.

slow query query analytics / profiler targeted index fast query
Indexing driven by observed query patterns, not applied defensively across the board.

The trade-off

Evidence-driven indexing is slower up front — you wait for real query analytics before touching anything, then keep revisiting as demand shifts. Indexing everything that might get queried ships faster, but it's a false economy: every unused index still costs write throughput and storage, and nobody notices until the collection is under real load. I took the slower path and treated it as recurring maintenance, not a task with an end date.

Outcome

The MongoDB query and index work produced a 10x improvement in API response times on the paths hit hardest by multi-tenant traffic. The ORJSON swap, measured separately on serialization-heavy endpoints, cut latency by at least 5x. These are two different numbers from two different interventions — one from changing how the database is queried, one from changing how responses are encoded — not a single combined figure.

MongoDBquery analyticsindexingORJSONRedisHTTPXconnection pooling