Bulk update user todos count cache
🍳  What does this MR do?
Avoids N+1 queries when updating todo count cache for multiple users. TodoService updates the cache count for example when users get mentioned in a Note.
- Issue: #325690 (closed)
- Related to https://gitlab.com/gitlab-org/ecosystem-team/team-tasks/-/issues/67
💾  Database
Previous query plans
Bulk todos count query
Updating the count will produce the following query when executed for 100 users:
SELECT
    COUNT(*) AS count_all,
    "todos"."user_id" AS todos_user_id,
    "todos"."state" AS todos_state
FROM
    "todos"
WHERE
    "todos"."state" IN ('done', 'pending')
    AND "todos"."user_id" IN (
        SELECT
            "users"."id"
        FROM
            "users"
        LIMIT 100)
GROUP BY
    "todos"."user_id",
    "todos"."state"This seems to be quite slow:
- cold cache: 20.992 s 🔗 query plan
- warm cache: 126.328 ms 🔗 query plan
Update: I've limited the amount of users to 10:
- cold cache: 836.757 ms 🔗 query plan
- warm cache: 17.800 ms 🔗 query plan
Update 2: I've added an index ON todos USING btree (user_id) WHERE ((state)::text = ANY ('{done,pending}'::text[])) to improve query performance.
- cold cache: 342.297 ms 🔗 query plan
- warm cache: 22.215 ms 🔗 query plan
Update 3 by @toupeira: I've changed the index to be on (user_id, state) instead, and changed the query to stop filtering on state (since we want all states anyway):
- cold cache: 103.595 ms 🔗 query plan
- warm cache: 5.927 ms 🔗 query plan
Update 4 by @toupeira: Reverted the index changes, and switched to a UNION query using the existing partial indexes:
- cold cache: 376.992 ms 🔗 query plan
- warm cache: 9.241 ms 🔗 query plan
🗒  Does this MR meet the acceptance criteria?
Conformity
- 
📋 Does this MR need a changelog?- 
I have included a changelog entry. 
- 
I have not included a changelog entry because _____. 
 
- 
- [-] Documentation (if required)
- 
Code review guidelines 
- 
Merge request performance guidelines 
- 
Style guides 
- [-] Database guides
- [-] Separation of EE specific content
Availability and Testing
- 
Review and add/update tests for this feature/bug. Consider all test levels. See the Test Planning Process. 
- [-] Tested in all supported browsers
- [-] Informed Infrastructure department of a default or new setting change, if applicable per definition of done
Edited  by Toon Claes