SELECT COUNT(*) FROM posts WHERE community_id = ? is taking over 450ms. Indexes are present on community_id.What is the recommended architecture to make count lookups sub-millisecond without killing database CPU?
SELECT COUNT(*) FROM posts WHERE community_id = ? is taking over 450ms. Indexes are present on community_id.
Here are the industry standard solutions:
1. Counter Caching (Denormalization): Add a
posts_countcolumn directly to the parentcommunitytable. Increment on INSERT, decrement on DELETE. Query time drops from 450ms to 0.5ms.2. Redis caching: Store counts in a Redis hash with atomic
HINCRBY/HDECRBY.3. Approximate counts for pagination: If exact count isn't critical (like Google search pagination), use
EXPLAIN SELECT ...to get an estimated row count instantly.posts_count = posts_count + 1in our feed service and it reduced DB server load by 70%.