194 points · by wheresvic1 · 10y ago · 183 comments
I've been using Mongo recently, and every time I raise criticism of it, the counterargument I hear is "forget about normalization! Duplication is okay."
Like the author, I really cannot wrap my head around this. While I understand that duplicating documents across collections may make querying faster, what about when you want to change the document? You need to propagate the change across every duplicate of the document in every collection where it exists. This means that any "de-duplication" logic needs to happen at the application level, rather than the database level.
Parse.com provided an interesting abstraction around that with "cloud code" and beforeSave and afterSave triggers. To maintain consistency, they encourage propagating updates to a document within its collection's beforeSave function. So if a document changes in one collection, you write code to change all instances of the document in other collections. That's nice in that it almost feels like you're writing the dedeuplication logic in the database layer, because you can view the "beforeSave" and "afterSave" functions as extensions of the schema. As long as those functions are up to date, the schema and any pseudo-linked documents will stay up to date.
But I really don't buy it. The strengths of mongo encourage a design that necessitates complexity for any significant write operation.
I think the real issue is that "if you have a hammer, everything looks like a nail." Mongo and other NoSQL stores have some real use cases, but people who are more familiar with Mongo than RDBMS are too trigger happy to employ it as a solution to problems where a RDBMS is the clear solution.
If you have semi normalized data relationships, Mongo really doesn't fit the bill that well as your primary data store.
Where it shines is when you've got computed pieces of data to display (parts of a user data feed for example, data for a live graph, etc), you want to quickly store some data to be processed later (analytics, event processing), or you just use it as an object cache for expensive queries.
I have found that with a decently tuned DB, and I mean barely tuned, a decent data model, and sane fetching strategies (don't eager load everything always), a database can be good enough for quite a while, if not forever.
The answer I pretty much always get from people when I ask, "Why did you start with (whatever NoSQL they chose)?" Is, "Because (whoever) said it's faster and scales better."
I think younger devs that have options besides relational DBs find the barriers to entry on NoSQL lower (it looks mostly like how it went in and it's just JSON) so they pass over the learning SQL and basic data normalization fundamentals.
Not having to think rigorously about the logical structure of your data is a huge selling point for many. For programmers, because it means they don't have to think. And for employers, because it means they can make do with programmers who don't want to think.
I'll play the devils advocate: what ever logical structure of the data you come up with will not line-up with relational DB tables - I have had the pleasure of designing relational schemas for cyclic graphs. Hell, we have been trying and failing to do Object-Relational Mapping for years now, and it's still a shit-show. I could name a long list of ORM libraries and an even longer list of their various deficiencies.
Say you've thought rigorously about the logical structure of your data and v1 is out, and now a change comes along and you need an extra field or 5. Renormalize your structure, write some migration scripts (in both directions, just in case you want to downgrade). With NoSQL I'll just dump the new document structure and call it a day (or rather, deal wiht the differences in the application layer).
In other words, the application probably needs to deal with normalization and schema if it's taking copies of data, and using a relational database doesn't remove this requirement. (Of course, small applications often get away without enforcing schema, with the understanding that frequent database write failures due to malformed data are ok.)
Pretty much the classic http://www.mongodb-is-web-scale.com/?
My point is that we deal with these problems out of necessity. If you don't get a ton of traffic, then sticking with a normalized RDBMS is probably best. However, large scale systems will have redundant logic. Generic solutions (letting the normalized DB do the work) will often be slower than specific ones (denormalizing your schema and moving logic into the application layer). These are pretty simple principles that I've seen on almost every large-scale application I've worked on.
They are denormalized data, sort of.
Uhm, no. Data warehouse is not a database with operational (i.e. current) data, it's a database with historical data. If it is out of sync with production for a day or a week, it's totally OK, depending on its design.
So no, cache invalidation is not a solved problem there.
You're assuming that you need to change things. Almost all big-data approaches work better when you abandon that and go for a log-structured model where you only ever append.
> I think the real issue is that "if you have a hammer, everything looks like a nail." Mongo and other NoSQL stores have some real use cases, but people who are more familiar with Mongo than RDBMS are too trigger happy to employ it as a solution to problems where a RDBMS is the clear solution.
True enough, but I think the converse is more true. If you're using a traditional RDBMS you're accepting a big series of constraints in exchange for functionality you often don't use. Indices are updated synchronously on every insert, slowing your writes, for the sake of transactional guarantees that most applications aren't written to take advantage of. Queries have to be passed over the wire as strings, so your application will spend a significant chunk of its time building them (hopefully using a library without vulnerabilities to send them over the wire so the database can spend a significant chunk of its time parsing them), or else you get to deal with the db-specific and per-connection quirks of prepared statements, for the sake of supporting ad-hoc querying in a language that frankly isn't great for humans. Tables, materialized views and the like occupy this awkward in-between condition where it's not clear whether you're supposed to create and modify them ad-hoc (and manipulate them programatically) or not; if you really do need to do ad-hoc reporting then they're what you want, but often the performance implications of that make it unacceptable to do in production.
I don't think a lot of cases are good fits for RDBMS. If you don't need ad-hoc reporting then you're better off building a data processing pipeline where you produce your results directly rather than the sort of semi-aggregating you end up with with an RDBMS. If you don't need full ACID then it's not worth paying the performance cost of it. And I don't know why there aren't RDBMSes without better query languages and schema definition languages, but there aren't.
Or you could use stored procedures. Think of it as making your RDBMS into a microservice, if you like.
>>I don't know why there aren't RDBMSes without better query languages and schema definition languages Huh... I always thought SQL was pretty straightforward for most cases. It only gets really arcane when you get into advanced cases (eg, recursive queries) and/or vendor extensions. It does take a bit of a mental shift, but no more so than imperative-style to functional-style, IMO.
There are certainly tradeoffs to using an RDBMS. But I think a lot of people jump to the conclusion that they have a big-data situation when they really don't. I also think a lot of people underestimate the value of very easy ad-hoc querying and already-solved backup/restore.
The trouble is testability, versioning, deployment, and SQL just not being a pleasant language for expressing business logic. And the lack of a library ecosystem. And poor IDE support. And...
Those are implementation details, not inherent properties of the relational model.
Well, better is subjective, but there are RDBMSs with languages other than SQL (e.g., Dataphor with its D4 language.)
That depends on your loads. If you're write heavy, then yes. If you're read heavy, then you're adding extra work to find the current row out of all the appends. If you're read and write heavy, then get used to buying really expensive beefy machines and maybe sharding...
I think a good solution is to use something like DynamoDB and use hot/cold tables. Like, if you're storing something high read/write (i.e. today's olympic stats), keep it in the hot table with a frequent cache timeout. Later, when they become yesterday's stats, move them to the cold table which will basically be read-only, with a longer valid cache.
The problem with MongoDB is that it discourages this type of data management, at least how I've seen it used.
CouchDB does this to a certain extent, but its JSON-document approach is not appropriate enough.
Regarding it as essentially a form of caching has been helpful. In fact there is a spectrum that goes from simple caching to denormalized schema with many points inbetween.
NO VIEWS! NO STORED PROCEDURES! NO TRIGGERS! YOU SQL MUST BE AGNOSTIC!
and stuff like that. However, they pick Mongo or anything like that and yep, they must use anything it provide just by necessity.
---
People:
Using views is easy. Is probably the most simple thing you can get to leverage what a DB can give (plus indexes) and let model the data in different ways and even help in transition from a data model and another.
That's a trade-off you have to analyze to see if it is worth it. If that data is not maintained often then is OK to have duplicated data. One thing you have to realize is that there is no a silver bullet in the CAP theorem and you always would give up something.
The other thing to realize is that not everybody needs a distributed database and most problems will live happily with an old-fashioned relational database.
I don't like MongoDB either, but normalization is not the answer for every project. For some projects, reading efficiency is so important that people are willing to pay for of it in disk space, an increase in writing costs, and even app complexity.
I think the bigger issue is that people are afraid of separating data at clear boundaries, so long as the orchestration is in place. Having definitive data in SQL, and having denormalized documents in elasticsearch/mongo/rethinkdb works very well... other instances (huge read and/or write throughput) may work better in a Cassandra (or other bigtable solution) with application-generated lookup tables may be better. It just depends on your need.
With better support for JSON/XML nested structures and indexes in sql rdbms, it's becoming less of an issue for a lot of types of data/documents.
Like I said, it was pretty crushing on the database... there were a lot of other expensive calculations that ran per request... pre-calculating, caching, and a few other things got some longevity, bit it was a tangled mess of a beast for what would have been 3-4 collections for a document database (mongodb, rethinkdb, etc).
NoSQL is designed to support both of these scenarios well. And with lower overhead requirements by not having to update a central store... It is used in particular for Big Data solutions. Rather than having to be optimized for one or the other as an RDBMS would require.
Normalization also better supports ad hoc inquiries and reporting compared to denormalization; denormalization is an optimization for regularized reporting patterns (responding to a question that a denormalized reporting design didn't anticipate often requires effectively renormalizing the data, which recovers the logical benefits of normalization, at a potentially very high performance cost.)
> NoSQL is designed to support both of these scenarios well.
Without the integrity benefits of normalization on updates, and without the benefits of normalization for ad hoc queries.
OTOH, there are very few uses of normalized RDBMSs where only the write performance benefits are sought -- usually at least integrity is a concern, and sometimes ad hoc querying as well.
Not just duplication. I did some work on a platform that used ElasticSearch as a relatively relational "document" store (that is, a purpose to which a true RDBMS would have been better suited). Besides data duplication, we ran into the problem of data consistency: using the author's TV show example, we would end up with some actor's whose birthdates would be recorded, but some whose age was recorded instead. Some TV shows would list the actors by role, some would just list the actors and the roles in two different lists. Sometimes the TV show start and end dates would be milliseconds since the epoch, some would be dates in YYYY/MM/DD formatted strings. Some would be dates in DD-MM-YY formatted strings. All scattered randomly throughout the data store. Elastic schema means random schema.
Of course we (they) were - lots of it! Just inconsistently...
The consensus is that relatively few applications are a good fit for MongoDB, irrespective of scale.
Compared to just using Postgres or even MySQL I do not understand the benefit. It takes less than an hour to spin up a PG database with user permissions and migrations to make tables and indexes.
TFA says: "In 2010, when the Diaspora team was making this decision, Etsy’s articles about using document stores were quite influential, although they’ve since publicly moved away from MongoDB for data storage. Likewise, at the time, Facebook’s Cassandra was also stirring up a lot of conversation about leaving relational databases. Diaspora chose MongoDB for their social data in this zeitgeist. It was not an unreasonable choice at the time, given the information they had."
Yes, it was an unreasonable choice. This is basically saying that the cool kids are using document stores, so we should too. There is no discussion of requirements, no recognition of the obvious conflict between Diaspora's data model and MongoDB's, and no discussion at all of the need for transactions, let alone distributed transactions!
TFA says: "In this post I’ve talked about how we used MongoDB vs. how it was designed to be used. I’ve talked about it as though all that information were obvious, and the Diaspora team just failed to research adequately before choosing. But this stuff wasn’t obvious at all."
Of course it was obvious. If you have a highly recursive data structure, and you decide to basically store the result of a seven-way join in a single document, then there is duplication. You should know, just from your earliest programming days, that duplicating data in data structures leads to grief. How are updates going to be handled? And if you decide against duplication, you have to do the joins, and clearly MongoDB doesn't solve that problem. So even before worrying about transactions it is obvious that you have a problem.
Finally, they migrate to MySQL and (then also? in addition?) Postgres. Although I don't quite see how this fits their database per pod architecture. I'm guessing that each pod talks to -- what -- one centralized database? Maybe they will eventually figure out what's wrong with that.
Oy.
You hit the nail on the head. I posit that this problem is caused by the Agile mindset that says "we don't need to collect or discuss requirements upfront. They change too often! Instead, we will just start hacking and change things as we go along." Two years later, the team is running into all kinds of complex, hard-to-reproduce problems, and they realize that they have made a terrible mistake picking MongoDB and they have to undertake a very painful migration and rewrite of the backend.
> You can see why this is attractive: all the data you need is already located where you need it.
That doesn't sound attractive at all. That sounds more like a recipe for "we use five hundred times more RAM than the deduplicated data that we actually have" type of disaster.
...All for a production data set which could be "turned into about 1.2 million rows in MySQL." I think the moral is "If you think your data is too big for a relational database, you're almost certainly wrong."
Denormalization. It's not always the answer, but sometimes making reads easy and writes more difficult isn't bad for the problem set. The funny thing is a social network at scale isbt going to be able to use a traditional SQL database without sharding it and killing joins. It will be a documebt DB with limited SQL features.
As for Mongo, it is sold as the answer to everything just like any other product. It actually fits some problems sets. I actually had great success with it, at scale, in an Amazon division. It ain't the answer for a lot of problem sets though.
I give this blog post two of five for bringing up a mildly interesting topic HN already beat to the ground with misguided conclusions.
Today I am fighting my enterprise bureaucracy to get MOngoDB for our enterprise applications .FUD like this allows armchair architects to quote this article to spook the management and we are stuck with stuffing json as in a RDBMS tables.
1) The developers clearly weren't experienced enough to know what document storage is and when/where it shines/fails. 2) Author jumped on the ever-boring 'i hate mongo' easy train. 3) I am so sick of technology becoming a religious war.
Previously, Mongo had very serious problems in that are because its client would assume that any message sent to the outgoing socket buffer was persisted "well enough", which was an obvious untruth [1]. This was also one of the somewhat underhanded techniques they used to achieve their early benchmarks.
As of version 3, they have defaulted their client's "write_concern" value to "1", which means that it will wait for confirmation from a replica set's primary before considering a value persisted [2]. This puts Mongo roughly on the same level as any other database in terms of durability guarantees.
Disk failure is entirely tangential to your original premise that "Mongo loses data". I'm not getting into it, but there a variety of techniques that Mongo (and every other known database) can use to protect against that.
[1] http://hackingdistributed.com/2013/01/29/mongo-ft/
[2] https://docs.mongodb.com/manual/reference/write-concern/
> Error establishing a database connection
Or is it truly an error? In a page that from the title is bashing another DB
It is not "bashing" to say, "I do not like this and by the way, it's unsafe." Especially when the Mongo project has been so resistant to fixing these core issues and instead are happy to sell expensive consulting and training on workarounds for the issue rather than addressing their core technology's issues.
It's a different kettle of fish when there's writes; but for reads, it should be a walk through the park.
As someone who used MongoDB extensively in the past (8TB+ of data) and also managed the devops side of things, I can tell you straight out that MongoDB has a place in a lot of startup stacks.
I would likely not use it as a main source of truth for any application. However for a lot of things, it's a good database.
Since I can't read the post I can't really address the points made in it, so at this point enough said.
I really don't understand this. In what case is it every acceptable for a data store to lose data? And that's not even MongoDB's only problem: it memory leaks!
There are a lot of applications where your database is not the or even a source of truth, but effectively a big cache that you can either fully rebuild or where rebuilding isn't necessary (the data is too "fast moving" for there to be much point).
Here is another: A search engine for classifieds where the source of truth of 99%+ of listings were external feeds that'd get re-crawled at least once a day. If we lost a few million updates, who cared? If it was few enough, we'd just let the normal updates take care of it. If we had a major problem, or needed to do a major update that'd have compatibility implications, we could just do a re-crawl of all the feeds.
Here's another one:
You're scaling reads by replication, and so the vast majority of your data exists in multiple data stores. You may choose one you consider reliable for the source of truth, and the rest are basically caches, but you may want/need something more capable than a straight up key/value store for various reasons.
I believe the vast majority of data stores I've worked with have been ok to suffer a total loss of because most of them are not the source of truth, and the source of truth can be re-queries fast enough for it to not be a big deal to deal with losses in secondary copies.
This use case doesn't mean it's okay to lose data randomly. Cache invalidation should happen intentionally via an intelligent algorithm, and other data stores (such as Redis) provide this.
> Here is another: A search engine for classifieds where the source of truth of 99%+ of listings were external feeds that'd get re-crawled at least once a day. If we lost a few million updates, who cared? If it was few enough, we'd just let the normal updates take care of it. If we had a major problem, or needed to do a major update that'd have compatibility implications, we could just do a re-crawl of all the feeds.
Just because some data loss is acceptable doesn't mean it's desirable, and while I agree that most of the time some data loss doesn't matter, I don't think you can actually say it never will. What if the 1% listing happens to include an client's feed when the client is doing a major product launch?
> You're scaling reads by replication, and so the vast majority of your data exists in multiple data stores. You may choose one you consider reliable for the source of truth, and the rest are basically caches, but you may want/need something more capable than a straight up key/value store for various reasons.
Again, cache invalidation should happen intelligently via a well-thought-out algorithm, not by randomly dropping data, and there are solutions which supply that.
> I believe the vast majority of data stores I've worked with have been ok to suffer a total loss of because most of them are not the source of truth, and the source of truth can be re-queries fast enough for it to not be a big deal to deal with losses in secondary copies.
Okay, I don't buy this, but let's say it's true. What about the memory leaks?
And what if your needs change, and you're no longer okay with data loss? Are you willing to take the risk that you're going to have to rewrite your storage layer because you chose a data store that drops data randomly, and your needs changed?
> In what case is it every acceptable for a data store to lose data?
This is usually acceptable on analytics data, session data, on most of the "big data" applications... In fact, data that you can not lose whatever happens is the exception, not the rule.
Anyway, when in doubt, it's certainly better to err to the side of security, not risk. Even more because all that security is already written into some middleware that you can simply install and use.
Memory leaks weren't a huge issue for us as well. After stabilizing the setup I have to say it was basically a fire and forget part of the stack for us.
The role of MongoDB was to act as a fast-insert and aggregation framework for other parts of the system.
So, we would insert BIG amounts of data at a time and aggregate it into a K/V store where we pulled the data from.
After a while, the setup became to expensive to run, at this point we turned it off for a cheaper solution, but in terms of functionality, it functioned pretty well.
How do you know? Was your data checksummed? Did you read back changes after writes to verify what was written?
Okay, but numerous people have experienced data loss using MongoDB. You can spend 10 minutes on Twitter and find someone talking about it.
> Memory leaks weren't a huge issue for us as well. After stabilizing the setup I have to say it was basically a fire and forget part of the stack for us.
"After stabilizing the setup"? So basically you worked around MongoDB's stability problems instead of choosing a solution that didn't have stability problems?
> The role of MongoDB was to act as a fast-insert and aggregation framework for other parts of the system.
Sure, but there are other solutions that can do this without MongoDB's issues (i.e. Cassandra).
> After a while, the setup became to expensive to run, at this point we turned it off for a cheaper solution, but in terms of functionality, it functioned pretty well.
Sure, you can build something stable on sand, but it's going to be a lot harder than just building on a solid foundation.
what the point then ? MongoDB isn't even good for analytics and big data. What do you store in MongoDB ?
I am okay if others continue to use MongoDB. It will keep my team gainfully employed ;)
The only thing it’s good at is storing arbitrary pieces of JSON. “Arbitrary,” in this context, means that you don’t care at all what’s inside that JSON. You don’t even look. There is no schema, not even an implicit schema
They changed over and everything was fine.
I always struggle with when not to use an RDBMS, because I work with Teradata at the office and so far it hasn't let me down and there's been little pressure to find something new. And my industry (insurance) does not do new for the sake of new.
after: mysql is sooo much easier with joins. Who cares about sharding anyway.
I hope people understand distributed systems a bit better today, but I don't have high hopes.
I am not sure the author realize that a relational model is actually a graph.
After about 5 years of the many/varied cases of Mongo losing data, I switched to rethinkdb for my current project. It's an uninteresting, surprise-less database and I like it very much.
Specifically, why is it bad to load a MongoDB document, and then load downstream documents that it links to? What kind of problems does this lead to?
Granted, when I worked with MongoDB, I encountered problems due to its lack of transactions. (It's surprisingly unreliable if you end up needing to update multiple documents; when a relational database can do that easily in a transaction.)
But, assuming you can pick an application design that does single-document updates; why is following links in a document bad?
This can be worked around somewhat. If you only ever update the parent documents, then you can create new associated documents and atomically update the parent document to point to all the new ones. It's a bit of a song and dance, and definitely has limitations and gets complicated fast.
But that's not really what the article complains about!
The context is that I met some of the Diaspora leads in the summer of 2010. At the time, they were ambitious, but very inexperienced. (They did teach me some valuable lessons about encryption!) The reason why I say this, is without some kind of data, it's hard to know if "don't emulate joins in MongoDB" is a conclusion of inexperience; and something that a more experienced developer would understand how to do correctly.
For example, in a message board application, if a join is emulated between a discussion and user objects that just have username and avatar; the penalty of seeing an incomplete update is inconsequential. Either the user sees the old name / avatar, or the user sees the new name / avatar. So the incomplete update problem (in theory) can be handled by restricting "joins" to only when it's okay to see old data.
So, assuming that the incomplete update problem is solvable, at what point do emulated joins stop scaling?
So what do you do when it's not OK to see old data? That's when it breaks down.
There are definitely ways around the issues, but you have to make compromises in how you build the application. If you don't make those design decisions early, you find yourself doing it wrong.
In describing large scale systems, a friend of mine said "Imagine a scenario that has a one in a billion chance of happening. On a 10k qps system, it happens almost daily."
That's how this breaks down at scale. Awkward corner cases that don't really seem likely suddenly become daily events.
- An entire discussion (think hacker news story and all corresponding discussion) is a single document - Each post, reply, ect, has a user ID - I load the post object and then do a "where uid in (all uids in document)" query
Obviously, that has scalability limits, but what are they? In practice, when do you hit them?
Could be a couple of solid weekends maybe with a few friends. A lot of good experience gained from my end that I could see.
By the way 99.99999% of the time a WordPress blog can't establish a database connection is because they used mysql.
Curious to know if he was somewhat inspired by it.
...but this is not a reason to stop using a RDBMS, just a reason to use it in the right places and for the right things. Using it to retrieve objects to fulfill every request is not the proper way. There are caching solutions which shine at performing this task.
...just as there are applications for which a variety of key-value stores shine.
Is that why you should never use MongoDB? :-)
Why you should never use database
1. Redis is great for caching in front of a relational database, and also for running task queues. I've used it personally in both cases. Unlike MongoDB it drops data based on cache invalidation criteria, rather than dropping it randomly. Caching is one of the cases other people are proposing MongoDB for, but it's ridiculous to use MongoDB here when Redis exists.
2. Cassandra is used by Reddit and Twitter--search around and you can find lots of good writing about how they use it. Personally I've only used it indirectly via Stream.io.
EDIT: guys, be honest... if this article appears again on HN today, it's because mongodb haters are still alive and well. Downvoting my comment doesn't make the arguments in this article more valid. At least my comment downplays the importance of this article which is on HN's first page, which makes it relevant.