The proposed solution is something like this:
- have a Redis key named after the category, for example
suggested:support/wordpress(category.url) - if we have N suggested topic slots to fill, try to RPOP n times
- if a RPOP returns nil (the list ran out), refill it:
-
Query for a thousand topics
SELECT id FROM TOPICS WHERE category_id = ? ORDER BY RANDOM() LIMIT 1000 -
LPUSH them all into the list 100 at a time (
LPUSH suggested:support/wordpress 123 54 87 35 78 15 64 79 ...) -
Expire the key in 2 days or so
-
- Continue RPOPing until either we have N unique topic ids or it returns nil again.
- If RPOP returned nil again, and the category was specified, repeat the fill attempt, but use
suggested:@allinstead of a category-specific one - Pass our topic ID list to Topic.find and then on to the serializer
This is also known as a “tetris random”.