In this episode, we focus on improving our blog's performance by adding database indexes, specifically to help with showing posts from a particular user. We kick things off by bumping up our test data so we can really see the impact of our changes—each of our five users now has 2,000 posts!
We then walk through adding a feature that lets us filter posts by a user's ID using a query string parameter (like ?user_id=1
). We discuss different approaches to filtering, including using query builder methods and thinking about how they affect query speed and database calls.
After we've implemented filtering, we analyze the speed of our queries. Initially, things are a bit slow because the table doesn't have an index on the user_id
column. So, we head straight into adding an index manually in the database, experiment with it, and watch our query times drop!
We also talk about best practices, highlighting that you don't want to add too many indexes (as that can actually hurt performance), and demonstrate how to add an index through framework migrations, both when creating a new table and by adding an index to an existing table.
By the end, you'll see just how much indexes can help with speed, especially as your data grows. We wrap up by running a few benchmarks, removing/re-adding indexes, and watching those query times go up and down. It's a super practical walkthrough if you're curious how indexes affect real application performance!