175 points · by jpmc · 15y ago · 124 comments
Granted, you often had to actually write Stored Procedures by hand back then. But then if you look at the LINQ in the article, you'll notice that it's pretty much exactly the SQL you'd stick into your stored procedure, just backwards. Had they not bothered introducing LINQ in the first place, they'd have had their 100x performance boost from the get go.
Naturally, SP's are not some magic 100x'ing cure-all. They're just a non-generated version of your SQL, which means that you're guaranteed never to have your ORM go nuts and build some monstrosity like the one outlined in the article.
You still need to tune your SQL by hand, but at least you can tune the SQL rather than some not-particularly-helpful abstraction on top of it.
SQLBooksOnline actually has this information clear as day, but MS Evangelists like Rob Howard (went on to create Teligent) would go around spouting the "sprocs are faster!" line and no one would ever think to point out the discrepancy. It just became religion for the masses of MS platform Developers.
ADO.NET (and whatever it's called these days) executes all Parameterized queries through (see if I can get the casing right) the sp_execsql procedure. This means that the Query Plan for every query run on ADO.NET is cached. IIRC the only additional step Stored Procedures avoided was Parsing. Execution for either would come up with the same, cached plans, but sprocs wouldn't have to parse each time.
Who's willing to bet that the SQL Parser, with decades of optimization work, can parse 100% of your queries in a few hundred nano-seconds?
In practice then, that savings doesn't matter. In side-by-side tests I did a few years ago (that anyone with a few minutes can replicate), there was effectively no performance difference between the two. So the parsing savings were swallowed up as noise in the actual network-latency/query-execution formula.
At the end of the day then, sprocs are not the solution. The solution is to avoid dynamic SQL, and use Parameterized queries. Generated queries that aren't Parameterized do not cache their query plans (last I knew, but it's been years, so maybe that's changed) and won't perform as well as sprocs.
The problem isn't LINQ then. If you know how the gears underneath it all fit together, you can easily avoid sprocs with no negative performance repercussions.
I think it's a terrible idea, but I've seen multiple places where there is a very blurred boundary between stored-proc-for-data-access and stored-proc-for-data-access-after-a-bit-of-business-processing
Versioning of SPs was hard. Code control for SPs was hard. Automated testing of SPs was hard. Incremental deployment (e.g. rolling out the new code to half of the servers in the web farm) was hard. Parallel development against a shared dev/staging server was hard. Trivial schema updates were hard.
And even then, it was never guaranteed to be fast. If the underlying tables weren't indexed, or your stored procedures did stupid shit like use cursors or temporary tables, it was still slow.
Nothing has changed in the last 10 years to make it harder. Granted, many shops weren't doing it well back then, thus the misconception that versioning SQL databases is hard, and that schema changes are hard.
That stuff was only ever hard because people declared it to be so, and built crazy bureaucratic organizational limitations to stop developers from changing the database (because that's hard and therefore not something that developers should be doing.) Once you start thinking of it as easy and build your tools around that fact, you'll notice that it actually is easy.
The example that comes to mind is making a change to a stored procedure's signature. In order to change it, you have to change all of the clients that talk to it at the exact same time. As a result, incremental rollouts become impossible, so you wind up doing high-risk huge-scale deployments or doing things like creating procedures named EntityInsertV2 and EntityInsertV3 or adding optional parameters with defaults or ignoring parameters that the procedure no longer needs but older clients still want to provide.
And then there's cleanup. As you really should remove EntityInsertV1 once all of the clients are using EntityInsertV2, but you can't have that in the same Update SQL, so there's really two deployments for every deployment.
If there's an easy fix for this problem (other than keeping procedural logic out of the persistence layer) I never found it.
Still though, while I don't dispute that SPs (frankly, databases in general) have issues with version control and deployment management, there are still options for managing that sort of issue that don't require the blunt instrument of the ORM tool generating its own set of dependencies and inappropriate SQL for the job, leading to the sort of performance issues that the article talks about....
Except that when StackOverflow started it was a small startup with just three developers and a small user base. They probably made the decision early on to tradeoff any premature performance optimization with the ability to quickly iterate and ship the product by using Linq-2-Sql instead of hand-writing every single CRUD operation.
Now that their business (i.e. web traffic) has grown exponentially and have a larger group of developers they can now go back and optimize and performance tune the code including doing complete re-writes as necessary.
This is an important takeaway for anyone building a startup.
I think there was an implicit assumption that everything Microsoft does is great, and Microsoft would never lie to you. Oh, and the next version will be even betterer! Honest!
Basically the fix boils down to replacing a slow ORM with a faster ORM, and using indexes. Well of course indexes are faster - Duh!
HOWEVER this is where if I was them, I would start to get worried, because every SQL Server horror story I've been told basically starts with "And then the indexes became randomly corrupted" and goes rapidly downhill from there.
My take would be: use a great ORM to develop quickly and maintain easily, but be aware of common pitfalls, set up sensible indices, and have some performance monitoring in place. Tune by hand if absolutely necessary.
MySQL could barely do joins ten years ago. Today, it's still behind where Oracle was ten years ago. You can throw extremely complicated queries at Oracle and it generally optimizes them well. Don't think of MySQL as "fast and highly optimized". It's only fast for relatively simple queries.
When I say complicated queries, I'm talking about 50+ line queries with many joins, subqueries, aggregations, etc. You can run these against tables with millions of rows and still get an answer in seconds, often regardless of indexes.
Just yesterday I rewrote a view that used a database link to act as a materialized view (which makes me feel icky). It ran approximately 10,000 times faster. For a 100-row result that only joins 4 modest tables, there shouldn't be that kind of a difference IMO.
This will sound incredibly mean, but I built a very lucrative career coming in behind people who tried to fix everything in their apps and not the DB.
What's the busiest website that you have experience with? Do you have any experience with scaling to, say, serve more than a million dynamic pages per hour to consumers?
I ask because your opinion seems extremely uninformed when it comes to high performance websites. If you've designed your application right in a traditional CRUD application, everything except the database layer scales fairly easily. The game then is about finding ways to help that remaining bottleneck. Standard techniques include optimizing queries, caching data intelligently, directing queries to read-only slaves, and in extreme cases sharding data across databases. Several of these result in moving more logic into the app, not less.
In fact, many ORMs will happily use CRUD sprocs to save and retrieve complex entities, which compounds the N+1 select problem by passing all columns, every time. Compared to that, raw-SQL mappers like LINQ to SQL are a positive step forward, and leave the door open for more intelligent mappers like Dapper (as mentioned in the article: http://code.google.com/p/dapper-dot-net/)
I found it to be much more interesting and a cool look at how he went about actually finding the slowdown and the steps he took to fix it.
I would go so far as to say that sql writing ORMs are a deeply misguided engineering idea in and of itself, not just badly implemented in its current incarnations. You can't possibly write data access logic entirely in your front end and expect some system to magically create and query a data store for you in the best or even close to the best way.
I think the real reason people use ORMs is because they don't have someone at the company that can actually competently operate a sql database, and at any company of a decent size traffic-wise that's simply a fatal mistake. Unless you are going 100% nosql, at which point this discussion is irrelevant.
ORM's aren't a problem at all as long as you have the ability to override problematic queries with named queries, etc.
ORM's can provide very real advantages when it comes to caching, development time, etc., as long as you review what the ORM is doing and notice when it's doing it wrong.
I've just spent 2 years architecting a high transaction global video game system using an ORM, and it worked well. In our case, the ORM provided acceptable SQL for about 85% of the queries, and we overrode the rest.
The ability to quickly and easily allow the developers to write their own SQL, to be reviewed later by a DBA, was a life saver. Combine that with our stress and load testing, it was easy to see where the hot spots were and deal with them effectively.
The problem comes from people who rely on the ORM to do everything for them without truly understanding how it works.
ORM's, like anything, are a tool, and there is a time and place for them.
In both cases, we had a large number of smart developers who we empowered with the use of an ORM; they understood the domain model, and they didn't have to worry about waiting for a "DB type" to write stored procedures, or develop a data model, etc. As a matter of fact, in both cases, I was the only DBA on the project, and it was a predominately part-time role. We'd meet, ensure we were all on the same page with the object/data model, and then they'd go and build it. The developers were able to immediately build and run and test and integrate something that was functional and operational, when they needed it. This was HUGE, and something that most people don't properly appreciate. Timelines were already insane enough as it was, the last thing we needed to do was artificially constrain ourselves by waiting for other (db) devs before work could go on. Especially when requirements had the potential to change from one day to the next.
In both situations, we took advantage of very, very sophisticated testing procedures that would happen nightly, both functional and stress/load, and it pointed us at the bottlenecks of each nightly build that would require tuning and investigation. We intentionally set up our testing to be able to monitor and test the effectiveness of the ORM, and to point it out when it didn't work efficiently. The devs would do the majority of the heavy lifting with the initial data model, and the results would be tested, reviewed, and then modified if required. The performance modifications were not a lot of effort to fix, either. Usually it was a very slight data model change, or using a named query to take advantage of a database-specific features. And CLOBS. Every database seems to handle them differently, so we had to hack some solutions.
Having done large scale database development for almost 25 years, using the classic stored procedure approach and the ORM approach, I'll say again that ORM's are a great solution for certain projects with the right staff, and aren't a crutch or some lazy choice if used properly.
No you're not. Look at ActiveRecord, it lets you drop to any level of SQL optimization you need. In ActiveRecord 3 with ARel queries are composable, allowing lazy loading and the breaking of queries into appropriate locations according to your code architecture.
I can't speak to other ORMs, maybe they really are as bad as your opinion would indicate, but I suspect what you're really complaining about people who don't know how SQL works being enabled to write horrible data persistence code by ORMs with a pretty facade. That's a legitimate problem, but the fact that a tool can be abused is not an argument against the tool itself. We'll never build anything great if we are driven primarily by what the ignorant will do with it, after all, every single person on the planet is ignorant of most things, our tool development should be driven by what they enable experts to do.
Here's what you're missing, and why ActiveRecord works: if you halfway know what you're doing with a RDBMS, 95-99% of the time the query generation just saves you writing a lot of boilerplate SQL. It's true that sometimes you have to drop to a lower level to hand-craft a query, but ActiveRecord in no way prevents that. Again, I don't know what kind of ORM hell you have been put through, but I assure you that an ORM does not need to be this horrendous performance killing black box that you think it is.
users = User.where(:age => 10) # no rows fetched
# Once you access something on users, then the query happens users.each do |user| # something end
It's not really that "magic", it's useful.
ActiveRecord uses joins (mostly). If you are using a "non-standard" table schema, you can tell ActiveRecord what column to use on joins.
The disadvantage is that due to some organizational dysfunction at MSFT there's still no really satisfactory ORM infrastructure surrounding the query engines.
(as for your "misguided engineering idea in itself" claim, I don't really see how it's fundamentally different from writing SQL in the first place to be translated by the database into query execution plans, vs. writing the query execution plans directly).
As for checking for type safety, I think frameworks that do sql-to-object mapping (with type safety), and also handle cache for you, are a very useful thing. Making raw calls on database connections is definitely too far "in the other direction" :).
I don't have much experience with ORMs or mapping frameworks other than LINQ-based ones, but it seems like it would be pretty difficult to typecheck queries expressed as SQL strings, at least dynamic ones, at compile time. Do the frameworks you mention typecheck the actual query itself at compile time, or do they just check at runtime that the data returned from the query matches what you want?
Then explain the massive success of Rails. Quite simply, you are wrong.
I don't think they're necessarily misguided. DataMapper made efforts to circumvent the N+1 problem, in most cases probably pretty effectively.
Partial Updates are also pretty easy. Slamming every field into every INSERT/UPDATE is obviously a bad idea.
I think the missing sauce for ORMs is funding. Getting the basics together takes time and money, and it's hard to pull off in your free time.
On the other hand, having written many an ORM, I think there's still plenty of room to advance the state of the art. One of the biggest untapped (AFAIK) opportunities is using Statistics for query tuning. It's the life-blood of databases, but statistics are noticeably lacking in ORMs. Even simple counters could allow you to tune lazy-loads, JOINs, pre-fetches, etc on-the-fly.
I don't think it saves dev time at all. It just makes it more difficult to know what queries you're running by looking at the code.
When it's not fast enough (high volume, specific complex queries, whatever) I can write specifically tuned SQL.
Performance tuning on anything that isn't an actual bottleneck is waste.
CRUD stored procedures can be generated directly from the database schema, wrapped in C# objects using the same code generator, and compiled into your project whenever you make a schema change. That gives you all the advantages of an ORM, without any magic runtime SQL generation.
You can't write it faster than an ORM. anObject.save, your SQL can't beat that in tersness and by the time you've written CRUD SQL for one table the guy with the ORM is far ahead of you in getting actual work done.
> I don't think it saves dev time at all.
It saves massive amounts of time, if you don't think so, then I doubt you've used one long enough to be able to have a valid opinion on the matter.
I guess he doesn't deal w/ this level of optimization, or it never hit his radar.
- how big is this table getting? - how are you querying on it?
That usually fixes most problems before they happen. Not sure it's my job to specify a join type though. A nested loop join isn't a bad thing or even a sign of a bad thing happening necessarily.
There's nothing wrong with relational databases, it's just that many of the NoSQL databases are newer, encourage denormalization, and implement things like intelligent sharding and mapreduce out of the box.
Which one you prefer seems to depend on whether you're more systems-oriented or code-oriented (if you have someone dedicated to tuning your database, why not just let them worry about it?), or whether you're just forced to use one by virtue of the platform you're using.
I think we all could benefit from articles similar to this one but applied to NoSQL databases: Take a real-world example of a slow-query in a NoSQL database, show how you identified it and profiled it, show how you solved it.
I've personally been burned with performance issues in CouchDB when it came time to perf-test my queries, and I really would have benefitted from articles that detailed a real-world example like this.
I feel like there's a lot of tutorials on how to create toy applications using NoSQL, and a lot of claims on how things like sharding and mapreduce will let you scale to the moon, but comparatively little information on how to do real-world things like what this article covers.
Things like NoSQL are neat to play with in your spare time, but I'd think long and hard before I'd use them in actual production code. I seem to remember hearing about Cassandra causing woes in the past, for example.
It's not about "latest tech buzzword", it's about using the tool that is most appropriate to the job. Cassandra worked up to a point, but it ultimately was not the right tool for the job at Twitter and Facebook scale. Is that cause to be dismissive of all NoSQL databases?
I agree that you should give careful consideration to your technology stack before putting it into production, but to me that means considering all of the options available, not just the old stuff.
That points to poor caching and poor scalability.
On top of that, you get well-known consistency, transactional updates, and so on. Stuff most developers are used to. So, there's plenty of reasons for picking a traditional SQL database, especially when starting.
Even more so, you don't need to throw SQL away (which is a nice declarative query language) in search of performance. For instance, look at VoltDB/HStore for an example of a SQL-based, table based RDBMS that provides ACID, high performance and linear scaleout. (Granted, with some tradeoffs - it's not for running reports off of, for instance.) On the non-OLTP side, look for massively parallel databases, which still allow SQL while providing amazing scaleout analysis performance. (Downside is that those analysis databases are very expensive; I'm unaware of any cheap or opensource alternative that still uses SQL, except perhaps Pig, but it doesn't really compare, performance-wise.)
Is that why Reddit is having a whole ton of scaling problems while SO seems to be able to scale quite well? NoSQL is not a magic cure-all.
This is a classic ORM problem. The usual solution: apply a Declarative Batch Query. I've even written one of those things! The reason why you might want to code a Declarative Batch Query option for your Object Relational framework? You can then apply it to similar problem queries in a few minutes total and one line of code.
The first operation I optimized went from 2500 SQL calls to just 40, which is an over 50X speedup. And yes, the entire declarative mechanism was written in about a week to satisfy a routine "Change Request," and yes, it ran in production on a heavily used trading application at a major multinational.
http://blogs.msdn.com/b/bartd/archive/2007/07/19/are-you-usi...
It gives an indication of the highest-impact indexes that are missing. Obviously there's room for experts to tweak, but for most it's an excellent quick tool. Don't create every index it suggests, obviously, just use it as a guide to look for hotspots. It's nice because often it'll surprise you with areas you had no idea were an issue. And it takes a few seconds to run.
Moral of Story: Relational database should be used in most cases. NoSQL is overated & extra-hyped.
Can this loop be closed and automated? Why do we all keep having to do this manually?
Part of the problem is that I think most ORM authors know OO but don't necessarily grok SQL, so you get the same failure cases over and over again. It's not easy to write an ORM that can do arbitrary joins and it's borderline impossible to retrofit one that didn't have it built in from day one. The other big failure that you get is a failure to support group queries or arbitrary selects.
Performing a code review the code uses a LINQ-2-SQL multi join. LINQ-2-SQL takes a high level ORM description and generates SQL code from it. The generated code was slow and cost a 10x slowdown in production.
All queries are typically passed through a standard function.
Part of the function logs the queries and times them.
Append them to the bottom of a page or in hidden html comments when special cookie is present.
Awesome that SE have come so far generating every pageview
When I read this I actually cringed, because they changed their SQL query in production without looking at the query plan first. Apparently it's the blind leading the blind over at stack overflow, not that it seems to be hurting them.
I read it as: 1) noticed that's slow in production, 2) look at query plan (prod or dev, not clear) 3) add index (not clear if they did that in dev first and then prod)