A few lessons learned from building a Rails backed API on Heroku
This year and last I learned a few lessons from building a Rails 4 backed API on Heroku.
Lesson 1 – TDD is for clean, but not necessarily performant code
I wrote the first version of the API using TDD, and less of an understanding of what makes performant Rails code. As I got more into performance monitoring, I learned the hard way that clean / working code is not the same as code that is performant.
Lesson 2 – Performance monitoring tools are helpful
Specifically, I used New Relic in production and development. It has a neat tool you can use in development mode to check how much time individual SQL queries are taking.
Lesson 3 – Don’t complicate your life
Lesson 4 – There are no unions in ActiveRecord
I wanted to use us an SQL UNION operation but there’s no friendly ActiveRecord method to do this. Your choices are to do use something like Arel or write some raw SQL (you might consider using the findbysql method).
Lesson 5 – Continuous integration is cool
We’ve been using a service called Codeship, which automatically pushes the latest commits to your main codebase up to your server. We setup staging and production branches and our latest commits to those branches are automatically tested and pushed to our servers by Codeship.
Lesson 6 – Slow tests really suck when you’re shipping multiple times a day
If you start to notice your tests getting slower and slower, it’s probably worthwhile figuring out how to get them moving faster. Early on, I had some VCR tests that slowly started getting slower.
Upon further inspection, I realized I was testing hundreds of similar things over and over again due to the way I had written the tests. So I did some ignoring and rewrote some tests to use mock objects (since we could be fairly well-assured the interfaces and data of those mock objects wouldn’t change)
Lesson 7 – TDD can really help you ship faster and leads to better legacy code
It’s a comforting feeling to know that you have 85-90% (or higher) test coverage so when you make a change, you’ll have a failing test notify you if something you thought would work will break the system.
Lesson 8 – Pay attention to the Heroku metrics dashboard
The Heroku metrics dashboard can tell you if you’re running out of memory or if you’re having a memory leak (you’ll notice your memory keeps going up without ever coming back down). There came a point we had to switch to a higher priced tier to accomodate the extra memory our Rails API began needing.