Caching a home feed without caching prices: p95 from 18.4 s to 2.8 s

The home screen of Abuk, an ebook and audiobook service on iOS, Android and the web, took 18.4 seconds to load at the 95th percentile. One request in twenty waited that long or longer, and the slowest took 52 seconds. The screen is the first thing a reader sees after opening the app.

We moved the home feed to a shared Redis cache with one hard rule: prices never go into it. After the change, p95 dropped to 2.8 seconds, the average went from 3.8 s to 1.6 s, and the slowest request fell from 52 s to 5 s. Below is what was wrong with the old cache, why prices stay out of a shared cache, how we recommend setting one up in Rails, and a checklist you can run against your own app.

What the home feed looked like

Abuk has been with us since 2018. We took it over from a previous contractor in poor condition and act as tech lead for the web service, both mobile apps, billing in the App Store and Google Play, and the AWS infrastructure. The backend is Ruby on Rails with Redis, and the services run on Amazon ECS.

A home screen in a book service shows collections of books with covers, titles and prices. The mobile apps and the website load it every time someone opens the app, so it is the most requested screen and the one users judge the product by.

Users grew from about 50,000 to almost 600,000 over the years we have worked on the product. A response time that was tolerable at the start became the slowest part of the first screen.

What was wrong with the cache

The Rails cache lived inside each container and was wiped on every deploy. That one fact explains most of the slow requests.

When the cache sits inside a container, each container builds its own copy from scratch:

  • A request landing on container A cannot use what container B has already computed. More containers mean more cold caches.
  • Every deploy replaces the containers, and every cache starts empty. A team that deploys often never lets the cache warm up.
  • Under a cold cache the database does the full work for the request, and those are the requests that end up in p95 and in the maximum.

In Rails this setup is easy to end up with by accident. In the Rails versions we work with, if config.cache_store is never set, Rails falls back to a file store in tmp/cache when that directory exists, and otherwise to an in-memory store. Both live inside the process or the container. On a single server that is fine. In containers it means one private cache per container, gone on the next deploy.

Why prices stay out of the cache

Abuk sells subscriptions and single books through the App Store and Google Play. Our rule for the shared cache is simple: prices never go into it.

The general reason applies to any app that takes payments. A purchase passes through two prices: the one the user saw on screen, and the one the server uses when it verifies the purchase. If the screen shows a stale price from a cache and the server checks against the current one, the purchase can fail after the user has already paid in the store. A stale cover or rating costs nothing. A stale price costs a failed purchase.

So the feed splits into two kinds of data:

  • Fields that are the same for every user and change rarely: title, author, cover, rating, the book’s place in a collection. These can go into the cache.
  • Price, plan and anything tied to the user’s subscription. These are read fresh on every request and merged into the cached data before the response goes out.

A whole-response cache, such as Rails action caching or a page cache in front of an endpoint that shows prices, cannot leave one field out. If an endpoint shows prices, we cache its parts and keep the price outside.

How we recommend setting up a shared cache in Rails

These are the settings we check on any Rails app that runs in more than one container. The code is a simplified example, not a copy of a client project.

One shared store for all containers. redis_cache_store has been built into Rails since 5.2. Every container and every Puma worker reads and writes the same cache, and a deploy no longer empties it. Give the cache its own Redis database or namespace, apart from background job queues and sessions, so that clearing the cache never touches background jobs.

# config/environments/production.rb (simplified example)
config.cache_store = :redis_cache_store, {
  url: ENV.fetch("REDIS_CACHE_URL"),   # a different Redis DB than the job queues
  namespace: "app:cache",
  error_handler: ->(method:, returning:, exception:) {
    Rails.logger.warn("cache #{method} failed: #{exception.class}")
  }
}

Decide what happens when Redis is down. With an error_handler, Rails logs the problem and the request continues without the cache. The screen gets slower and still works. For a home screen, a slow answer is better than an error.

Key entries by data version. If a cached block is keyed by the record’s ID and its updated_at, an edit changes the key and the next request builds a fresh entry. Old entries expire on their own, and most manual invalidation goes away.

