Fixes the DB query cache out of memory issues

Also includes some clean up of the entity cache