Trong bài viết này, bạn sẽ học cách test database performance trong Rails và giải quyết một số common database performance issues nhất.
Khi bạn develop Rails application, ActiveRecord là default tool manage database. ActiveRecord cung cấp interface dễ dàng và nhanh để query và insert data dùng commands như .where, .save, .create, và .update. Rails làm việc convert các commands thành SQL queries, điều này tốt, nhưng đôi khi gây performance issues. Quan trọng là bạn hiểu một số common issues và cách optimize performance.
Lưu Ý Nhanh Về ActiveRecord Trong Ruby on Rails
Rails ActiveRecord là layer trong Model-View-Controller (MVC) manage database bằng cách represent nó như business object. ActiveRecord pattern dùng ORM technique để connect objects của application đến relational database table management system.
Bây giờ, hãy bắt đầu!
3 Cách Identify Và Test Database Performance Issues Trong Rails
1. Chạy Explain Trên ActiveRecord Queries
Explain statement hiển thị thông tin về execution plan của SQL query - query sẽ được execute như thế nào, bao gồm số rows sẽ được scan, index nào sẽ được dùng, và cách tables được joined.
Execution plan giúp figure out gì làm chậm query execution bằng cách nhìn vào:
- Index nào nên thêm để improve performance của query.
- Tables có được joined theo optimal order không. Bạn có thể dùng
STRAIGHT_JOINđể force table order trong join statement cho better performance.
Explain hoạt động trên SELECT, DELETE, INSERT, REPLACE và UPDATE statements.
Dùng explain với ActiveRecord rất straightforward. Thực hiện:
User.where(id: 1).explain
Thêm .explain ở cuối command cung cấp query plan cho ActiveRecord commands. Ví dụ trên là query rất đơn giản dùng id (primary key) để query table. Output của explain statement cho thấy dùng pkey. Từ đó, bạn chắc chắn statement là optimal và fast.
Bạn có thể thử thêm .explain vào slow queries để uncover order of execution, cùng với index used. Nếu query plan cho thấy Seq Scan, index không được dùng và cần query change hoặc thêm index mới.
Ví dụ khác với join:
User.joins(:collaborations).explain
Ở đây, user table joined với collaborations table. Khi nhìn query plan, collaboration table dùng seq scan và execute first — trong khi user table dùng pkey index và execute later. Bạn có thể thêm index trên cột user_id trong collaborations table để optimize query. Explain giúp break down query, để bạn figure out đâu cần optimization.
2. Measure Key Database Metrics
Query time không phải metric duy nhất để measure xem query có performant không — hãy nhìn several other database metrics, bao gồm:
- CPU usage
- Memory usage
- Disk queue cho waiting IO
- Network bandwidth cho inbound và outbound traffic
- Available disk space
- Throughput
Query có thể slow down khi các metrics này vượt quá certain threshold. Bạn phải look at data point across time range để hiểu performance issues.
Data point cần measure phụ thuộc vào nhiều factors, như:
- Database type: Relational, In-memory, No-SQL, Data-Warehouse
- Server hosted như thế nào: On-premises, On the cloud
Không có single way để monitor database metrics — nó phụ thuộc vào different factors.
3. Measure Rails App Performance Dùng AppSignal
Có thể difficult manage all performance metrics không có central place cho visibility over all queries. Thêm performance code vào every code block có thể cumbersome và unmanageable.
Với tools như AppSignal, bạn dễ dàng integrate performance measurement vào application. AppSignal support Rails out of the box. Tìm hiểu simple AppSignal installation process từ documentation 'AppSignal for Ruby'.
Một số critical metrics cần keep an eye on:
- Slow queries
- Database performance dựa trên throughput
- N+1 queries
- Database latency
- Số active connections
Đây là AppSignal dashboard có thể trông như thế nào:

