Caching so the database can sleep
A small catalogue site I run had a database bill that made no sense: tiny data, little traffic, and compute that was awake most of every day.
How serverless Postgres bills
The database suspends after a few idle minutes and wakes on the next query. You pay for awake time. The catch is the minimum: one query keeps it up for the whole idle window afterwards. On my plan that window is five minutes.
What was keeping it awake
Every public page cached its data for an hour. Sensible, I thought. But crawlers visit many different pages, a few per hour, around the clock. Each visit to a page whose cache had expired ran one query, and one query bought five minutes of awake time. A dozen such visits spread across an hour kept the database up for most of it. At three in the morning. For bots.
The fix
The admin panel already invalidated the cache whenever content changed. So the hourly expiry was protecting against nothing. I raised it from an hour to a week.
Then the leaks:
- The search page queried the whole catalogue on every request. It now filters a cached copy, and search results are excluded from indexing.
- List pages cached per combination of filters, and URL parameters are unbounded. Normalising them (sorted, deduplicated, validated) stops crawlers minting new cache entries.
The general lesson
With scale-to-zero, the question is not "how many queries" but "how many separate moments does a query happen". One burst of fifty queries is cheap. Fifty queries five minutes apart is the most expensive pattern there is.
Invalidate on write, cache for a long time, and look at awake hours rather than query counts.