• This repository has been archived on 27/Sep/2024
  • Stars
    star
    411
  • Rank 105,247 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 3 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Performance profiling for Rails, made simple πŸ¦”

Rails Mini Profiler

logo

Performance profiling for Rails, made simple.

Gem Version Main License

Maintainability Test Coverage

What's this?

Rails Mini Profiler is an easy-to-use performance profiler for your Rails applications. It is heavily inspired by Rack Mini Profiler and other APM tools. To find out how it stacks up against those check out Why Rails Mini Profiler?

To see it in action view the preview below:

Rails Mini Profiler Preview

Note: This gem is in early development and I'm looking for contributors. Try it out and leave some feedback, it really goes a long way in helping me out with development. Any feature request or bug report is welcome. If you like this project, leave a star to show your support! ⭐

Getting Started

Add Rails Mini Profiler to your Gemfile:

gem 'rails_mini_profiler'

Install the gem and run the installer:

bundle install
rails rails_mini_profiler:install

Inspect the generated migration in db/migrate and run it:

rails db:migrate

Start your Rails application and perform some requests. You can either click the little hedgehog πŸ¦” on the top left or navigate to /rails_mini_profiler to view collected performance metrics.

Usage

Rails Mini Profiler provides detailed information about your requests to help you figure out why certain requests perform poorly.

Installing it will generate a new initializer config/initializers/rails_mini_profiler.rb and add a new route:

# routes.rb
Rails.application.routes.draw do
  mount RailsMiniProfiler::Engine => '/rails_mini_profiler'
end

Once you perform requests against your applications you can inspect them using that route, or by clicking the badge on the top right that is injected into your pages.

Request Overview

overview

Requests to your application will be profiled automatically. You can view and search all stored requests by navigating to yourapp/rails_mini_profiler/profiled_requests.

Request Details

Light Β  Β  Β  Β  Dark

This view shows you how your requests spend their time. How much of it is spent in the DB, how much in rendering views? May can filter and clicking on individual traces to gain deeper insights and see detailed information.

Flamegraphs

Rails Mini Profiler automatically records Flamegraphs for profiled requests. To enable this feature, add Stackprof to your Gemfile:

gem 'stackprof'

For convenience, Flamegraphs are recorded for every request. This may incur a significant performance penalty. To change the default behavior see Configuration.

Flamegraphs are rendered using Speedscope. See Troubleshooting if Flamegraphs are not rendering correctly.

Configuration

Rails Mini Profiler provides a wide array of configuration options. You can find details below. For an example configuration check initializers/rails_mini_profiler.rb (or the template file).

Name Default Description
enabled true (dev)/ false (prod) Whether or not RMP is enabled
flamegraph_enabled true Should flamegraphs be recorded automatically?
flamegraph_sample_rate 0.5 The flamegraph sample rate. How many snapshots per millisecond are created.
skip_paths [] An array of request paths that should not be profiled. Regex allowed.
storage Storage.new Storage configuration. See Storage.
ui UserInterface.new UI configuration. See UI.
user_provider Rack::Request.new(env).ip How to identify users. See Authorization

Storage

Rails Mini Profiler stores profiling information in your database per default. You can configure various details of how traces and requests are stored.

Name Default Description
database nil Set a custom database to be used for storing profiler information. Uses connect_to for profiler records
profiled_requests_table rmp_profiled_requests The table to be used to store profiled requests.
flamegraphs_table rmp_flamegraphs The table to be used to store flamegraphs.
traces_table rmp_traces The table to be used to store traces.