7 Cách Optimize Ruby on Rails Database Performance
1. Eager Loading Cho N+1 Queries
N+1 queries là common database performance problem nhất. Xem ví dụ N+1 query với hai models — user và project:
class User < ApplicationRecord
has_many :projects
end
class Project < ApplicationRecord
belongs_to :user
end
Bây giờ, nếu muốn find user và project names, chạy code sau:
users = User.all
users.each do |user|
puts user.projects.map(&:name)
end
Code trên sẽ query database với mỗi loop và gây performance issues. Tổng số queries executed = số users + 1.
Eliminate issue này rất đơn giản: eager load association. Chỉ cần thêm .includes(:projects) ở cuối query:
users = User.includes(:projects).all
users.each do |user|
puts user.projects.map(&:name)
end
Bây giờ, executing loop sẽ không query database, vì query trên eager loads projects:
# Chỉ 2 queries: SELECT * FROM users; SELECT * FROM projects WHERE user_id IN (...)
Rails 6.1 cung cấp strict loading để ensure association được eager loaded trước khi accessed. Để enable strict loading, thêm line sau trong model:
class User < ApplicationRecord
has_many :projects, strict_loading: true
end
Bây giờ, khi bạn thử access projects không eager loading, Rails sẽ throw ActiveRecord::StrictLoadingViolationError exception.
Nếu không có Rails 6.1, bạn có thể dùng gems như Bullet.
2. Sử Dụng Database Index
Databases cung cấp indexes để giúp retrieve data nhanh hơn. Dùng explain command đã cover, bạn sẽ figure out nếu query dùng proper index.
Bạn có thể change slow query để dùng already existing index hoặc added index giúp improve performance.
Có 4 loại indexes khác nhau trong MySQL:
- Primary key - Index tự động thêm vào primary key, cũng ensure unique
- Unique - Unique key index ensure items added trong attribute luôn unique
- Index - Thêm vào attributes khác primary key
- Full text - Giúp query against character-based data
Index được store trong B-Tree hoặc Hash format.
Indexes có thể thêm vào single field hoặc tạo as composition của multiple fields. Composite index useful để optimize queries include multiple fields. Khi chỉ dùng one index, nó require large dataset scan.
Ví dụ, query sau có 2 fields:
User.where(project: 'abc', country: 'US')
Có thể nhiều users trong project "abc" và country field sẽ bị scan. Quá trình này chậm vì large result dataset. Trong case này, bạn có thể thêm composite index cho cả project và country fields để improve performance.
Bạn có thể thêm index vào Rails với ActiveRecord migration commands:
Single index:
add_index :users, :country
Composite index:
add_index :users, [:project, :country]
3. Sử Dụng Limits
Càng nhiều records returned, performance càng chậm. Tốt hơn làm multiple queries thay vì single query return large data set.
User.limit(100)
Để fetch next 100 batches, dùng offset:
User.limit(100).offset(100)
Điều này significantly improve performance. Một điều nhớ: với higher offset, query gets slower. Add limit to offset.
4. Dùng find_each Để Load Large Number Of Items
Khi iterate over records, batch chúng trong Rails cho better performance:
# Cách KHÔNG TỐT
User.all.each do |user|
# process user
end
Cách này query all records once và gây memory và database performance issues.
Dùng find_each hoặc find_in_batches sẽ improve performance bằng cách làm same operation in batches:
# Cách TỐT
User.find_each do |user|
# process user
end
Mặc định, find_each query results in batch của 1,000. Bạn có thể change batch size bằng argument:
User.find_each(batch_size: 500) do |user|
# process user
end
Bạn cũng có thể dùng find_in_batches dựa trên operation bạn cần. Khác biệt giữa find_in_batches và find_each là find_in_batches yield result as array of models thay vì individual records.
5. Select Required Field Dùng Pluck
Pluck command trực tiếp convert query's result thành array thay vì ActiveRecord object.
Nếu query return large results, dùng Pluck sẽ improve code performance. Pluck chỉ select required field từ database:
# Thay vì
User.select(:name).map(&:name)
# Dùng
User.pluck(:name)
Result fetched từ index, không phải main table, và effective hơn với queries involving sorts.
6. Sử Dụng Bulk Operations
Bulk Delete Delete operation loop qua ActiveRecord object sẽ delete records one at a time:
# CHẤM
User.where(active: false).each(&:destroy)
Delete each record requires nhiều queries đến database. Thay vào đó, optimal dùng single bulk delete_all query:
# NHANH
User.where(active: false).delete_all
Bulk Create Một số người không nhận ra rằng similar to bulk delete, bạn cũng có thể bulk insert với ActiveRecord. Giảm n queries xuống chỉ 1. ActiveRecord::Base create method accept array of hashes as input:
User.create([
{ name: 'John', email: 'john@example.com' },
{ name: 'Jane', email: 'jane@example.com' }
])
7. Dùng In-Memory Calculation Nếu Cần
Trong một số instances, in-memory calculation preferable hơn querying. Giả sử muốn find countries trong database không có user record:
# CHẤM - N queries
Country.all.each do |country|
puts country.name if country.users.empty?
end
Query trên require N queries để get result. Thay vào đó, viết single query find users trong given countries và làm calculation khác in memory:
# NHANH - 1 query + in-memory
countries_with_users = User.select(:country_id).distinct.pluck(:country_id)
Country.where.not(id: countries_with_users).pluck(:name)
Bạn có thể cache để reuse request-response cycle và reduce database load trong some cases. Rails cung cấp 3 caching techniques: page, action, và fragment caching (fragment caching offered by default).
Tóm Lại: Optimize Ruby on Rails Performance Với ActiveRecord Và AppSignal
Okay, time to recap! Trong bài này, chúng ta cover 3 cách identify và test database performance issues trong Rails:
- Chạy Explain trên ActiveRecord queries
- Measure key database metrics
- Measure Rails app performance dùng AppSignal
Và 7 cách optimize database performance, bao gồm:
- Eager loading cho N+1 queries
- Database index
- Limits
find_eachđể load large number of items- Pluck để select required field
- Bulk operations
- In-memory calculation
Rails làm cho việc develop application siêu dễ và nhanh. ActiveRecord giúp productivity, reusability, và maintainability của database code. Hiểu cách ActiveRecord queries translate thành SQL queries và execute là quan trọng.
Tuy nhiên, điều crucial nhất để optimize Rails database performance là visibility over performance data. Performance issues thường gặp, nhưng bạn có thể resolve khi có visibility này. Bạn cần proper monitoring tool cung cấp database metrics. Chúng tôi thích AppSignal ;)
P.S. Nếu bạn muốn đọc các bài Ruby Magic ngay khi xuất bản, hãy đăng ký newsletter Ruby Magic để không bỏ lỡ bất kỳ bài viết nào!