Ruby on Rails

Performance Optimization

Database indexing, query optimization, Bullet gem, rack-mini-profiler, concurrency/Puma, thread-safety, connection pool

26 interview questionsยท
Senior
1

What is the main purpose of adding an index on a database column?

Answer

An index speeds up search queries by creating an optimized data structure (usually a B-tree) that avoids scanning all rows in the table. Without an index, the database performs a sequential scan which can be very slow on large tables. Columns frequently used in WHERE clauses, ORDER BY or joins are ideal candidates for indexing.

2

How to create a composite index on user_id and created_at columns in a Rails migration?

Answer

The add_index method accepts an array of columns to create a composite index. Column order matters: the index will be efficient for queries filtering first on user_id, then created_at, but not for queries filtering only on created_at. A composite index is optimal for queries using columns from left to right.

3

What is the N+1 problem in the context of ActiveRecord?

Answer

The N+1 problem occurs when an initial query retrieves N records, then N additional queries are executed to load each record's associations. For example, loading 100 posts then making 100 individual queries for authors. This pattern multiplies the number of queries and severely degrades performance. The solution is to use includes, preload or eager_load to load associations in one or two queries.

4

Which ActiveRecord method to use to solve the N+1 problem by loading associations in advance?

5

What is the role of the Bullet gem in Rails performance optimization?

+23 interview questions

Master Ruby on Rails for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free