Fix memory issues

My focus here was to reduce the number of queries on the most accessed pages, and also to move the calculations of statistics into a single query, which now runs in less than 10ms.