Rails Performance: Lessons from Production — #4
The first three posts were about making queries cheaper — fewer N+1s, indexes, not dragging data back into Ruby. This one flips the angle: the fastest query is the one you never run. Compute a result once, store it, and hand it to everyone after. Same example throughout (a shipments table), walking through the four layers of Rails caching: compute, invalidate, render, transfer.
The homepage shows a "courier shipment ranking." It's heavy — scanning a few million shipments and a GROUP BY takes 800ms.
The thing is: that number looks the same to every user, and it doesn't need to be real-time (a few minutes stale is fine). But our code makes every visitor recompute it from scratch — 800ms each. Under traffic, the DB gets ground down by the same calculation over and over.
That's the sweet spot for caching — expensive (worth saving) and hit repeatedly (the same result is reused). Let's start from the most basic tool.






