DEV Community

Cover image for What MongoDB taught me about Postgres.
Frank Snelling
Frank Snelling

Posted on

What MongoDB taught me about Postgres.

Using MongoDB arguably taught me more about Postgres than using Postgres did.

Hear me out. Previously, my knee-jerk reaction was to always opt for Postgres when starting a new project. Honestly — reasonably safe bet. But only using Postgres limited my understanding of it — as well as its benefits and its limitations.

Sounds weird to say I learnt more about something by not using it. But it's true — and that's why I'm planning this as the first article of a series. Because I genuinely learnt so much from not using Postgres.

How did I end up using MongoDB to start with?

Well, my current startup had already opted for MongoDB when I started. This largely came down to the experience on the ground, as well as the fact that the schema was rapidly evolving. This is well suited to a document-based database where schema flexibility is effectively unlimited.

But this flexibility came at a cost.

At first, it was a real joy not having a migrations-folder-of-death which harbored the scars of months of schema discovery in hundreds of back-and-forth migrations. Schema changes were fast and — when coupled with Pydantic — also continued to ensure a high-level of consistency across the codebase.

Nothing broke. The system always continued running. But it did become progressively slower and more expensive. Without rigid schemas, repeated validation was required in application code, not just on writes but also on reads.

Once Pydantic validation was happening at scale the CPU cost in our services became quickly noticeable. This was exacerbated by the fact that our validation relied on full models, limiting the effective use of projection. Simple queries started turning into full-document reads.

I suddenly began to appreciate the intentional rigidity of Postgres. Keeping validation right next to the data is efficient — not only because it is optimized, but because validation only happens once. And Postgres constraints are powerful, turning assumptions into guarantees.

That being said, it's also nice in a lot of ways to have validation close to the business logic. If we had handled migrations better, the need for defensive and expensive application code could have been reduced. And don't forget MongoDB schema validation — this is a feature I underutilized.

From my initial joy at the flexibility of MongoDB I quickly learnt an important truth. Schema discipline doesn't disappear — but you can choose whether it lives in your application code or in the database.

Top comments (0)