Slow query to count projects pending deletion

We observe a slow query on GitLab.com when counting projects pending deletion:

SELECT
    COUNT(*)
FROM (
    SELECT
        ? AS one
    FROM
        "projects"
    WHERE (EXISTS (
            SELECT
                ?
            FROM
                "project_authorizations"
            WHERE
                "project_authorizations"."user_id" = ?
                AND (project_authorizations.project_id = projects.id))
            OR projects.visibility_level IN (?, ?))
        AND "projects"."visibility_level" = ?
        AND "projects"."pending_delete" = ?
    LIMIT ?) subquery_for_count

It seems like this is run about once every minute and takes about 10s to complete. For details see https://gitlab.com/gitlab-com/gl-infra/infrastructure/snippets/1865195#replica-1022016103-7.

Assignee Loading
Time tracking Loading