Make Database Performance Great Again

I built a Rails app that took 300 seconds to load. No, that’s not a misprint. I didn’t forget to include the ‘milli’ prefix, and I’m well aware an app that slow will never be more than a dumpster fire of sadness — no matter how interesting or visually appealing the data it renders is. So, how did I get there? And more important than that, how did I refactor my code to bring database performance back to a satisfactory state? Before we dig in, let’s take a step back. On the job, you’re likely to encounter database performance issues due to the average web app being so database reliant. When this happens, where do you start? Resist the urge to immediately start rooting out N+1 queries, and instead use a service that measures app performance one call at a time. The small time investment required up front will almost assuredly save you time and headaches in the long run versus the guess and check approach. Bullet, Skylight, and New Relic are all good options for Rails apps. I used New Relic and quickly confirmed the problem I suspected — an index page was calling nearly the entire database over 200 times when only a single query was necessary. So, we’ve found the bottleneck, now what? In my app, the ‘count_tweets’ method queries a database of 10,000 tweets, groups them by user location, and groups them once more according to a hashtag ID. Prior to the refactor you see in the screenshot, the return value from ‘count_tweets’ was called by four other methods in the class and the database was queried each time. A table in the index view called these four methods for each of the 50 states plus DC — 204 database queries in all! Gross. Let’s eliminate this absurd traffic jam. Wanting to...
Read Full Article
Upload Background Image
Drop File