|
Databases

Why your database gets slow and how to fix it

A page timing out at 2am is rarely the host's fault. One query was scanning 1.2 million rows for 20 results. Here is the order to check things before you buy RAM.

Why your database gets slow and how to fix it

At 2:14am my phone rang. A client's order page had been timing out for forty minutes, and his WhatsApp was filling with angry customers. He was sure the host had a problem. He wanted to move to a bigger server and he wanted to do it that night.

I opened the slow query log. One query was taking 11 seconds. It was a search on the orders table, filtering by phone number, on 1.2 million rows. There was no index on that column. The database was reading every single row, every time, for every search.

No server on earth fixes that cheaply. You fix it with one line.

It is almost never the server

The instinct when things get slow is to buy more RAM. Sometimes that helps, for a week. Then the data grows and you are back at 2am with a bigger bill.

Nine out of ten slow database problems I have seen are one of these: a missing index, a query that fetches more than it needs, a loop in the code making one query per row, or a table that has grown past what a single query should scan. That is a short list. Learn to check it in order and you will stop guessing.

Start with the query, not the database

Find the slow query first. In MySQL, turn on the slow query log and set the threshold to one second. In Postgres, use pg_stat_statements and sort by total time. Most hosts also show you a list of recent slow queries in cPanel or their dashboard.

When you find it, run EXPLAIN in front of it. You are looking for the word "scan" and a big row count. If the plan says it examined 1,200,000 rows to return 20, the database is doing manual labour. That is your problem.

Also look at what the query selects. SELECT * on a table with a long text column pulls megabytes you never display. Name the columns you need. It is the cheapest speed fix in existence.

The index you forgot

An index is a sorted lookup that lets the database jump to the matching rows instead of reading all of them. If you filter, sort or join on a column, that column probably wants an index.

Create one and the same query goes from 11 seconds to 30 milliseconds. Not because the server got faster. Because it stopped doing unnecessary work.

Two things to know before you add ten indexes. First, every index slows down writes, because each insert has to update the index too. Second, an index on a column with three possible values, like status, rarely helps on its own, because the database still has to look at a third of the table. Index what you filter by, not what looks important.

The N+1 hiding in your code

This one does not show up as a single slow query, which is why people miss it. Your code fetches 100 orders in one query. Then, for each order, it fetches the customer in another query. That is 101 queries, each fast, and the page takes six seconds.

The fix is to fetch the customers once with a join, or with a single query using WHERE id IN (...). If you use an ORM, look for the setting called eager loading and turn it on for the relationships the page uses.

I lost two days to this in 2020. The query log looked clean because every query was under 20ms. The page was slow because there were 400 of them.

When the table is simply too big

If one table holds three years of orders and you only ever read the last 90 days, the old rows are weight. Archive them into a separate table or a reporting database. Keep the live table small enough that queries stay quick.

The same applies to logs. An activity table that grows by 50,000 rows a day will be a problem in a year. Decide early where old rows go. Nobody wants to clean that up during a crisis.

Before you buy a bigger server

Work down these steps before you spend money on hardware.

  1. Find the slow query. Do not guess.
  2. Read the query plan and see how many rows it examined.
  3. Select fewer columns and fewer rows.
  4. Add the index the filter needs, then recheck the plan.
  5. Look for loops in the code making repeated queries.
  6. Only then think about caching or a bigger server.

Each step is cheaper than the one after it. Skipping to the last step is how people spend money and stay slow.

Open your slow query log today and read the top five entries. Pick one, run EXPLAIN on it, and check whether the row count is close to the table size. If it is, you have found a missing index. Add it, measure again, and write down the before and after numbers.

If you are not sure how indexing works, start with what database indexing is. And if your app works locally but drags on the server, read why code works locally but not on the server. The software development course covers query plans and indexing in more depth.

Dave Partner

Dave teaches digital skills at Braintem and has helped thousands of Nigerians move from watching tutorials to charging for real work. He writes about the parts nobody puts in the course trailer.