The Three-Second Homepage (and the Cache That Fixed It)

I recently gave the Herbistry homepage the things you would expect from a useful front door: current articles, featured herbs, recently added products, and a few database statistics. It looked good. It also took about three seconds to load.

The tempting explanation was that the homepage had become “heavy.” That was only half true. The HTML response was about 13 KB, and the page displayed only a handful of records. The real problem was that every visitor caused the application to open a PostgreSQL connection and run six queries before rendering the page:

  1. Count products.
  2. Count herb profiles.
  3. Count published articles.
  4. Fetch the newest articles.
  5. Fetch featured herbs and their product counts.
  6. Fetch recently added products, their images, and their botanical ingredients.

The application and database are on different machines connected through Tailscale. That setup is convenient, but it makes a sequence of database round trips particularly visible to the person waiting for the page. None of the underlying information changes from one second to the next, yet two visitors arriving five seconds apart caused exa ctly the same work.

That is a caching problem, not a reason to buy a larger database server.

Measure first

I measured the original route with six sequential HTTP requests to the application through its Tailscale address. These were real requests against the real PostgreSQL database, not calls to a mocked test fixture. Each response returned HTTP 200 and the same 13,260-byte page.

Uncached requestTotal response time
13,192.1 ms
23,046.5 ms
33,048.0 ms
42,924.3 ms
52,886.5 ms
62,886.9 ms

The mean was 2,997.4 ms, the median was 2,985.4 ms, and the fastest request was 2,886.5 ms. This was not a synthetic load test. It was a small, sequential benchmark intended to answer a simple question: how long does one homepage request take when the application does all of its database wo rk?

The answer was consistently “about three seconds.”

What I chose to cache

There are two obvious places to put a cache: around the individual sections or around the complete homepage dataset.

Separate caches would allow the article list, product list, herb list, and counters to expire independently. That flexibility would be useful if each section had a different freshness requirement or an expensive invalidation strategy. Here, they do not. The editorial pipeline and ingestion jobs run infrequently, and a homepage that is a few minutes behind is perfectly acceptable.

I therefore cached one homepage context object containing all four collections: statistics, articles, herbs, and products. The default time to live is 300 seconds, configurable with HOMEPAGE_CACHE_SECONDS. Setting it to zero disables caching.

I deliberately did not cache the final HTML. Herbistry has user-specific navigation: administrators see additional links, and signed-in users see their account menu. Reusing rendered HTML across requests would risk showing one visitor's navigation to another. Caching only the database context avoids that problem. Jinja still renders the page separately for every request, using the current visitor's authentication state.

The implementation

The original database code moved into _load_homepage_context(). It returns a plain dictionary that the template can consume. The route asks _get_homepage_context() for that dictionary and adds an X-Homepage-Cache response header so a request can be identified as a MISS or a HIT without guessing from its timing.

The cache itself is deliberately small: one object, one monotonic expiry timestamp, and one asynchronous lock.

HOMEPAGE_CACHE_SECONDS = int(os.getenv("HOMEPAGE_CACHE_SECONDS", "300"))
_homepage_cache = None
_homepage_cache_expires = 0.0
_homepage_cache_lock = asyncio.Lock()


async def _get_homepage_context():
    """Return a shared snapshot; only one request rebuilds an expired cache."""
    global _homepage_cache, _homepage_cache_expires

    def fresh_snapshot():
        if HOMEPAGE_CACHE_SECONDS > 0 and _homepage_cache is not None:
            if time.monotonic() < _homepage_cache_expires:
                return _homepage_cache
        return None

    cached = fresh_snapshot()
    if cached is not None:
        return cached, "HIT"

    async with _homepage_cache_lock:
        # Another request may have populated the cache while this one waited.
        cached = fresh_snapshot()
        if cached is not None:
            return cached, "HIT"
        context = await asyncio.to_thread(_load_homepage_context)
        if HOMEPAGE_CACHE_SECONDS > 0:
            _homepage_cache = context
            _homepage_cache_expires = time.monotonic() + HOMEPAGE_CACHE_SECONDS
        return context, "MISS"