def book_fields(book)
  Rails.cache.fetch(["book-fields", book.id, book.updated_at.to_i]) do
    BookFieldsSerializer.new(book).as_json   # no price, no plan
  end
end

def feed_item(book, user)
  book_fields(book).merge(pricing_for(book, user))   # always fresh
end

Make the cache visible in production. A small health check or admin page that reports the cache store in use and does a test write and read tells you in seconds whether a container fell back to its own cache after a configuration change.

The result

We measured the home feed in production before and after the move to the shared Redis cache.

MetricBeforeAfter
Average response3.8 s1.6 s
p9518.4 s2.8 s
Slowest request52 s5 s

The p95 and the maximum moved more than the average. In our case the likely reason is cold caches: the average hides the requests that hit an empty cache on a fresh container, while p95 and the maximum show them. Once every container shares one warm cache, the long tail shrinks.

Because prices never enter the cache, there is no price invalidation logic that could go wrong.

If your product has a similar shape, a web backend serving mobile apps with a heavy first screen, this is the kind of work our web development team takes on. For audio, video and reading apps specifically, see media streaming app development. The full case, including billing, content protection and the move to AWS, is on the Abuk case page.

Checklist for your own Rails app

Run through these before you add more caching code. Most of them take minutes to check.

  1. Find out which cache store production uses. Open a Rails console on a production container and print Rails.cache.class. If you see FileStore or MemoryStore and you run more than one container or server, each one has its own cache.
  2. Deploy and watch the cache. If response times jump after every deploy and recover slowly, the cache lives inside the container.
  3. List what each cached block contains. Anything that depends on the user, the store, a currency or a promotion should not sit in a shared cache entry. Price is the usual offender.
  4. Check action and page caches on endpoints that show prices. They cache the whole response and cannot leave one field out.
  5. Put the cache in its own Redis database or namespace. Flushing the cache should not delete background jobs or sessions.
  6. Set an error handler. Decide in advance what happens when Redis is unreachable. Serving without cache is usually the safe choice.
  7. Key entries by data version. IDs plus updated_at let stale entries expire on their own and remove most manual invalidation.
  8. Measure p95 and maximum, not only the average. Cache problems live in the tail.
  9. Give yourself a production check. A small admin page or health endpoint that writes and reads a test key will save hours the next time someone changes the configuration.

FAQ

Why not cache the price with a short expiry?

A short expiry only narrows the window in which a reader sees a wrong price. It does not close it. In apps that sell through the App Store or Google Play, a mismatch between the price on screen and the price on the server can fail a purchase after payment. Reading the price fresh costs one lookup per book, and that is cheap next to a failed payment and a support case.

Is Redis required, or would Memcached work?

Rails supports both through the same Rails.cache interface. What matters is that the cache is shared across every container and survives deploys. If the app already runs Redis for background jobs, Redis is the natural choice because the team already operates it. In that case we recommend a separate Redis database or namespace for the cache, so it stays apart from the job queues.

What happens to the feed when Redis goes down?

With an error_handler configured, Rails logs the error and the request runs as if there were no cache. The feed becomes slower until Redis returns, and users still get a correct response. Without an error handler, a cache failure can turn into failed requests, so it is worth setting on day one.

How do we know the shared cache is working after a deploy?

Check from inside a running container that Rails.cache is a Redis store, then write and read a test key. Putting that check on an admin page or a health endpoint lets anyone on the team confirm it without console access. Watching p95 on the cached endpoint after each deploy gives a second signal: with a shared cache, it should not spike.

What would you like to do next?

Discuss a project

Tell us about the task. Within one working day we reply with questions or a first view on scope and cost.

Start a project

Ask a question

A short question about your app, website or idea. An engineer replies by email.

Get new articles

New articles and case studies by email, no more than once a month. Unsubscribe at any time.

Tell us about your project

Describe the task in a few lines. Within one working day we reply with questions or a first view on scope and cost.

Prefer email or a call?

welcome@revolsource.com
+38 097 662 23 20

Revol Software OÜ, Tallinn, Estonia. Our team is distributed around the world.

Join our team

Send your CV to career@revolsource.com