Skip to main content

Postgres or MongoDB? I Measured It

Software
One Django service, the same code on both engines, the same k6 scenarios back to back. MongoDB’s first run had a p95 of 5.27 s. Two fixes took it to 16 ms. It still lost on every rate, gave out in the soak, and the service stayed on Postgres.
Author

Benedict Thekkel

Published

November 8, 2026

The app is my experimental test bed: a Django REST + React SaaS split into two services, catalog and instances, behind one gateway, each with its own database, running in LXC containers on my Proxmox lab. It is synthetic load on small containers, and the numbers should be read as that. The load-test method is the one from the k3s post: the same k6 scenario after every change, and a column for what saturated.

The question was simple. instances stores questionnaires, and its data is mostly JSON blobs: answers, a snapshot of the questionnaire definition, computed metrics. That is the textbook case for a document database. So does MongoDB beat Postgres on it?


Why instances, and how to make the test fair

instances was the obvious candidate. Its models carry answers_json, questionnaire_json_snapshot and metrics_json. It has no user table, no Celery and no outbox. And it does about 90% of the app-tier work under load, so a database change shows up in the numbers.

catalog stayed on Postgres. It holds auth, the admin, Celery beat and a transactional outbox, all of which assume a relational database.

Three rules kept the comparison about the database and not about a rewrite:

  • Keep the ORM. django-mongodb-backend 6.0.4 lets Django models run on MongoDB. Views, serializers and most tests stayed unchanged. The engine is a deploy setting.
  • Same box, same cache. MongoDB 8.0 got its own container with 2 cores and 1 GB, a one-member replica set (needed for transactions), and a 0.25 GB WiredTiger cache. Postgres 16 keeps shared_buffers at 256 MB, so both engines have the same cache.
  • Each run from its own reset. Both engines are seeded with the same deterministic data (20 owners x 200 questionnaires). Every scenario ran on Postgres, then on MongoDB, back to back.

Making the code engine-neutral was its own piece of work. MongoDB has no row locks, so the double-submit guard became a conditional update() that works on both engines. Integer auto keys became UUIDs, because the backend refuses integer auto keys. And atomic() became engine-aware.


The first run collapsed

The first MongoDB run at a fixed 200 iterations a second had a p95 of 5.27 s, against 9.36 ms on Postgres. It dropped 34,253 iterations, and mongod sat at 98% CPU.

A 500x gap is not “MongoDB is slower”. It is a query doing something it should not. So I turned on mongod’s slow-query log for every operation over 100 ms, with docsExamined. That number, documents read per query, found both problems in a few minutes.


Problem 1: a unique index that cannot find null

In SQL, two NULLs in a unique column do not collide. To copy that, django-mongodb-backend builds every unique index as a partial index, filtered to documents where the field exists ({id: {$gte: ""}}).

That has a side effect. A partial index only contains the documents that match its filter, so it cannot answer a query for null. And select_related("battery") becomes a $lookup on battery.id. For every questionnaire with no battery, the lookup searched for null, could not use the index, and scanned the whole battery collection.

One query examined 2,822,816 documents to return 10 rows.

The fix: for a unique field that can never be null, build a full unique index instead (in the backend wrapper, core/mongodb/base.py), and a migration rebuilds the existing ones. p95 went from 5.27 s to 160 ms.


Problem 2: the join runs before the limit

160 ms was still 17x Postgres. The slow-query log showed the second shape. The backend puts each $lookup before $sort and $limit. So one page of 25 questionnaires joined all of the owner’s ~3,000 rows, sorted all of them, and then kept 25.

Postgres limits before it joins. The generated MongoDB pipeline joined and sorted every row first.

A second cost made it worse. MongoDB timestamps have millisecond precision, so the list had gained an -id tiebreaker for a stable order. The list index ended at created_at, so it could not supply that order, and MongoDB sorted every row instead of reading them in index order.

Postgres has neither problem. Its planner limits before it joins, and it can sort incrementally from an index that covers only the first sort key.

The fix had two parts:

  • joined(), a small helper in apps/questionnaires/db.py. On Postgres it is a join. On MongoDB it is a prefetch: fetch the page of 25 first, then fetch their related rows in a second query.
  • A migration adds -id to the list indexes, so the sort comes from the index.

