Skip to content

Commit

Permalink
Cache the result of DB queries in leaderboards
Browse files Browse the repository at this point in the history
Temporary fix until I figure out how to optimize leaderboards
  • Loading branch information
Simyon264 committed May 6, 2024
1 parent 64c47e6 commit d8ccfce
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions Server/Api/DataController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,12 +332,18 @@ public async Task<LeaderboardData> GetLeaderboard(

var stopwatch = new Stopwatch();
stopwatch.Start();

var rangeTimespan = rangeOption.GetTimeSpan();
var dataReplays = await _context.Replays
.Where(r => r.Date > DateTime.UtcNow - rangeTimespan)
.Include(r => r.RoundEndPlayers)
.ToListAsync();

var replaysCacheKey = "replays-" + rangeOption;
if (!_cache.TryGetValue(replaysCacheKey, out List<Replay> dataReplays))
{
dataReplays = await _context.Replays
.Where(r => r.Date > DateTime.UtcNow - rangeTimespan)
.Include(r => r.RoundEndPlayers)
.ToListAsync();
_cache.Set(replaysCacheKey, dataReplays, new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromHours(1)));
}

stopwatch.Stop();
Log.Information("Fetching replays took {Time}ms", stopwatch.ElapsedMilliseconds);
Expand Down

0 comments on commit d8ccfce

Please sign in to comment.