How it works
A cache adds stale data, invalidation, and cold starts; in a multi-tenant product, a key that omits the customer ID can leak one customer’s data to another. So try cheaper fixes first: fix the query (removing an N+1 pattern, say), add an index, then precompute heavy totals in a summary table or materialized view (a stored query result). In an illustrative case, a page that scans a whole table and takes 1.8 seconds might take 40 ms with an index on (customer_id, created_at).
Add a cache once measurements show that the same expensive result is read repeatedly, tuning was not enough, slightly old data is acceptable, and those reads matter to total database time. A 95% hit rate on a query that accounts for 3% of database time saves under 3%.
For slow work such as emails or PDFs, start with a job table in the same database. Insert the job in the same transaction as the business change, so neither can exist without the other. Workers claim rows with Postgres FOR UPDATE SKIP LOCKED, so several workers can take different rows without blocking. For example, 600 jobs a minute is 10 per second; at about 2 queries per job (claim and finish), that is 20 queries per second.
Move to a broker such as RabbitMQ or Kafka when job queries rank among your costliest, row churn keeps Postgres vacuum (its cleanup of dead rows) busy, or several independent consumers need the same events. Brokers do not give exactly-once processing, so make jobs safe to retry either way.
The invoice list for your largest customer takes 4 seconds. A teammate’s pull request adds Redis with a 5-minute expiry. Finance users mark an invoice paid and reload this page immediately. What do you do with the pull request?
Hold it. Run EXPLAIN, and try an index such as (customer_id, issued_at) with pagination. A 5-minute cache would show paid invoices as unpaid for up to 5 minutes on a page people check right after writing, unless every write path invalidates it, and its key must include the customer ID. Reconsider for something expensive that repeats and can be a little old, such as a monthly revenue chart, and only if a summary table did not solve it.
Keep in mind
- Try the query, an index, and a summary table before a cache.
- A cache earns its place when repeated, expensive, staleness-tolerant reads matter to total load.
- A database job table is a real option until job traffic measurably competes with users.