# Improve performance of Topic load - ORDER BY RANDOM

**URL:** <https://meta.discourse.org/t/improve-performance-of-topic-load-order-by-random/25619>\
**Category:** Bug\
**Tags:** slow-sql\
**Created:** [February 24, 2015, 4:48pm UTC](https://meta.discourse.org/t/improve-performance-of-topic-load-order-by-random/25619 "2015-02-24T16:48:29Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![riking](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/riking/32/170938_2.png) [@riking](https://meta.discourse.org/u/riking)\
**Post date:** [February 24, 2015, 10:11pm UTC](https://meta.discourse.org/t/improve-performance-of-topic-load-order-by-random/25619/3 "2015-02-24T22:11:35Z")

</div>

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

  - 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:@all` instead 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”.

---

_[View the full topic](https://meta.discourse.org/t/improve-performance-of-topic-load-order-by-random/25619)._
