DEV Community

Gerardo Andrés Ruiz Castillo
Gerardo Andrés Ruiz Castillo

Posted on • Originally published at geanruca.gitvlg.com

Tenant Landing Page Optimization: Caching for Performance

The devlog-ist/landing project delivers landing pages for tenants. A recent optimization focused on reducing database load by implementing a caching strategy for tenant-specific landing page data. This change significantly improves performance by minimizing redundant database queries.

The Problem

Previously, each request to a tenant's landing page triggered multiple database queries to fetch stats, badges, recommendations, and post languages. In particular, loading all posts to generate statistics resulted in a substantial performance bottleneck. This "load ALL posts for stats" query ran on every landing page hit, even if the data hadn't changed. This approach was clearly unsustainable as the number of tenants and posts grew.

The Solution: Caching Tenant Landing Page Data

To address this, a caching mechanism was introduced. Now, tenant-specific landing page data is cached with a Time-To-Live (TTL) of one hour. This means that the first request for a tenant's landing page will still incur the database queries, but subsequent requests within the hour will be served from the cache. The cache is automatically invalidated whenever a post is saved or deleted, ensuring data consistency.

Here's a simplified example of how the caching might be implemented in PHP:

<?php

use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter();
$cacheKey = 'tenant_' . $tenantId . '_landing_page_data';

$landingPageData = $cache->get($cacheKey, function () use ($tenantId) {
    // Fetch data from the database
    $stats = getTenantStatsFromDatabase($tenantId);
    $badges = getTenantBadgesFromDatabase($tenantId);
    $recommendations = getTenantRecommendationsFromDatabase($tenantId);
    $postLanguages = getTenantPostLanguagesFromDatabase($tenantId);

    $data = [
        'stats' => $stats,
        'badges' => $badges,
        'recommendations' => $recommendations,
        'postLanguages' => $postLanguages,
    ];

    return $data;
});

// Use $landingPageData to render the landing page
Enter fullscreen mode Exit fullscreen mode

This code snippet demonstrates how the Symfony cache component can be used to store and retrieve tenant landing page data. The get method either returns the cached data or executes the provided closure to fetch fresh data from the database if the cache is empty or expired.

The Impact

This caching strategy significantly reduces the number of database queries per request, particularly on cache warm. More importantly, it eliminates the expensive "load ALL posts for stats" query that previously ran on every landing page hit. This leads to improved landing page load times and reduced database load, resulting in a better user experience and improved system scalability.

Top comments (0)