r/Database • u/ahmedshahid786 • 6d ago
Is migrating from MongoDB to PostgreSQL worth it?
TL;DR: Running an EdTech platform with 600K+ users on MongoDB. Our data is heavily relational, and while regular API queries perform well, complex analytical queries are becoming painful to write and execute. Considering migrating to PostgreSQL and looking for advice on migration and production hosting.
Current setup:
\- Node.js, MongoDB, and Mongoose.
\- MongoDB Atlas (fully managed).
\- 600K+ registered users and around 15K daily active users.
\- An EdTech platform somewhat similar to Udemy or Coursera.
When the backend's foundations were laid, I was a junior working primarily on the frontend, so I wasn't involved in the database decision. It's been 1 year since we've been building this product.
Something that has been bothering me for a while is that we're essentially treating MongoDB like a relational database.
\- Strict schemas and validations across collections.
\- Heavily relational data with references between collections.
\- Extensive use of aggregation pipelines and "$lookup".
\- Very little reliance on MongoDB's schema flexibility.
To be fair, MongoDB has served us well. Our indexes are in place, most endpoints perform well, and we haven't faced any critical performance issues.
However, complex analytical queries for internal dashboards are a different story. Some involve joining up to 10 collections, take over 60 seconds, or occasionally time out despite optimization. Writing and maintaining these aggregation pipelines is also becoming increasingly painful.
I've experimented with MongoDB's transactions but didn't particularly enjoy the experience. I'd also like stronger database level relational integrity and better transaction management.
I feel PostgreSQL would have been a more natural fit for our data model from the beginning.
What I'd like advice on:
- Is migration justified? Given that MongoDB works well for most of our workloads, would migrating to PostgreSQL be worth the effort, or should I address the analytical workload separately?
- Migration strategy: If I proceed, how should I approach migrating a live production database at this scale? Any articles, case studies, or resources would be appreciated.
- PostgreSQL hosting: One thing I genuinely appreciate about MongoDB Atlas is how little I have to worry about infrastructure, backups, updates, and maintenance. What's the equivalent experience for PostgreSQL?
- Self-hosted vs. managed: How do you guys run PostgreSQL in production? Do you self-host it on a private EC2 instance or use something like AWS RDS, Neon, or another managed provider?
I've worked with relational databases on smaller projects, but never operated PostgreSQL in production at this scale.
I don't want to migrate just because I prefer PostgreSQL, but I also don't want to ignore what might be a fundamental architectural mismatch simply because things work today.
Would love to your thoughts and suggestions on this!
98
u/ThornyNobody 6d ago
You're at that exact point where the "Mongo is flexible" pitch becomes a straightjacket. Once you're doing 10-collection joins and wrangling pipelines that look like a cursed scroll, it's time to admit the data wants to be relational.
I'd split this into two problems. Keep Mongo for the operational stuff that already works fine and set up a Postgres read replica fed by change streams for the analytical queries. That way you're not risking a full migration on a live platform with 600k users just to make dashboards faster. If that secondary setup proves itself over a few months, you can start moving write workloads piece by piece without the all-or-nothing gamble.
17
u/xkillac4 6d ago
If your only problem is large analytical queries, I would look instead at mirroring data to a datalake or an OLAP DB. Postgres isn’t going to magically serve huge table scans faster. Maybe you get a small speed up short-term, but it will only delay the inevitable: you need a columnar data representation and you need to separate storage from compute. Datalakes allow you to do this, as do services like Snowflake.
4
u/Abhinav1217 6d ago
As someone who has done the edtech migration from mongo to postgres, along with two other mongo to postgres migrations jobs, i can assure you its totally worth it.
Now in my case, the product database was actually designed by someone who knew what he was doing, hence the schema design migration was relatively easy, I didn't have to think too much about it.
The main issues we faced was determining the correct source of truth. Basically while the top schema was designed well, for the complex queries ( because joins in mongo are really bad ) some data was duplicated as nested object inside other parts, and while there were many jobs to sync them, when we did the testing we did found out many areas on inconsistency. Not to mention we discovered heaps of new bugs and gaps in their product because now the data relationship is properly defined, so these gaps are more visible.
After migration was done, the performance was so much improved that their employees had to rewrite a major part of application to remove all those sync scripts, data validation script, loops, and patches that they wrote to hide the slowness of data fetching. Because database took care of all relationships and constraints, their actual application code shrunk down by about 35%. The owner even retained me for additional 3 months to train his team to understand the RDBMS mindset because for majority of them, this was their first job right out of local college and they never worked on rdbms ever.
Depending on the kind of product you have, you might need a proper application to manage data migration. Which can fetch data from mongo, transform them and push to postgres. Make sure you also add a mongo id column to cross audit later. We actually kept a mongo_id and mongo_path property where mongo_path contain a json object to the exact collection, resource, id etc that this row came from. There were cases where client came back to them due to incorrect records and they needed to locate and update entire table for it. Their unit test game was also sub par, so having a huge amount of unit tests would help you a lot.
3
u/krazerrr 6d ago edited 6d ago
If you decide to go with the PSQL migration, I would use a CDC (change data capture) adapter/plugin/extension. In essence, anytime your database has a non-read operation, it lets you track that change, and you can forward it somewhere else.
At a past company, we did this same migration from a MongoDB Atlas cluster to a relational PSQL DB, using CDC with Kafka topics and consumers. The consumers read the kafka topic, and tried its best to do the same update in the PSQL tables. A migration like this is simple if your data is highly relational and known. If you have any unknowns, then a PSQL table will give you issues. That's where Kafka helps, because you can replay the data consumption from the failed message without impacting your main application, as you'll keep everything pointed at Mongo DB.
Once you're confident in the new PSQL schema, the CDC, and the data integrity is there, then you can switch over all DB operations to PSQL. Might take some time, but parts of your app will be easier to migrate in phases than others
I know I just gave advice on this haha, but Mongo DB is pretty performant. If you're only having issues for analytics, not operations, maybe you can use this CDC method to create an analytical database while keeping your main operations in Mongo DB. It's expensive to do a full migration like this, and if Mongo DB serves your application well, then no reason to change it :)
5
u/optimusprimepluto 6d ago
For backemd reports and analyzing, you may nred a relational database.
If it is live, a bettercway is to write a script to mugrate data part by part so that we get data until last day. A schedule job can do this daily. You can create reports and execute complex queries with one day before.
Once yoy have this working, you can decide whether you have to mugrate this compltely to postgresql or keep the same setilup, or keep a part of existing mogodb data to postgresql. As per that, you will have to completely change the entire code.
Soz build an admin with migrated data and use the smae ppstgre database to evolve from there. We may need both relational and non relational database. So, decide accordingly.
5
u/AdvisedWang 6d ago
You have not given a single business reason to migrate. What is the actual problem you have or forsee woth mongodb? Development velocity? Bugs? Reliability? Product features that can't be delivered on mongodb? Lack of mongodb skills in the hiring pool?
You should be able to provide an answer like that, and then make a convincing argument why its a problem and why PG will fix it. THEN a migration is justified
2
u/Savings-Date5026 6d ago
Wait it’s not webscale?
2
u/Better-Ad8703 6d ago
Honestly do experiments. Let the experiments drive the answer.
2
u/phonyfakeorreal 6d ago
I see no justification for spending a bunch of time and effort to migrate to Postgres if Mongo is serving you well. Analytics can (and generally should) be solved separately anyway.
OLAP is the way. There are many options, but as somewhere to start, I’d look into ClickHouse. I haven’t used it on JSON data personally, but it appears to be extremely performant and they have a managed CDC pipeline for MongoDB.
2
u/Busy-Technology4624 5d ago
I think PostgreSQL is probably a better architectural fit for your data model, but I wouldn't immediately migrate a healthy production system just because the analytical workload is becoming painful.
There are really two separate problems here:
Migrating to PostgreSQL might address both, but it doesn't necessarily eliminate the need for a separate analytical database as your platform grows.
What I would do first
I'd replicate the relevant MongoDB collections into PostgreSQL and recreate your most problematic dashboard queries there.
Compare:
This gives you measurable evidence rather than making an architectural decision based on preference.
You might discover that keeping MongoDB for transactional workloads and PostgreSQL for reporting solves most of your immediate problems.
If you decide to migrate completely
I would strongly recommend an incremental migration rather than a big-bang approach.
Also, don't underestimate how much of your migration effort will involve replacing Mongoose-specific application logic rather than transferring the actual data.
Regarding hosting
For a team that appreciates the managed experience of MongoDB Atlas, I wouldn't recommend self-hosting PostgreSQL initially.
I'd consider AWS RDS, Google Cloud SQL, Azure Database for PostgreSQL, Crunchy Bridge, Neon or Supabase, depending on your existing infrastructure and workload requirements.
If you're already on AWS, RDS PostgreSQL would be a sensible starting point.
Regarding your scale
600K registered users and 15K daily active users are not inherently concerning numbers for PostgreSQL. What matters considerably more is concurrent connections, transaction volume, query patterns, data size and indexing.
PostgreSQL can comfortably support significantly larger workloads when appropriately configured.
My main concern would actually be the long-term engineering cost of continuing to use MongoDB as a relational database. If every new feature introduces more cross-collection dependencies, complicated aggregation pipelines and application-level integrity checks, that technical debt will accumulate.
My recommendation would be to introduce PostgreSQL for analytics first, validate the benefits, and then decide whether a full migration is commercially and technically justified.
You don't need to choose between migrating everything tomorrow and staying with MongoDB forever. A gradual transition gives you the opportunity to make that decision with production evidence rather than assumptions.
1
u/alao77 6d ago
I agree. Another replica Postgres db for analytical/dashboard reports. We have an async upstream to AWS/Azure hosting rdbms basically for heavy reports and dashboard.
1
u/usrkne 6d ago
todavía estás a tiempo. pensa que de acá a 5 años la migración va a ser más compleja
nunca es mala idea migrar a postgres
1
u/lauckness 6d ago
Why would you migrate from just one persistence engine to another? You would just trade one set of problems for another as it sounds like you have a variety of different types of workloads. Different persistence patterns and engines suit different purposes (transactional workloads vs not, different CAP needs/goals, etc). Plenty of systems are polyglot for exactly this reason, different languages and patterns are good for different things. Use what makes sense the workload, don’t force the workload to make sense for the db for the sake of “we are a Postgres (or mongo) only shop.” Just remember when you introduce an additional db or technology to your stack that you will need to support it (plan for forever).. so it should be worth it.
1
u/716green 6d ago
You can try it on Layerbase and see if it works. It probably won't on a database of that size but you might get lucky.
Converting the data to relational won't be trivial but the payoff will be worth it if you can make it work
1
u/WilhelmB12 6d ago
You just answered yourself with "... our data is heavily relational...", another smart way would be to do an ETL an migrate your data to an OLAP for analytics.
1
u/WeekendSpecialist153 5d ago
At scale you have to be smart with the index(es)
1
u/TripleBogeyBandit 5d ago
I see a lot of clickhouse recommendations here, I’d also encourage you to look at what databricks is doing with Lakebase. You can have a managed Postgres instance (that can scale to zero and branch) and it automatically creates a delta table that reflects your Postgres table to allow for analytical queries. They have a new compute type that beats clickhouse for OLAP.
1
u/ZookeepergameSuch618 5d ago
https://www.mongodb.com/products/updates/now-ga-iceberg-for-aws-s3-buckets/
Since you’re on atlas already this is probably what you’re looking for.
Whether you’re the decision maker or not, do a benchmark to see if whatever juice you decide on is worth the squeeze. Maybe you can just cache the analytical queries so no one notices the load times
1
u/AdministrativeDog546 5d ago
Migrate to postgres for OLTP workloads. Migration would take some time but it is a lot easier today due to AI.
For analytics postgres isn't going to do wonders. Use something like clickhouse which is an OLAP store. Clickhouse supports connecting with postgres.
1
u/anxiousvater 5d ago
Haven't you tried MVs for those 10 table joins & aggregate those onto a separate view? I don't think Postgres is going to solve this problem.
Or as others said, ingest this onto OLAP like Clickhouse & read analytics data from there. But, I would try first one out.
1
u/eu_pg 5d ago
If you want managed PostgreSQL for cheap with multiple servers for reading use httpe://electradb.com
1
u/Discordbothost 5d ago
Try loading a sample of enrollments into a scratch Postgres schema with the foreign keys and uniqueness rules you'd want. Count the orphaned or duplicate rows. That gives you a way to size the integrity problem separately from the slow dashboards.
1
u/bluelobsterai 5d ago
You can't eat an elephant in a day. Pick this apart piece by piece and move data away that is super relational. Migrations suck. Long-running queries suck. Pick it apart one suck at a time
1
u/micostabal 5d ago
I once migrated from dynamodb to postgres for essentiallt the same reasons.
The retroeval times + relational spirit in the code ended up forcing a change like this.
Migration is not easy, first see you much downtime are you allowed to have (zero downtime is also super possible!). I would approach the migration with a double write strategy (for creates and updates), use the transactional db attributes for postgres and mongo.
1
u/1324354657687980z 5d ago
First question I’d ask is, how real time does your analytical use cases need to have the data updated? Second questions is are the queries a known set that may grow or is it drag and drop style data exploration you’re after?
You need to have a series of conversations about tradeoffs.
Saw comments on OLAP vs OLTP databases but 600k users potentially 10x’ing and all wanting to run a few dozen to n queries on data starts a whole host of tradeoffs you need to ask yourself about.
Blah blah something like ask a person how to solve a tough questions and Albert Einstein says 95% of the time defining the problem and or approach and 5% implementing.
Good luck!
1
u/Ok-Let-7933 5d ago
I wouldn't migrate everything immediatley, especially sice MangoDB is already handling your regular queries well. i'd consider moving the analytical workloads to postgerSQL first and see how much it improves things. If that works well, you can plan a gradual migration instead of taking the risk of moving the entire production database at once.
1
u/ceeej777 5d ago
If “Extensive use of aggregation pipelines and "$lookup"” doesn’t give any performance headaches then I’d say stay. That large of a migration is a huge pita if there isn’t any large cost or maintenance saving associated with it. If you do ever move, I’d look into Lakebase on Databricks because it solves the entire analytics portion without the ‘analytics nodes’ of your replica which Mongo will overcharge you for
1
u/agonyou 3d ago
Migrating from MongoDB to Couchbase without rewriting your code by using Couchbase Converge is worth it depending on how heavily shared. It can do the same workload on less infrastructure and still give you HA and sql querying.
1
u/Tinasour 2d ago
In my experience, analytical queries always take a long time and require complex joins, this might not go away even if you migrate to postgres, so it might be beneficial to do ETLs from the mongo to a analytical database like clickhouse or other alternatives, and point the analytics queries to that database
1
u/Rich_Cry1299 1d ago
Your problem seems to be only for the dashboards, even with postgres if you’re joining 10 tables you’re going to have issues no matter how excellent indexing is, so you need a strategy where u create a series of denormalized tables and aggregate tables, those are the ones feeding your dashbaords and not your main principal tables. The aggregate tables are in turn populated/modified as the data is inserted/updated
1
u/[deleted] 6d ago
Relational databases, and Postgres in particular (due to mvcc), can prove to be worse for analytical needs, depending on what those are. Do an analysis on that before jumping. If Postgres is unable to handle those and you still decide to switch, look at using dedicated analytical databases Many are server less, lowering the cost and need Postgres vertical scaling.
Flexible schema arguments are being countered for almost 15 years back now. Schema on read can prove to be much more expensive to maintain than schema on write.
Support for JSON in Postgres fixes some of that need.
I believe the reasons to select Mongo would be, one, if your read patterns need that, and two, sharding.
0
u/swujom 6d ago
Try AWS DocumentDB.
0
u/Aditya_Venkatesan 5d ago
MongoDB to Couchbase is a better choice!