DEV Community

Cover image for The most performed RANDOM querying on Rails!
Ivan Marynych
Ivan Marynych

Posted on • Edited on

The most performed RANDOM querying on Rails!

🌟 Prepare to have your mind blown by the Unbelievable Performance Gem! 🌟

Are you tired of slow random record retrieval in your Rails applications? Say goodbye to sluggish queries and hello to lightning-fast performance! Our gem is here to revolutionize the way you fetch random records, delivering results that will leave you speechless.

πŸ”₯ Experience the future of speed and efficiency as our gem seamlessly integrates into your codebase. With near-instantaneous responses, you can elevate your user experience to new heights.

πŸ’ͺ Join the ranks of developers who are already witnessing jaw-dropping results. Don't miss out on this game-changing gem that's setting new performance standards in the Rails community.

Ready to ignite your Rails application? Visit our repo to learn more about the Unbelievable Performance Gem and be part of the performance revolution today! πŸš€πŸ’Ž

GitHub logo the-rubies-way / random-rails

The most performed gem to get random record you ever seen! Available for Ruby on Rails with PostgreSQL right now!

lint test Gem Version

Image Oct 9, 2025, 04_30_33

RandomRails

πŸš€ The most performant way to get random records from ActiveRecord. Supports PostgreSQL, MySQL, and SQLite with intelligent strategy selection to replace slow ORDER BY RANDOM() queries.

Why RandomRails?

Traditional ORDER BY RANDOM() queries become extremely slow on large tables because they require sorting the entire dataset. RandomRails solves this by using:

  • TABLESAMPLE BERNOULLI for PostgreSQL (ultra-fast on large tables)
  • Efficient offset-based sampling for all databases
  • Intelligent strategy selection based on table size and database type
  • Configurable sampling methods for different use cases

Performance Comparison

Real-world benchmark results comparing RandomRails with traditional methods (10 iterations each):









































Sample Size ORDER BY RANDOM() User.random() User.sample() Performance Gain
1,000 users 3.8359s 0.2157s 347.1409s 17.79x faster
10,000 users 6.1273s 2.7313s 369.7583s 2.24x faster
100,000 users 31.578s 3.6968s 369.4334s 8.54x faster
1,000,000 users 171.497s 5.3441s 373.6102s 32.09x faster

image

Key Takeaways:

  • RandomRails consistently outperforms ORDER BY RANDOM() by 2-32x
  • Performance advantage increases dramatically…




Top comments (0)