Jobs::SyncTopicUserBookmarked in a loop using 100% CPU

I reduced SIDEKIQ_WORKERS to 2 and, not too long after, the queue (with many pending things) cleared up and there’s no more Jobs::SyncTopicUserBookmarked running… :thinking:

Before trying that, I caught the query below running multiple times at once (using same topic id):

SELECT bookmarks.user_id, COUNT(*)
INTO TEMP TABLE tmp_sync_topic_user_bookmarks
FROM bookmarks
LEFT JOIN posts ON posts.id = bookmarks.bookmarkable_id AND bookmarks.bookmarkable_type = 'Post'
LEFT JOIN topics ON (topics.id = bookmarks.bookmarkable_id AND bookmarks.bookmarkable_type = 'Topic') OR
 (topics.id = posts.topic_id)
WHERE (topics.id = 51303 OR posts.topic_id = 51303)
AND posts.deleted_at IS NULL AND topics.deleted_at IS NULL
GROUP BY bookmarks.user_id;

UPDATE topic_users
SET bookmarked = true
FROM tmp_sync_topic_user_bookmarks
WHERE topic_users.user_id = tmp_sync_topic_user_bookmarks.user_id AND
  topic_users.topic_id = 51303 AND
  tmp_sync_topic_user_bookmarks.count > 0;

UPDATE topic_users
SET bookmarked = false
FROM tmp_sync_topic_user_bookmarks
WHERE topic_users.topic_id = 51303 AND
  topic_users.bookmarked = true AND
  topic_users.user_id NOT IN (
    SELECT tmp_sync_topic_user_bookmarks.user_id
    FROM tmp_sync_topic_user_bookmarks
  );

DROP TABLE tmp_sync_topic_user_bookmarks;

I’m not clear how PostgreSQL runs multiple statements in a single query, but if it is executed multiple times concurrently, could it cause a loop somehow?