Video in progress
When read load grows, do you add a read replica or put in a cache? How do you choose?
If the queries are varied and the data has to be fresh, a read replica; if the same things are read over and over and a bit of staleness is fine, a cache. You often need both, but each one has a different cost.
📖 Answer
First, look at what the load looks like. Take the top 20 queries from pg_stat_statements. If 80% of the load lands on 10-20 identical keys (a product card, settings), a cache is very effective, with a hit rate of 95%+.
If the queries have a long tail (each user's own report, combinations of filters), the cache hit rate will be low and invalidation will hurt. A replica is better there: the SQL doesn't change, you just route readOnly transactions to another DataSource.
| Read replica | Cache | |
|---|---|---|
| Staleness | replication lag (usually ms, seconds under load) | depends on TTL or invalidation |
| Code changes | few | many: keys, invalidation |
| Complex queries | no problem | only ready-made results |
| Cost | a full copy of the DB | cheap memory |
The replica's trap is read-your-writes. The user saves their profile, the page refreshes, the request goes to the replica and shows the old name. The fix: after a write, route that user's reads to the primary for a few seconds, or check by LSN/position that the replica has caught up.
The cache's trap is invalidation and stampede, which is a separate conversation.
My usual order: first fix indexes and queries, then cache the hot keys, then a replica for reports and search.
Sign up to mark studied questions and save your progress.