0
0
Ruby on Railsframework~8 mins

Callbacks overview in Ruby on Rails - Performance & Optimization

Choose your learning style9 modes available
Performance: Callbacks overview
MEDIUM IMPACT
Callbacks affect the server response time and database transaction speed by adding extra processing steps during model lifecycle events.
Running complex logic on every model save
Ruby on Rails
class User < ApplicationRecord
  after_commit :enqueue_heavy_job

  def enqueue_heavy_job
    HeavyJob.perform_later(self.id)
  end
end
Moves heavy work to background job, keeping request fast and non-blocking.
📈 Performance Gainreduces request blocking to near zero, improves server throughput
Running complex logic on every model save
Ruby on Rails
class User < ApplicationRecord
  before_save :heavy_computation

  def heavy_computation
    # complex calculations or external API calls
  end
end
This callback runs heavy logic on every save, blocking the request and increasing response time.
📉 Performance Costblocks server response for 100+ ms per save, increasing request latency
Performance Comparison
PatternServer ProcessingDatabase ImpactResponse DelayVerdict
Heavy logic in before_saveHigh CPU usageBlocks transactionIncreases latency[X] Bad
Lightweight after_commit with background jobMinimal CPUNon-blockingFast response[OK] Good
Rendering Pipeline
Rails callbacks run during model lifecycle events before or after database operations, affecting server processing time before response is sent.
Model Validation
Database Transaction
Controller Response
⚠️ BottleneckHeavy or synchronous callbacks block database transactions and delay response.
Optimization Tips
1Avoid heavy or blocking logic in before_save or before_create callbacks.
2Use after_commit callbacks to trigger background jobs for heavy tasks.
3Monitor callback execution time to prevent slow server responses.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using heavy logic in before_save callbacks?
AIt increases CSS paint time.
BIt causes visual layout shifts on the client.
CIt blocks the database transaction and delays the server response.
DIt reduces bundle size.
DevTools: Rails logs and New Relic (or similar APM)
How to check: Check Rails server logs for callback execution time or use APM to profile request breakdown.
What to look for: Long callback durations or increased request time before response indicates performance issues.