p95 went from 160 ms to 16.1 ms. The second fix also changed Postgres’s indexes, so Postgres was re-run too, with no measurable change.


The fair comparison

With both fixes in, every scenario ran on both engines. Every scenario finished with 0 failed requests on both.

Postgres MongoDB
Fixed 200/s, mixed, p95 8.54 ms 16.12 ms
Fixed 200/s, read-mostly, p95 8.74 ms 10.44 ms
Stress knee, mixed ~575 to ~614 req/s ~322 to ~332 req/s
Stress knee, read-mostly ~495 to ~526 req/s ~404 to ~419 req/s
Soak, 1 h at ~350 req/s held, 1,266,447 requests, 0 failed stopped at minute 18 (5 minutes over 1% dropped)
Respondent / PDF / outage, p95 4.8 / 104 / 4.9 ms 6.8 / 110 / 6.6 ms
Catch-up after instances restarts 10 s 5 s
Storage, 4,000 questionnaires 7.2 MB 3.6 MB

MongoDB won two rows. It catches up faster after a restart, and it stores the data in half the space, because it compresses data and Postgres does not below its TOAST threshold. Its indexes were the same size, since the UUIDs are stored as 32-character strings and a UUID primary key adds a second index beside _id.

It lost every row that measures speed.


Why MongoDB slows down as the rows grow

The fixed-rate table hides the important part. On MongoDB, database CPU and the slowest group’s p95 rose every minute at a constant request rate. In the mixed run the slowest group went from 37 ms at minute 1 to 130 ms at minute 5, while Postgres went from 11 to 17 ms. Each run adds rows, and MongoDB’s remaining costs grow with them.

The soak showed it plainly. mongod’s CPU climbed from 16% to 76% at a constant rate, the slowest p95 passed 150 ms at minute 6 and 400 ms at minute 11, and the run was stopped at minute 18.

The cause is the same shape as problem 2, in the queries I had not fixed. The slow-query log during the soak named them:

Query Slow runs Docs examined, first to last
Dashboard recent submissions 1,407 1,763 to 7,305
Dashboard battery status 943 1,989 to 5,355
Dashboard scores 583 524 to 1,265
Questionnaire list 15 6,112 to 7,637

Each dashboard cache miss joins every row in its time window before it keeps 10 or 500. That, and not CPU, set MongoDB’s stress knee: it hit the latency limit with CPU to spare on both containers. Postgres runs the same queries as joins, but its planner limits first.


The decision

instances stays on Postgres. On 2026-11-08 the MongoDB support was removed, and the baseline write-up stays in the repo as the record.

Each remaining slow query could be rewritten for MongoDB the way joined() rewrote the lists: fetch the page, then its related rows. But that is engine-specific code for every dashboard query, on top of the engine-specific paths MongoDB already needed for transactions, the submit guard, list joins and index shapes. All of that buys a database that, after the work, would at best match the one I already have.

“Document-shaped data” was the wrong test. What matters is how the service queries the data. These queries are relational: filter by owner, join to the questionnaire type and battery, sort, page. The JSON blobs ride along, and Postgres jsonb already stores them well.

The most reusable lesson is the debugging one. docsExamined against rows returned found both problems in minutes. Any ORM that translates to a different engine needs that check, because the translation, not the database, is where the cost hides.


What this is not

One run per engine at fixed rate, two stress runs, one soak each, on a shared host. Small containers (2 cores each) and a small dataset (4,000 questionnaires at seed). It measures MongoDB through django-mongodb-backend 6.0.4, not MongoDB with hand-written pipelines. A later version of the backend may place $lookup differently, and the result could change. I did not run a Postgres EXPLAIN with stale statistics to see how badly Postgres degrades in the same situation.


Takeaway

Step MongoDB p95 (mixed, 200/s) Lesson
As generated by the ORM backend 5.27 s A 500x gap is a query bug, not an engine trait
Full unique index for never-null fields 160 ms Partial indexes cannot find null
Prefetch instead of join, -id in the index 16.12 ms Limit before you join; let the index supply the order
Postgres, same code 8.54 ms Its planner already does both

Compare engines with the same code, the same cache and the same scenarios, and keep measuring until the gap has a cause you can name. Here the named cause was the shape of the queries, and the queries are relational. So the data stays in Postgres.


Back to top