News for hackers. Stuff that matters.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jasonkester on Tuesday May 03, 2011 @10:21AM (#2510026)
Remember 10 years ago when this was a solved problem? There were only two rules: "always use stored procedures" and "never build dynamic SQL". Doing stuff on relational databases was fast.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by ssmoot on Tuesday May 03, 2011 @12:24PM (#2510616)
This is the old Microsoft Misinformation. Stored Procedures are not faster.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by nl on Tuesday May 03, 2011 @09:41PM (#2512457)
Ah.. but stored procs are faster if you are executing business logic in them, because you can avoid round trips.

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

[deleted]
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by ssmoot on Tuesday May 03, 2011 @12:53PM (#2510738)
That's a non-sensical statement. Stored Procedures are always parameterized. It's the only way to pass in arguments.

What I'm talking about is a special stored-procedure called sp_executesql. It takes varargs for parameters and executes your query.

Open up Query Analyzer. Run SELECT * FROM users WHERE id = 1;

That's an ad-hoc, not parameterized query.

Now run: sp_executesql 'SELECT * FROM users WHERE id = @id', @id=1

(My MSSQL may be a bit rusty :p, so syntax issues aside)

That's a parameterized query. That's what runs when you use the classic ADO.NET .addParameter interface.

Queries executed that way have their query plans cached.

I spent a couple seconds on Google and came up with this. Looks like a decent overview: http://blog.sqlauthority.com/2007/07/02/sql-server-2005-comp...

If you can actually measure a significant difference between sp_executesql and a stored-procedure call that's news to me. Definitely not my experience, and not what the actual documentation indicates. I'd go so far as to bet that unless you came up with some kind of pathological example you're mis-remembering or misunderstanding what I'm trying to say.

To keep it simple: If you use the .AddParameter interface you should see no appreciable performance advantage to Stored Procedures. If you simply interpolate your parameters (or your O/RM does it for you), then you will pay the price for generating the execution plan each time. Probably not a significant different for 100ms queries, but it could be quite a substantial cost for a <10ms query.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by pradocchia on Tuesday May 03, 2011 @01:48PM (#2510941)
that would be:

exec sp_executesql N'SELECT * FROM users WHERE id = @id', N'@id INT', @id=1

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by ssmoot on Tuesday May 03, 2011 @06:35PM (#2511920)
Thanks for the syntax help. It's been awhile. ;-)

For anyone curious, here's an old article on the interface I'm talking about: http://www.techrepublic.com/article/shorten-development-time... Just so you don't think you have to memorize the above syntax.

I'm not sure what's used these days, but I assume it's fairly similar if not simplified a bit. If it's not broke right?

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Tuesday May 03, 2011 @12:04PM (#2510524)
I remember 10 years ago, and I'm sure as hell not going back.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jasonkester on Tuesday May 03, 2011 @12:46PM (#2510715)
Why is any of that hard? Stored procedures and database schema changes are all written in SQL, which goes into source control nicely. Schema changes are easy in an environment like that. Parallel development on multiple dev databases rolling changes into a single staging server is easy in an environment like that. Just check in your code and let the automated build do it's thing.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Tuesday May 03, 2011 @01:15PM (#2510813)
I'm not laboring under a misconception. I know how to do all of those things, I was doing them, it's just easier not to.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by r00fus on Tuesday May 03, 2011 @01:52PM (#2510962)
> 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.

Assuming all of your clients are all server-side (ie, servlets) and are also in source control, this should not be an issue.

If you have thick clients accessing SQL functions directly, you have a bigger problem (client-server... ugh) that browsers have solved.

If you have multiple servers talking to each other, you still have a version of the "thick client" problem, namely enterprise integration... for which there are intermediary APIs.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Tuesday May 03, 2011 @04:14PM (#2511455)
Assuming all of your clients are all server-side (ie, servlets) and are also in source control, this should not be an issue.

Source control isn't the issue (of course everything is also in source control, this isn't the dark ages).

I'm talking about a pretty common scenario where you have one SQL server and 4 web servers acting as clients. Let's say you want to do a zero-downtime rolling deployment and upgrade the web servers one at a time while the other 3 continue to run. This is a real issue that I encountered on multiple projects that were adhering to the "everything must be in sprocs" dogma. Moving to ORMs and parameterized queries saves a lot of headaches.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jasonkester on Wednesday May 04, 2011 @06:12AM (#2513350)
This doesn't seem to have anything to do with Stored Procedures. Do a quick search & replace above:

  s/stored procedure/function
... and notice that you're simply describing a common issue with building anything. If you change the interface to something, you need to change the stuff that calls it. That's just life, and it's the same story whether you have databases in the mix or not.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Wednesday May 04, 2011 @01:11PM (#2514481)
The distinction is that with functions, I can have my automated refactoring tools help me change them safely, I can have my compiler tell me if I get them wrong, I can have my automated tests tell me if I get them wrong.

By keeping the procedural stuff in the procedural layer and not in the persistence layer, it's easier (for me, anyway, your experience may be different) to keep things encapsulated and make contained changes in contained places.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by eftpotrm on Tuesday May 03, 2011 @12:43PM (#2510695)
Yes, bad table designs and poor practice will make your code slow regardless.

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....

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by rayvega on Tuesday May 03, 2011 @12:17PM (#2510579)
>> "...Had they not bothered introducing LINQ in the first place, they'd have had their 100x performance boost from the get go..."

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by Stormbringer on Tuesday May 03, 2011 @10:46PM (#2512591)
They cover the "why Linq?" question in one of their podcasts... and it basically boils down to if you're drinking the Microsoft cool-aid anyway, might as well drink the whole cup.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by eftpotrm on Tuesday May 03, 2011 @12:51PM (#2510730)
But.... every single CRUD is normally not a huge amount of code and relatively simple to generate from the information schema if you know a bit of SQL Server. Do it that way and you've got your sprocs just sitting there for later use, primarily OK to be used straight out of the box but available for modification as soon as you need something different.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Tuesday May 03, 2011 @01:18PM (#2510823)
You say that like having CRUD sprocs sitting around is a good thing.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by noblethrasher on Tuesday May 03, 2011 @01:48PM (#2510945)
Just curious, why isn't it?
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by gnaritas on Tuesday May 03, 2011 @07:49PM (#2512173)
Your generated procs's are your home-brew ORM, what exactly do you think an ORM does other than dynamically generate CRUD and map data into objects to speed development? The ORM is better, generates it's code at runtime so it doesn't leave a mess behind when things change and removes any need for you to regenerate.

That ORM can generate update statements that only update changed fields... can your proc do that or does it blindly update all fields? That ORM effortlessly maps data from the db into objects so you don't have to pass record-sets around; I don't want record-sets and data readers littered all over my programs, I want business objects.

Programs that keep all SQL in procs are horrible to work on and a bear to maintain, I'll take an ORM any day over a mess like that.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Tuesday May 03, 2011 @04:22PM (#2511480)
All code, auto-generated or not, is a sort of liability in that you have to maintain it. You have to re-generate it each time you make changes, and there's a possibility that someone can mess with it and cause it to break.

My take on auto-generated code is this: If code is so simple/deterministic/boilerplate that it can be auto-generated, then the generation of that code should be completely automated (at runtime, if possible) and the generated code should be invisible and untouchable.

I've never had a pleasant experience tweaking auto-generated code.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by eftpotrm on Wednesday May 04, 2011 @05:21AM (#2513274)
But, if the code is being generated in that way, you're also doing a lot of identical string concatenation at runtime, when identical results with higher performance can be achieved by doing it at an earlier point - compile, design, whatever. You're burning CPU cycles to avoid the existence of these objects and separetly make it harder to optimise your application later when you find you need it in places.

Depending on your application architecture, you're also increasing the chances of your needing multiple round-trips to the database to query various bits of information for building your query, increasing the load on the DBMS (and possibly the network, depending on your architecture) and increasing the query latency.

Properly auto-generated code should be the cleanest, best laid out, most consistent code you work on, quite possibly well commented as well. It's obviously not a panacaea that'll work for everything and I'm not saying ORM tools never have their benefits, but certainly I'm not convinced that third-party ORM tools are right for what I'm doing at present.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MartinCron on Wednesday May 04, 2011 @01:16PM (#2514496)
Sure, ORM tools can be a tradeoff between what's fast at dev time and what's fast at runtime. What has been working for me is relying on the ORM and then hand-tuning the small subset of things that need to be hand-tuned.

And, of course, I don't know anything about what you're doing at present, so I won't even try to speak to that. But I can't imagine a weaker argument against ORM than the first one you made, though. When you're doing data-intensive work, are you really worried about the CPU overhead of string concatenation on your application layer?

:)

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by eftpotrm on Thursday May 05, 2011 @05:14AM (#2516667)
For a decent subset of the procedures I've worked on, yes, I am, from experience. I've had app performance killed by excessive string concatenation before, so my inclination to repeat identical jobs at runtime which I know from experience cause performance issues is limited. Precompile.

I should stress in this though, I'm not a complete 'it must be a compiled sproc stored in the DBMS' guy; I have worked with systems before which effectively provided their own stored procedure implementation within the application source code because the underlying DMBS didn't support anything else; it's not ideal for a number of reasons but it does work, is an order of magnitude superior to ad-hoc SQL scattered throughout the app, still permits some of the benefits of genuine sprocs but also still provides the dev with proper control over what they're doing.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by billybob on Tuesday May 03, 2011 @10:29AM (#2510048)
I haven't used LINQ, but I do use Rails and its ORM. Using Rails' ORM to generate SQL is a case of optimizing for development time rather than execution time; assuming I would write faster SQL by hand, which is questionable, it would still be premature optimization and would be harder to maintain.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by pfedor on Tuesday May 03, 2011 @11:28AM (#2510304)
Actually, I do remember 10 years ago, that was when I got my first job. I remember that already then I was rather surprised to learn that what they said in the books about database applications was exactly backwards: the often repeated wisdom was that the database engines were fast and highly optimized, and you should do as much processing as possible on the database engine and as little as possible in your PHP script which was bound to be less efficient. The reality was that the database engine was always the bottleneck. If the PHP script was slow, you could replicate your Apache to as many machines as needed. If the MySQL was crapping out, you could buy a bigger machine or optimize your queries but generally that was a bigger pain.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by electrum on Tuesday May 03, 2011 @01:34PM (#2510885)
10 years ago ... MySQL

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jacques_chester on Tuesday May 03, 2011 @06:43PM (#2511953)
With one exception: joining over database links is terrible. I admit that it's a hard problem to solve, but still.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by silverbax88 on Tuesday May 03, 2011 @11:30AM (#2510320)
If your database engine is the bottleneck, you don't have an enterprise architecture.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by btilly on Tuesday May 03, 2011 @02:56PM (#2511207)
If your database engine is the bottleneck, you don't have an enterprise architecture.

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.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jacques_chester on Tuesday May 03, 2011 @06:40PM (#2511943)
I think the fundamental mismatch is not between OO and relational, or the application layer and the relational layer, but between reads and writes.

In the database world this conflict has been studied for decades under the headings of OLAP and OLTP. All you get taught in a university course or a beginner's book is OLTP-focused. Great if you're storing thousands of credit card transactions per second. Less useful if you need to read thousands of records per second.

Lots of NoSQL looks like it's actually dimensional modelling minus some of the really clever bits.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by chopsueyar on Tuesday May 03, 2011 @08:32PM (#2512304)
Well, with the ORMs the objects generate the relational stuff. I enjoy modeling my entities on paper as an ERD (from the entity relationship perspective) and then writing the object code.

However, I have found it is sometimes necessary to denormalize my schema and store entities based on how they are presented, not necessarily the idealistic OO ORM'ed way.

At the end of the day, the user doesn't care if your code is abstracted properly (who's definition?) or enough. It just needs to work speedily and correctly and be easily maintainable.

I think alot of people know SQL, but may not understand how to model entities correctly, and if they can't model the entities correctly, what ever they denormalize is still coming from a 'less-good' model.

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by jacques_chester on Tuesday May 03, 2011 @08:40PM (#2512327)
Personally, when it comes to denormalisation, my preference is that it be done in a semi-structured way such as dimensional modelling.

And that's exactly what I was talking about: a key purpose for DM is to make the database more accessible for fast bulk queries at the cost of duplicate data.

Whereas normalisation drives out duplication in order to maximise transactional performance and space efficiency.

In your case, you start with the OLTP/normalised model, then devolve to what is actually a kind of OLAP/denormalised model.

Write-oriented vs read-oriented.

Maybe the missing link for relational databases in a web world is actually some kind of real-time ETL?

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by simonw on Wednesday May 04, 2011 @03:06AM (#2513024)
What's your definition of an "enterprise architecture"?
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by pradocchia on Tuesday May 03, 2011 @01:43PM (#2510916)
This is simply not true. Stored procedures and dynamic SQL are completely orthogonal to the problems of N+1 select and index seek vs table scan.

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/)

Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by MichaelGG on Tuesday May 03, 2011 @10:29AM (#2510049)
They chose to write their query in C# instead of SQL. They could have kept LINQ-to-SQL and manually written the query (even made it a SP, for the slight gain that'd provide) and then used LINQ's mapping features to get objects out of it. (I believe the DataContext has a Translate feature that'll take any data reader and pop out objects.) I do this from time to time when the LINQ-to-SQL query has a bug or isn't doing exactly what I want, or when there's a bulk operation I can do much more efficiently. It's not exactly advanced LINQ-to-SQL...
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by brunomlopes on Tuesday May 03, 2011 @02:27PM (#2511077)
Actually, if you look at other posts from Sam mentioning dapper you'll find that they profiled the site and found some bottlenecks also on the translator from the datareader to objects on linq2sql. Since they're going to hand-write the sql then they're going to take advantage of that really fast microorm instead of sticking with l2q.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by drtse4 on Tuesday May 03, 2011 @11:58AM (#2510492)
Checking the SQL that your ORM engine produce if you deploy your app in an environment where performance matters has always been a good practice. It's true now as it was 6-7 year ago when modern ORM solution like hibernate (or similar things on .Net) started to appear.
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by HelloBeautiful on Tuesday May 03, 2011 @10:33AM (#2510064)
Remember 200 years ago when industrial pollution was a solved problem?
Re:Stack Overflow Makes Slow Pages 100x Faster By Simple SQL... by gjm11 on Tuesday May 03, 2011 @12:10PM (#2510548)
It wasn't. It's just that it consisted of wood and coal smoke and horseshit rather than CO2, weird organic chemicals, and so forth.