Production failures: the things that page you · Chapter 5 of 24 · Reliability · new chapter every Friday morning
By the end of this chapter: Find the query whose plan changed when the table grew.
The problem
You are a junior engineer on call for the first time, and your pager has just gone off at 3am. The alert is for a slow query on your database, but when you log in to investigate, everything looks normal. The query is still running, but it's not like it's bringing down the entire system. You start to dig in, running EXPLAIN statements and checking the query plan, but nothing seems out of the ordinary. It isn't until you start looking at the query logs from earlier in the day that you notice something strange - the query was running fine until around lunchtime, when the number of concurrent users spiked. Now, the query is taking seconds to complete, where it used to take milliseconds. You're not sure what's going on, but you know you need to fix it before the rest of the team wakes up and the system gets even more loaded.
As you start to investigate further, you realize that the table the query is running on has grown significantly over the past few weeks. You're not sure if this is related to the slow query, but it seems like a good place to start. You've heard of queries slowing down as tables grow, but you're not sure how to diagnose or fix the problem.
The cost of this problem is already starting to add up. The slow query is causing delays for users, and the longer it takes to fix, the more frustrated they'll become. You're also worried about the impact on the rest of the system - if this query is slowing down, what else might be affected?
Before you start
To follow along with this chapter, you'll need a PostgreSQL database with a table that has a significant amount of data in it. You can use a sample dataset like the Sakila database, which you can download from the PostgreSQL website. You'll also need to have pg_stat_statements installed and enabled, which will allow you to see detailed statistics about the queries running on your database. You can install it by running CREATE EXTENSION pg_stat_statements; in your database.
To verify that everything is set up correctly, run the following command: SELECT * FROM pg_stat_statements;. This should return a list of queries that have been run on your database, along with their execution times and other statistics.
Understanding query plans
To diagnose the slow query, you need to understand how the database is executing it. The EXPLAIN statement is your friend here - it will show you the query plan that the database is using to execute the query. Run the following command: EXPLAIN (ANALYZE) SELECT * FROM my_table WHERE my_column = 'my_value';. This will return a detailed breakdown of the query plan, including the estimated cost of each step and the actual time it took to execute.
Identifying the problem
As you look at the query plan, you notice that the database is using a sequential scan to retrieve the data from the table. This is slow because it has to read every row in the table, rather than using an index to quickly find the relevant data. You also notice that the estimated cost of the query has increased significantly since the table grew. This suggests that the database is having to do more work to execute the query, which is causing it to slow down.
Build it
To fix the slow query, you need to identify the query whose plan changed when the table grew. Here are the steps to follow:
- Run the following command to get a list of queries that have been run on your database, along with their execution times:
SELECT query, calls, total_time, rows, 100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;. This will show you the top 10 queries by execution time. - Look for queries that have a high execution time and a low hit percent. These are likely to be the queries that are causing the problem.
- Run
EXPLAIN (ANALYZE)on each of these queries to see their query plans. Look for queries that are using sequential scans or other slow operations. - Check the query logs to see when the query plan changed. You can do this by running
SELECT * FROM pg_stat_statements WHERE query = 'my_query';and looking at thequerycolumn. - Once you've identified the query whose plan changed, you can start to optimize it. This might involve adding an index to the table, or rewriting the query to use a more efficient algorithm.
When this breaks
There are several ways that this solution can break:
- The query plan can change again, causing the query to slow down. This can happen if the table grows or if the database is restarted.
- The index can become corrupted, causing the query to slow down. This can happen if there is a hardware failure or if the database is not properly maintained.
- The query can start to use a different algorithm, causing it to slow down. This can happen if the database is updated or if the query is modified.
To fix these problems, you can use the same techniques as before - run EXPLAIN (ANALYZE) on the query, check the query logs, and optimize the query as needed.
What it costs
The solution to this problem has several costs:
- Adding an index to the table can slow down write operations, since the index has to be updated every time data is written to the table.
- Rewriting the query to use a more efficient algorithm can be time-consuming and may require significant changes to the application code.
- Monitoring the query plan and optimizing the query as needed can require significant ongoing effort and resources.
However, the benefits of fixing the slow query outweigh the costs. A fast and efficient query can improve the user experience and reduce the load on the database, making it more scalable and reliable.
In the interview
In an interview, you might be asked a question like: "How would you diagnose and fix a slow query that only appears at scale?" A weak answer might be: "I would just run EXPLAIN on the query and see what it says." A stronger answer would be: "I would start by running EXPLAIN (ANALYZE) on the query to see the query plan, and then check the query logs to see when the query plan changed. I would also look at the table statistics to see if the table has grown significantly, and consider adding an index or rewriting the query to use a more efficient algorithm. I would also monitor the query plan and optimize the query as needed to ensure that it remains fast and efficient."
As a junior engineer, you might be expected to explain the basic steps of diagnosing and fixing a slow query. As a senior engineer, you might be expected to explain the trade-offs and costs of different solutions, and to describe how you would monitor and optimize the query in a production environment. As a staff engineer, you might be expected to describe how you would design a database and application to avoid slow queries in the first place, and how you would lead a team to diagnose and fix slow queries.
Your tasks
- Create a sample database with a table that has a significant amount of data in it. Run
EXPLAIN (ANALYZE)on a query that retrieves data from the table, and look at the query plan. What operations is the database using to execute the query? - Add an index to the table and run
EXPLAIN (ANALYZE)on the query again. How has the query plan changed? - Write a query that uses a sequential scan to retrieve data from the table. Run
EXPLAIN (ANALYZE)on the query and look at the query plan. What operations is the database using to execute the query? - Optimize the query to use an index instead of a sequential scan. How has the query plan changed?
- Monitor the query plan and optimize the query as needed to ensure that it remains fast and efficient. What tools and techniques would you use to do this?
Your tasks this week
Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.
Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.
Production failures: the things that page you
Chapter 5 of 24. New chapter every Friday morning.
Next: Clock skew, timezones and the off-by-one-hour outage.
· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe
Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.
Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.
Top comments (0)