There are a few details here that matter more than the small amount of code might suggest.

The expiry uses a monotonic clock

time.monotonic() measures elapsed time without being affected by a system clock correction. A cache expiry should not move because NTP adjusted the machine's wall clock.

The lock prevents a cache-expiry stampede

Without a lock, twenty concurrent requests could all discover that the cache had expired and all run the same six queries. A lock by itself is not quite enough, though. After waiting for the lock, each request checks the cache again. The first request rebuilds it; the remaining nineteen see the new snapshot and return without touching the homepage queries.

This is often called a double-checked cache fill. It turns a potential database spike into one rebuild per application process.

Database work runs outside the event loop

The project uses synchronous psycopg2 code inside a FastAPI application. asyncio.to_thread() moves the snapshot rebuild to a worker thread instead of blocking the asynchronous event loop while PostgreSQL responds. It does not make the SQL faster. It keeps other requests responsive while the cold request does its work.

The route still renders normally

A cache hit skips the homepage database connection and its six queries. It does not skip authentication, template rendering, or HTTP transfer. That is why the improvement is large without pretending the rest of the request path has disappeared.

After caching: cold and warm requests

I restarted the application to guarantee an empty cache, then made one cold request followed by six warm requests through the same Tailscale address.

CaseRequestCache headerTotal response time
Cold cache1MISS2,931.3 ms
Warm cache2HIT4.1 ms
Warm cache3HIT1.6 ms
Warm cache4HIT1.4 ms
Warm cache5HIT1.2 ms
Warm cache6HIT1.4 ms
Warm cache7HIT1.7 ms

The cold request behaved like the old implementation, as expected: it took 2,931.3 ms and populated the cache. The six warm requests had a mean of 1.9 ms, a median of 1.5 ms, and a maximum of 4.1 ms.

For this small benchmark, the normal warm path went from roughly three seconds to roughly two milliseconds. The important point is not a precise speedup multiplier. The important point is that warm requests no longer wait for six queries to cross the network and execute.

The database-load difference is easier to reason about than the latency multiplier. Suppose 1,000 homepage requests arrive within one five-minute cache window on a single application worker:

  • Before: 1,000 homepage database connections and 6,000 queries.
  • After: one homepage database connection and six queries, assuming the first request succeeds and the cache does not expire mid-window.

That is arithmetic based on the request path, not a simulated 1,000-user load test.

What this cache does not solve

This is an in-process cache. If production runs four application workers, each worker has its own snapshot and can perform its own cold rebuild. That is still a large reduction in database traffic, and it avoids introducing Redis as another operational dependency. If measurements later show that independent worker caches are a problem, a shared cache can replace the storage without changing the homepage queries.

Content can also be up to five minutes old. That is an explicit trade-off, not an accident. Immediate invalidation after article publication would be a reasonable next improvement if editorial changes need to appear instantly.

Finally, this benchmark does not prove how the site behaves under a large concurrent load. It measures the uncached path, one cache fill, and the warm path. A separate load test would be needed to establish throughput, queueing behavior, and tail latency under pressure.

Why five minutes

A seconds-long TTL would still help during a sudden burst, but it would continue producing database work throughout ordinary traffic. A five-minute TTL matches the actual update frequency of this homepage much better. It also gives a simple operational guarantee: no single application worker needs to rebuild the homepage snapshot more than once per five-minute window while requests continue to arrive.

The cache is not a substitute for sound SQL or useful indexes. The product query still deserves attention, and the homepage still needs its recently proposed diversity filter. But repeatedly running the same queries for data that has not changed was pure waste. Removing that work was the most direct fix—and the measurements show just how much of the response time it represented.

Verification

The homepage cache has an automated test covering a cold MISS, a subsequent HIT, and identical returned content. The full project suite passes: 73 tests. git diff --check also passes.