202 points · by e2e4 · 5y ago · 130 comments
> [...] in some instances you might work with vast quantities of data, or deal with transactional systems that just don’t easily fit the operational limitations of relational databases. And in those cases, you should consider moving some, or all, of your data into a non-relational database.
I've worked with a big application that utilised this approach with good results.
The overall problem was that we had an application tailored for a specific country, but needed to expand to other countries. One of the specific problems was that we needed to store addresses and related data differently for each of the countries' users, and this didn't fit well with the current database schema.
Our solution was to move the typing of this information to the application layer, and just store the arbitrary data in a NoSQL solution. This worked perfectly, and to my knowledge it's still working without a glitch.
This was before RDBMS solutions supported JSON, and if I were to do this again, I'd probably just continue to use MySQL, PostgreSQL or whatever, and store it as JSON in the database.
So, yes, you can get the best of both worlds, but I would _never_ use a NoSQL solution to store all the application's data, independent of the type of application.
> This was before RDBMS solutions supported JSON, and if I were to do this again, I'd probably just continue to use MySQL, PostgreSQL or whatever, and store it as JSON in the database.
Both solutions sound like anti-patterns to me. I was under the impression that the correct solution in an RDBMS would be the introduction of a custom type for the address that would cover all of your use cases, and all the associated operations, indices, etc. (in PostgreSQL, maybe even with PostGIS support for spatial operations and spatial indices). That not only keeps your logic, data integrity checks etc. on the server but also doesn't need text munging for every operation.
One of our addresses that caused trouble is literally: "The yellow sign across the street from the Seven-Eleven at <reasonable address>".
We have one address that's legally in two countries at the same time.
One address is just a whole city. Like the entirety of the city, but also it still needs to be considered a separate place from the city.
It of course depends on your use cases and etc. But I find addresses can be like storing names in a lot of contexts. i.e. Just take the bytes the user gives you and alert them if some service downstream complains, but don't require they change it to meet your requirements.
There are systems to help offer standardized addresses and you can display them as suggestions to the user. But sometimes you get a multi billion dollar company telling you "Maybe the address is legally X, but the bus stops at the yellow sign across the street, and we get 30 customers calling for refunds every week because they didn't get on the bus. So either accommodate this change or we'll need to find a new partner."
Unless cleaning, parsing, and geocoding addresses is one of your core business values, let somebody else do it. It's a lot of work that's never really finished. Find a good service, hand them your garbage addresses, and feel confident they'll do better than you could.
YAGNI
We were using MySQL, and MySQL didn't (doesn't?) have user defined types, so it was really not an option.
(This was back in 2013, btw.)
This is WRONG. With capital letters.
Confuse limitations of (the codebase/the enterprise/the specific RDBMS) with the MODEL:
> And in those cases, you should consider moving some, or all, of your data into a non-relational database.
Making data "non-relational" is not a cure for the above. Is more often than not, a regression (like some on this thread: Using JSON instead of regular tables!).
---
Now where we must focus instead is on make RDBMs more powerful (or more exactly: less constrained that cause less powers).
RDBMS are hurt more for the interfacing (SQL) and the design decisions of 40 years ago, but not because the "relational model" is the reason performance, scalability or anything like that suffer.
P.D: And also: Is incredible how many truly think the "relational model" is agains dynamic data. Even using SQL, that is a subset of it, is HIGHLY dynamic! What is a trouble, is that current RDBMS lack a easy way to embed relations in relation, forcing to detour to sub-optimal, ad-hoc, bug-ridden hacks.
ACID imposes a limitation on scalability, there is no way to escape that. If you want to claim that approximately nobody reaches that scale, that's true, and if you want to claim that you don't need to ditch your data schema, that's also true. But relations aren't worth much without global coherence, and global coherence requires ACID, and will only work up to some size (that fits almost everyone, but not literally everyone).
But is tangential to be relational. You can have relational data in a causal way. Now, i see that some think "relations" are PK/FKs and that only GLOBAL coherence is the only way to make relations to work.
If we can take a JSON and make it valid and correct only in this replica in this moment of time, relational data can too.
With mysql, I love when new people join and they can see and play with actual tables - slap in a good sql viewer and BAM you now have an admin portal. VP wants stats? give them mysql access and slack any sql they want: done .
This is why people invented read models. Because the data model that works for the app and makes it easy to work with there might not necessarily work for analytics.
Generate analytics data from you app model so that both world can move independently.
> Need an admin portal? With blobs you are coding all these custom admin pages.
Admin portal with direct access to database columns? No thanks! IMHO, admin portal should hook into you business logic so that all the constraints are validated. Unless your app is just a CRUD.
Other rdbms often have even better json support.
Addresses now can be entered the way the user prefers.
The relational data model is the best model for arbitrary data - by definition we know nearly nothing about the data and that gets us schema control, guidelines for how to normalise data and joins mostly for free.
In practice unless there is a complete understand your data before starting work (ie, nearly never) the first attempt should be to model it relationally. Then if that proves unsuitable - or the scale is so large that even the relational model is too demanding - only then response is to fall back to something else.
The type of database should be dictated by the application requirements.
Relational databases provide some exceptional guarantees while also being able to run quite large systems.
This means, when you have:
1. Relational data,
2. Queries that are not known beforehand,
3. Data that can fit one server or can be sharded to fit,
that RDBMS is probably the best choice for you.
You may not like SQL as a language but at least there is large body of knowledge on how to use SQL effectively for your problem, how different choices affect performance, etc. And a lot of very good tools to help you with that.
I have seen time and time again small teams to "revolt" against SQL databases choosing something like Cassandra or MongoDB. The effect that the team spends now years learning the new database, complicates their application to provide same functionality they got from SQL for free, contorts the data to the new paradigm.
My team chose, years ago, before I came, to use MongoDB for what is very relational problem. This resulted in huge duplication, performance issues and complexity on the application side.
No, the team does no longer have SQL problems. Instead we have other problems that consume large part of our focus, rather than use it to make the product better.
The answer to questions like 'what is the best DB' is online always 'depends on your use case', but in enterprises is usually 'what upstairs decided'.
Sometimes what happens is that somebody buys X, X is expensive, and so now everybody must use X for everything (even if it is not strictly needed). Usually because it looks silly when X is being paid for on an ongoing basis but not being used for anything important.
Hibernate creates appallingly bad SQL, so “databases are slow”. Particularly when using a getter on a lazy-loaded relationship. A query might end up taking 1ms per record instead of 10ms for 10k records.
You can rewrite all you want in Hibernate and greatly improve performance, but you often need to introduce Projections, lazy/nonlazy flags, in the end you program Hibernate more than you would have written basic SQL. Ah, also you’re writing JQL not SQL, so you need to learn “how it’s written in JQL”. But every Java developer is happy, because it’s Java. Phew, at least you didn’t write SQL!
- Any storage, even file or memory storage, can perform better on production than Hibernate.
- Devspeed is much faster without Hibernate. Source: I’m a founder, initiated a few apps, one is on prod making money after 2 weeks, the other one is still losing money after 18 months, guess which one uses React-Spring-Hibernate and which one used jQuery-Freemarker-Dropwizard.
- But if you want competent developers, React-Spring-Hibernate makes you look young and cool.
It’s sad, because frameworks are as difficult as the maximum difficulty our developers can handle, and if they’re not, they will add a layer. Conclusion: People have no love for databases because they’ve put too many layers before them. But they are not the problem.
The SQL generated by Hibernate is as good or bad as you tell it to; something like inappropriate config causing the n+1 SELECT you describe will instantly show up in any decent dev workflow. You're not bound to JPQL, you can very well use SQL directly too if that benefits your situation.
As any powerful tool, Hibernate ORM requires good knowledge of it in order to use it efficiently and effectively. Use it if you have the problems which it solves; don't use it, if you don't have those problems.
Disclaimer: former Hibernate core team member
I find the the main benefit of ORMs is type safety. Provided you're using the ORMs to also manage your schema (which you really should if you're using an ORM), then the compiler can guard you from a whole class of mistakes. You're also able to change table and column names with trivial effort and without fear of missing updating some SQL query string somewhere and only finding out during runtime that something is wrong.
While it's possible to write LINQ which results in bad SQL, if you didn't have an ORM it would still be possible for developers to write bad SQL anyway. Either way your developers should understand SQL at least a bit and be able to use something like SQL Profiler to ensure that their queries are performant. There is no substitute for competent developers.
There is a performance overhead to Entity Framework in the way it tracks changes to objects in contexts. If you're needing to work with a lot of objects from/to a database, then for these particular use cases you can opt out of some of these convenience features to avoid the performance costs.
ORMs are an incredibly useful tool if the trade-offs make sense for your project and you know how to use them correctly. But as with any tool, if you use it inappropriately, you're going to have a bad time.
Want to know my secret? It's very simple. I just read the manual in 2004.
After using it successfully for so long, I wrote a best-seller about how to get the most out of it:
https://www.amazon.com/High-Performance-Java-Persistence-Vla...
And, just because afterward I even worked on Hibernate to add all sorts of performance improvements to it, it doesn't mean I don't love SQL. In fact, I happen to run a High-Performance SQL training too:
https://vladmihalcea.com/trainings/high-performance-sql/
Your comment is based on a very common misconception that Hibernate aims to replace SQL. If that were true, then why do you think Hibernate has been offering the createSQLQuery (a.k.a. createNativeQuery) since 2002?
Why not save a lot of time and bugs and use a battle tested ORM and drill down to SQL for the queries that really matter instead?
There’s also a middleground where developers learn to use the ORM better. I’ve seem people get terrible performance using the Django ORM, but after a rewrite, redesigning the queries and using the more advanced features performance would improve massively. The problem is that need to be able to write the SQL and then mentally backport to the ORMs syntax.
We’ve had customers complain about poor database performance. When we find the horrible queries generated by their ORM it’s frequently easier for the developer to just request more hardware or ask if we can: “performance tune” the database.
With a query builder, you can still use the database in a type-safe way and without gluing strings together, but accessing the database is also more explicit, so mistakes are harder to make.
It's fine to represent the result of a database query as a sequence, but its type and interface should be different from that of eg. a list datastructure, because it can fail. similarly, if you have "User" objects representing users, it needs to be explicit which methods fetch data from the database and which use only in-memory properties that code may freely access. Preferably, have different types for "UserInDB" and "User" altogether, with some glue to go between them.
There is nothing inherently slow about Hibernate (other than people not knowing how to use a tool and blaming it), and frankly, providing a unified SQL dialect that ports over another DB is a plus.
In practice the developers go overboard with SQL - the native-first SQL actually makes for quite confusing data model. There is value in clarity that limitations of Hibernate model brings or promotes.
With MyBatis approach the underlying DB can contain incredibly bizarre joins, crazy FKs, you find aggregation functions in queries trip you up, massive views used under the hood, triggers make appearance to confuse you, the list just goes on.
(The reason this happens is as years tick by, extra requirements get fitted into SQL model by doing these "clever hacks" and avoiding re-architecting. The kludges pile up, it's done because it's possible to do so, and every little decision seems like fair tradeoff when made in isolation. End result = massive pile of confusion.)
You think staying close to SQL is the salvation, but really it's just another way to hang yourself. I will not argue it's possible to do excellent work, but in no way it's guaranteed.
Talking about "NoSQL tradeoffs" implies all non SQL databases share similar features, operational models, use cases, etc, which is simply not true. For example, DynamoDB, Mongo, and Fauna have absolutely nothing in common.
Eg:
Fauna is considered a NoSQL database and doesn't have any of the drawbacks the article mentions. It has ACID guarantees, a relational model, and strong consistency.
Mongo and Dynamo also offer transactions with ACID guarantees these days.
Etc.
Perhaps your comment was meant to say that in general talking about tradeoffs can fall into that trap, but the article here looks like a good discussion
I'd say it's more vague than abstract.
For example, what dbs is the author referring to when saying things like "NoSQL databases generally make tradeoffs around these guarantees." when referring to ACID?
This seems to be an outdated view. These days, all major NoSQL databases offer transactions with ACID guarantees.
NoSQL should mean: No-SQL, No SQL query language, and therefore no required implementations of the SQL standard (tables, relations, transactions etc).
A lot of "NoSQL" databases actually include an SQL layer.
Heck. CSV is NoSQL too.
The transaction model is one of the things which would be nice to be able to select (eventual-consistent, non-consistent, consistent). In case you have different performance requirements. Similar to UDP vs TCP. But again, it has nothing to do with no-sql.
There was a term - object database. But it was old, so it couldn't be used. Then it was document store / database.
Caching and naming things are the most difficult parts. But instead of selecting a name that makes sense and reflects a system/architecture/we, we let some marketing people (read - advocates) promote a new, seo-clean, name.
Except that it does not. It does mean „Not Only SQL“, and not „no SQL“.
This turned out to be misleading, so the Not Only SQL was suggested as an alternative name.
Furthermore, the article is uninformed and writes as if "NoSQL" is an alternative paradigm to SQL. In fact, NoSQL covers a whole range of paradigms and approaches, from key-value, to document, to graph, to more exotic flavors. Some of which can even be queried with SQL
ACID can be a feature of other database paradigms as well, if necessary. With MongoDB Atlas, for instance, an engineer can ensure that data consistency is high priority across clusters. Or not, if that's not important.
On top of all that, table-based database management systems are designed to prioritize saving hard drive space over cpu cycles. As cpu cycles have become more expensive relative to "hard drive space", the need for this kind of database has declined.
Exactly, and that's my whole point.
> Except that it does not. It does mean „Not Only SQL“, and not „no SQL“.
That's a (silly, IMO) retronym. "No SQL" means literally no SQL in English, and that's all the original "NoSQL" DB evangelism meant, too. Later, as they found their paradigm more or less sucks, the proponents retrofitted -- more or less hastily, frantically, or desperately -- SQL to it.
The original dBase and Paradox formats were also databases, and didn't have SQL: They were the canonical "NoSQL" databases. Are you claiming they're now somehow "Not Only SQL"?
You're tech-gaslighting
Take LMDB as an example. LMDB is a fast low-level KV storage engine. NoSQL here, but with full ACID semantics & usable as a backend for whichever DB flavor you so wish to implement. LumoSQL and the older sqlightning are sqlite implementations backed by LMDB.
Since then there were tons of small projects but none handled the atomicity and solidness as good as SQL databases.
After all these years, I thought the advantage and trade-off of different database should be well-understood. But the fact is, there are still lots of mis-infomation floating around.
It looks like the lesson we have learnt are not communicated to border groups of engineers.
When I talked to my dad about RDBMS he was like "weeeelll, sure, there's things like DB2 UDB that do relational but performance wise, nothing beats reading the data straight by key in exactly the format you need.".
DB2 UDB: "Initial release: 1987; 34 years ago". I.e. what he would rather use and is sort of the NoSQL equivalent is _even older than that_. DBM (Ken Thompson - released by AT&T in 1979) comes to mind, tho I don't remember exactly what it was he was using/referring to, which would have been something that would rather run on S/360 and S/370 systems. It's been a while.
Background: he started off with 360 assembler and worked all his working life on IBM Mainframes and the various technologies in and around it. They had it all and they had it before it came to "us". We're just re-inventing most of these things on much cheaper and more open hardware and software.
All that to say: We still need these kinds of articles, because people "tend to forget". Or not even check "prior art". There was a recent article and comments around even research papers essentially being re-done and presented as novel research. And on some level that is even correct, because the authors genuinely came up with the same ideas and research as the original authors did. But 20+ years after the fact.
Schema, stability, performance, fault tolerance, and the full laundry list of things is available in either form.
> OOP is the Roman numerals of paradigms
> C is a PDP assembler that thinks it’s a compiler
Yup, everything popular is evil and bad. Run away to your ivory towers.
Not doing relational again.
Define "scale" and "cheaper".
I have some SQLite databases that are chewing through over 1K writes per second in production (WAL=on). Many of our transactions resolve within 10-100 microseconds because the application process and the database process are the same thing.
SQLite seems to be one of the cheapest options available, being totally free and of negligible footprint. It's also exceedingly cheap in terms of engineering complexity and scary unknowns. Something about being literally the most deployed piece of software on earth seems to help.
NoSQL reads like a religion to me these days. Starting with something that is actively trying to tear itself apart due to the inherent complexity seems like a horrible way to build a 5 user POC.
Is that with synchronous full(2) or normal(1)?
What's your SQLITE_THREADSAFE mode?
Would it be 210 writes in a relational db though? Our product at work started on Firestone and one of the main problems was it was causing us to have to do far more operations than we would otherwise have needed. E.g in a relational db you can do UPDATE WHERE or DELETE WHERE in a single operation. I’m Firestone that’s a get followed by an update/delete for each record!
I guess it depends on your workload, but we’re the opposite: never doing Firestone again!
200 writes/second is not even scale, a single instance would handle that fine, with beefy hardware you could do 100x that.
You could even run it in cloud, for about $50/month, and as a bonus use the same instance to perform the analytics which will be real time.
Not to mention enjoying much better data integrity.
Also, and this is neither here nor there, I thought Firebase hit a hard user limit of 1,000,000 daily users.
You’re enjoying vast economies of scale and for practical terms it’s fine. For now all those bits with cute names aren’t dinosaurs but for damn sure they aren’t sharks.