Caching from Redis using ASP.NET Core Web API

I am using SQL Server for my database. I want to cache the result from API endpoints because the app is taking too much time initially to load as we have images/audios as files. I have implemented redis in order to cache the result and improve upon initial load time. It is running locally fine, but when I deploy this on the server, it did not show any improvement – rather it delays.

This is my controller endpoint:

[ResponseCache(CacheProfileName = "Default604800")]
public class BookController : BaseApiController
{
    private readonly ILogger<BookController> _logger;
    private readonly IDistributedCache _cache;
    public readonly IConnectionMultiplexer _redis;

    public BookController(IDistributedCache cache, IConnectionMultiplexer redis, ILogger<BookController> logger)
    {
        _cache = cache;
        _redis = redis;
        _logger = logger;
    }

    [AllowAnonymous]
    [HttpGet("getBooks")]
    [Produces("application/json")]
    //[OutputCache(Duration = 604800)]
    public async Task<IActionResult> GetBooks([FromQuery] BookParams param)
    {
        _logger.LogInformation("Alhamdulillah. Starting getBooks endpoint....");
        Stopwatch stopwatch = Stopwatch.StartNew();

        try
        {
            var cacheKey = $"Books_{param.Status}_{param.PageSize}_{param.OrderBy}_{param.OrderAs}";
            var cachedData = await GetBookFromRedis(cacheKey);
            if (cachedData != null)
            {
                var books = JsonConvert.DeserializeObject<List<BookDto>>(cachedData);
                return Ok(books);
            }

            var result = await mdtr.Send(new List.Query { Params = param });

            if (result != null && result.Value != null)
            {
                var pagedList = (PagedList<BookDto>)result.Value;

                var items = pagedList.ToList();

                var serializedBooks = JsonConvert.SerializeObject(items);

                await StoreBookInRedis(cacheKey, serializedBooks);

                return Ok(items);
            }
            else
            {
                return BadRequest("Failed to retrieve books.");
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex.Message}");
        }
        finally
        {
            stopwatch.Stop();
            _logger.LogInformation("getBooks endpoints completed in ${Elapsedmilliseconds} ms", stopwatch.ElapsedMilliseconds);
        }
    }

    private async Task<string> GetBookFromRedis(string cachekey)
    {
        try
        {
            var db = _redis.GetDatabase();
            var cacheData = await db.StringGetAsync(cachekey);

            return cacheData;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error fetching data from redis, {ex.Message}");
            return null;
        }
    }

    private async Task StoreBookInRedis(string cacheKey, string serializedBook)
    {
        try
        {
            var db = _redis.GetDatabase();
            await db.StringSetAsync(cacheKey, serializedBook, TimeSpan.FromSeconds(604800));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error saving on redis, {ex.Message}");
        }
    }
}

Redis connection is configured in appSettings.json:

"ConnectionStrings": {
    "MyRedisConStr": "localhost:6379,abortConnect=false",
    ....
}

And I added another configuration and dependency inside program.cs like this:

builder.Services.AddStackExchangeRedisCache(options =>
 {
     options.Configuration = builder.Configuration.GetConnectionString("MyRedisConStr");
     options.InstanceName = "SampleInstance";
 });

builder.Services.AddSingleton<IConnectionMultiplexer>(x =>
{
    var connection = ConnectionMultiplexer.Connect("localhost");
    connection.ConnectionFailed += (sender, e) =>
    {
        Console.WriteLine("Redis connection failed.");
    };
    return connection;
});

I have configured serilog to diagnose the performance bottleneck. I am using SQL Server as database.

Any insight/advice for diagnosing issue in production as to why redis is not performing in production while in localhost it is working fine is much appreciated.

My docker-compose.yaml in production is

  redis:
    image: redis
    container_name: my-redis
    volumes:
      - ./redis-data:/data
    ports:
      - "6379:6379"
    environment:
      - REDIS_CONNECTION_STRING=Redis
      - REDIS_MAXMEMORY=5gb
    user: root
    restart: unless-stopped
    networks:
      - my-nw

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật