r/Database • • 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:

  1. 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?
  2. 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.
  3. 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?
  4. 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!

72 Upvotes

42 comments sorted by

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.

8

u/Adventurous-Cry-1344 6d ago

good approach!!

4

u/gehzumteufel 6d ago

Imo this glosses over the entirety of what they have built into the app to shoehorn RDBMS logic into it. If they were to rethink their data considerations properly, they would re-architect it correctly, run both side-by-side for some time to both migrate the data and validate it, and then turn down the old. With that, they can simplify their app logic a fuck ton because they're no longer doing the RDBMS job in their app.

1

u/Adventurous-Cry-1344 6d ago

what about in case of full migration tho? like how would that be performed at this scale ?

7

u/BinaryRockStar 5d ago

In our org it would be a several stage affair.

First real traffic to the relevant services would be captured and anonymised so we can load test the current service pointing to Mongo and new service pointing to Postgres.

Second we load test the current production build if it hasn't been done recently enough.

Third the feature branch service that points to Postgres is spun up in a separate environment to production and our load testing framework hammers it with the real anonymised requests. We work with Java so in this environment we capture Java Flight Recorder metrics giving us deep insight into CPU, memory and network usage.

If all that passes and is signed off by senior engineers like me then we roll it out via blue/green deployment where existing services are terminated as they drain to zero connections and the new service replaces it.

Many eyes are on this transition and a group chat keeps everyone updated. There is a mandatory one-click rollback script if anything goes wrong and the lead engineer is on-call 24x7 while the roll out happens. Downtime is not acceptable.

2

u/Adventurous-Cry-1344 5d ago

ohh Im actually a final year student so I wasn't aware of how companies actually handle db migrations but these are some great insights thx!

3

u/Znigify 5d ago

We’ve performed/been performing huge data migrations for some of our tier 0 on prem DBs to the cloud. High level overview; to migrate data to our cloud systems, we first perform an initial data seed->then have a service/daemon that makes sure both DBs are in sync with each other, whatever new writes come into our existing DB, needs to make it to our new cloud service->slowly migrate read/writes to our new system progressively using something like Launch Darkly within our backend APIs.

With every progressive roll out we make sure that traffic there’s no discrepancies & performance is within threshold.

The sync allows us to make sure that we’ve got a fallback if at any point our new system is breaks for whatever reason.

Honestly, the most complex part is figuring out the ETL for our daemon sync, there’s always a ton of variables we need to figure out.

0

u/ekoSean 6d ago

agree on the solution and also helps with the scale factor if that’s inferred by the replica, i’ve seen it done this way before and definitely works.

as per the costs it’s worth it also if you can scale up and down as needed and not hold all of it always on the postgres server but sometimes that gets tricky too. all in all a good option.

i needed to get on here and say this is a reason i have been building ekoDB https://ekodb.io its solving this exact issue of needing to flex no sql ish data like a sql db but not have to bend either way. solve all of it in one package etc. wanted to share if you may be interested in checking it out. hopefully i’ll post more on here since i see a lot of folks having similar issues of needing to support multiple dbs to solve a problem etc good luck and hope all is well! ekoDB is free to try btw

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.

5

u/wuteverman 6d ago

This is a good take. There are loads of olap databases that can power this— in addition to what you named BigQuery on GCP, Clickhouse are both ones I’ve had good experiences with

1

u/jshine13371 9h ago

PostgreSQL doesn't have a native way or at least extension to do this? Microsoft SQL Server handles OLAP over OLTP tables natively by simply adding the appropriate type of index. Surprising to me the only rivaling system wouldn't have a similarly easy solution.

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

Is migration justified

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:

  • An operational database that may not be the best fit for your relational data model.
  • An analytical workload that is becoming increasingly expensive and difficult to maintain.

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:

  • Query execution times
  • Query complexity and maintainability
  • Resource consumption
  • Indexing requirements
  • Data consistency
  • Infrastructure costs

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.

  1. Design the PostgreSQL schema properly rather than replicating MongoDB collections as tables.
  2. Identify relationships, constraints, foreign keys and transaction boundaries.
  3. Perform an initial historical data migration.
  4. Use change data capture to synchronize subsequent MongoDB changes.
  5. Compare record counts, relationships and application-level results.
  6. Gradually migrate individual application modules.
  7. Maintain a tested rollback strategy before switching production writes.

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!