Rails Mini Profiler does not offer an automatic way to clean up old profiling information. It is recommended you add a sweeper job to clean up old profiled requests periodically (e.g. using clockwork. For example, with ActiveJob:

# Clockwork
every(1.month, 'purge rails mini profiler') do
    ProfiledRequestCleanupJob.perform_later
end

# ActiveJob
class ProfiledRequestCleanupJob < ApplicationJob
  queue_as :default

  def perform
    RailsMiniProfiler::ProfiledRequest.where('created_at < ?', 1.month.ago).destroy_all
  end
end

UI

Rails Mini Profiler allows you to configure various UI features.

Name Default Description
badge_enabled true Should the hedgehog πŸ¦” badge be injected into pages?
badge_position 'top-left' Where to display the badge. Options are 'top-left', 'top-right', 'bottom-left, 'bottom-right'
base_controller ApplicationController Which controller UI controllers should inherit from.
page_size 25 The page size for lists shown in the UI.
webpacker_enabled true Use Webpacker if available? Disable to fall back to the asset pipeline.

Request Configuration

You may override static configuration on a per-request by attaching request parameters. For example, https://myapp.com/api/mydata?rmp_flamegraph=false

Name Description
rmp_flamegraph Overrides flamegraph_enabled If set to true will redirect to the flamegraph immediately.

Authorization

Profiling information is segregated by user ID. That means users cannot see each other's profiled requests. Per default, individual users are identified by their IP adress.

You may change this by setting a custom user provider:

config.user_provider = proc { |env| Rack::Request.new(env).ip }

You may also explicitly set the user by modifying your application controller (or the controller you have configured as UI base controller):

class ApplicationController < ActionController::Base
  before_action do
    RailsMiniProfiler::User.authorize(current_user.id)
  end
end

ApplicationController is used as the default base class for UI controllers. To change it, you may use configuration.ui.base_controller.

Profiling in Production

Rails Mini Profiler is not intended for performance reporting. There are other tools for that ( Skylight, New Relic, DataDog...). But you can still use RMP in production to profile specific requests.

Per default, no requests will be profiled in production, and the Rails Mini Profiler UI will be inaccessible.

Enabling Profiling

Since profiling impacts performance, it is recommended that you limit which requests are being profiled:

RailsMiniProfiler.configure do |config|
  config.enabled = proc { |env| env.headers['RMP_ENABLED'].present? }
end

Authorizing Users

You must explicitly authorize profiling for users, as well as authenticate them to the UI:

class ApplicationController < ActionController::Base
  before_action do
    RailsMiniProfiler::User.authorize(current_user.id) # Requests by this user will now be profiled, and they get access to the UI
  end
end

Why Rails Mini Profiler?

Improving the performance of any application is a 3-step process. You have to answer these questions:

  1. What is slow?
  2. Why is it slow?
  3. Did my solution fix the slowness?

I'm a huge fan of rack-mini-profiler, and APM tools such as Skylight or Scout APM. Each of these tools has its own areas where it succeeds.

APM tools are excellent for profiling your app in production - aka. they show you what is slow - and offer some hints as to what causes the slowdown. rack-mini-profiler can do some sampling in production, but excels at providing detailed insight into why something is slow by providing Flamegraphs and detailed query information.

Rails Mini Profiler improves upon rack-mini-profiler in the latter regard. It is a developer tool, rather than a monitoring tool, and sets a big focus on developer experience. Simply put, it aims to be the best tool available to help you figure out why specific requests are slow.

As such, compared to rack-mini-profiler, it does not support non-Rails apps (e.g. Sinatra) or production sampling, but provides a much better user experience and better support for API-only applications.

Troubleshooting

Upgrading

Rails Mini Profiler is in early development. As such, breaking changes may still be introduced on a regular basis. While Rails Mini Profiler is in pre-release we do not offer upgrade migrations.

If an upgrade to Rails Mini Profiler breaks your application, we recommend that you clean house and start over. Re-run the initializer and overwrite existing files:

rails rails_mini_profiler:install

If only the DB schema is out of date, drop the offending tables and re-run migrations for the latest version:

rails rails_mini_profiler:install:migrations
rails db:migrate

Support for API-Only Apps

Rails Mini Profiler supports API-only apps, but you have to make some small adjustments to use it. At the top of application.rb add Sprockets:

require "sprockets/railtie"

Then, modify application.rb:

module ApiOnly
  class Application < Rails::Application
    
    config.api_only = true # Either set this to false
    config.middleware.use ActionDispatch::Flash # Or add this
  end
end

Note: Sprockets and flash are currently required for some of Rails Mini Profiler's UI features. These modifications may no longer be needed in the future.

No Flamegraphs are being recored?

Make sure you have added StackProf to your Gemfile.

gem 'stackprof'

Flamegraphs are not rendering?

Flamegraphs are loaded into Speedscope using an Iframe and URI Encoded blobs (see source) If your browser gives you warnings about blocking content due to CSP you must enable blob as default source:

Rails.application.config.content_security_policy do |policy|
    policy.default_src :self, :blob
    ...
end

Some requests have no Flamegraphs attached?

StackProf, which is used for recording Flamegraphs, does not work on concurrent requests. Because of this, concurrent requests may skip recording a Flamegraph.

It is recommended that you resend only the request you wish to build a Flamegraph for.

Credit

This project was heavily inspired by projects such as rack-mini-profiler and rack-profiler. Skylight was also a huge influence.

Lena Schnedlitz designed the Logo and provided great support. Without her supreme CSS skills this project would not have been possible πŸ™Œ

Contributing

See Contributing

License

This gem is available as open source under the terms of the MIT License.

More Repositories

1

data-dead-drop

Simple, quick data sharing. For humans and machines πŸ€–
Ruby
38
star
2

graphql-groups

Run group- and aggregation queries with graphql-ruby
Ruby
24
star
3

puny-monitor

A batteries-included monitoring tool for single hosts. Works great with Kamal πŸ’Ž
Ruby
23
star
4

mr-loga-loga

The bombastic, fantastic logger for Ruby πŸ’Ž
Ruby
22
star
5

fzf-git

Zsh plugin for nice git completions using fzf
Shell
21
star
6

schienenzeppelin

A Rails app generator to get you started quickly. Includes TailwindCSS, Devise, Deployment and more
Ruby
20
star
7

git-aliases

A pretty git-alias cheat sheet. Includes a print version:
HTML
14
star
8

spinny

Another spinner written in bash. Customizable and pretty πŸ’„
Shell
12
star
9

sommerkinos

Kalendar fΓΌr Sommerkinos in Wien
11
star
10

tints-n-shades

The tints & shades generator for CLI lovers 🌈
Ruby
9
star
11

reveal.js-starter

A template to quickly get started with customizable reveal.js presentation πŸ–Ό
JavaScript
8
star
12

googleme

Demo of OAuth for Ruby CLI's
Ruby
5
star
13

anonymous-location

Share your location with anyone. Completely anonymous.
Ruby
4
star
14

kalamazoo

A minimal Rails template focused on shipping stuff, fast πŸš€
Ruby
4
star
15

actioncable-cli

Ruby
3
star
16

locality

Managing machine-specific changes to your dotfiles πŸŒ‹
Shell
2
star
17

meisterstar

A sparkling meisterstar in your terminal ⭐
Shell
2
star
18

gatsh

gatsh is a simple shell script to compile multiple shell scripts into a single one
Shell
2
star
19

mochma

Extract TODOs from your files using the power of bash πŸ’ͺ
Shell
1
star
20

sublime-micro-16

Syntax definitions for Micro16-Code
1
star
21

tuwien.sepm

The repository for the SEPM introduction exercise
Java
1
star
22

sernie-banders

Making The Front Page Great Again
JavaScript
1
star
23

samsonr

A simple command line client for Samson, written in Rust
Rust
1
star
24

jpf-samples

Some examples on how to use JPF.
Java
1
star
25

battle-kittens

A simple angular application. Includes lots of kittens
TypeScript
1
star
26

fabulous-factorybot

A simple tutorial project to show off some trickery with factorybot πŸ€–
Ruby
1
star
27

tired-dad-notes

Tired dad write about life with smol baby πŸ‘Ά
CSS
1
star