rack-mini-profiler
repository·master·Indexed 23 days ago
https://github.com/miniprofiler/rack-mini-profilerA middleware for Ruby web applications that provides real-time performance profiling. It displays a speed badge on HTML pages and offers deep dives into database queries (Mysql2, Postgres, Oracle, Mongoid3), call-stack profiling via flamegraphs using stackprof, and memory profiling using memory_profiler. It supports integration with Rack, Sinatra, and Hanami, and includes features like snapshots sampling and multiple storage backends including Redis and Memcache.
What's inside rack-mini-profiler
- rack-mini-profiler is a middleware that displays a speed badge on every HTML page. It provides insights into application performance, including database profiling, call-stack profiling via flamegraphs, and memory profiling. It is designed to be used in both development and production environments.
Generate Flamegraphs
masterTo use flamegraphs, add the
stackprofgem to your Gemfile. You can then view flamegraphs using these methods:- Direct HTML response: Append
?pp=flamegraphto the URL or add the headerX-Rack-Mini-Profiler: flamegraph. - Async Flamegraphs: Append
?pp=async-flamegraphto the URL. This returns your normal response (useful for JSON/XHR) and stores the data for later viewing via the 'flamegraph' link in the MiniProfiler UI or theX-MiniProfiler-Flamegraph-Pathheader.
- Direct HTML response: Append
Upgrade speedscope assets
masterTo upgrade the speedscope files and assets used by
rack-mini-profilerto the latest version, run thespeedscope_upgraderake task from the root directory of the repository. This task performs the following actions:- Downloads the latest speedscope release ZIP file from GitHub.
- Removes existing files in the
lib/html/speedscopedirectory. - Extracts the new ZIP file into
lib/html/speedscope. - Modifies
index.htmlto replace external Google Fonts links with local copies from thefontsdirectory, ensuring compatibility with intranet environments that lack third-party internet access.
bundle exec rake speedscope_upgradeImplement access control for rack-mini-profiler in production
masterTo use
rack-mini-profilerin production environments, you must explicitly authorize requests to prevent unauthorized users from seeing profiling data. UseRack::MiniProfiler.authorize_requestwithin your application logic (e.g., in a controller callback) once you have verified the user's identity and permissions.Warning: If your production application runs on multiple servers or dynos, you must configure the storage backend to use Redis or Memcache to ensure consistent profiling data across nodes.
# inside your ApplicationController before_action do if current_user && current_user.is_admin? Rack::MiniProfiler.authorize_request end endPerform Memory Profiling
masterAdd the
memory_profilergem to your Gemfile. To generate a report, append?pp=profile-memoryto your request URL.You can use the following query parameters to filter results (using regular expressions):
memory_profiler_allow_files: Filename pattern to include (default: all).memory_profiler_ignore_files: Filename pattern to exclude (default: none).memory_profiler_top: Number of results per section (default: 50).
Example:
?pp=profile-memory&memory_profiler_allow_files=active_record|appAlternative memory tools (no extra gem required):
?pp=profile-gc: Report Garbage Collection statistics.?pp=analyze-memory: Report ObjectSpace statistics.
Integrate MiniProfiler with Single Page Applications (SPA)
masterSPAs (Ember, Angular, etc.) require manual handling because routes change without full page loads.
- On route transition: Call
window.MiniProfiler.pageTransition()to clear old profiling data and statistics. - Inject Speed Badge: Manually inject the MiniProfiler
<script>tag into your application. Note that thedata-versionGUID and the?v=parameter must match the current release ofrack_mini_profilerto ensure the latest assets are fetched.
// Call this on every SPA route transition if (window.MiniProfiler !== undefined) { window.MiniProfiler.pageTransition(); }- On route transition: Call
Integrate rack-mini-profiler with Rack, Sinatra, or Hanami
masterRack Builder
require 'rack-mini-profiler' use Rack::MiniProfilerSinatra
require 'rack-mini-profiler' class MyApp < Sinatra::Base use Rack::MiniProfiler endHanami
For Hanami, use Rack integration and manually register the rendering method to be profiled:
# config.ru require 'rack-mini-profiler' Rack::MiniProfiler.profile_method(Hanami::View::Rendering::Partial, :render) { "Render partial" } use Rack::MiniProfilerRun the project specifications
masterTo run the test suite, you must have Memcached and Redis services running. Use the following commands to build and run the specs.
$ bundle exec rake build $ bundle exec rake specConfigure MiniProfiler for Heroku Redis
masterWhen using Heroku Redis in production, you may need to configure
storage_optionswith specific SSL parameters to avoid connection issues.if Rails.env.production? Rack::MiniProfiler.config.storage_options = { url: ENV["REDIS_URL"], ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE } } Rack::MiniProfiler.config.storage = Rack::MiniProfiler::RedisStore endInstall rack-mini-profiler
masterAdd
rack-mini-profilerto your Gemfile for Ruby 3.2+.Important: To ensure SQL instrumentation works, you must require
rack_mini_profilerbelow your database gems (likepgormysql2) in the Gemfile.To enable advanced profiling features, include these optional gems:
- Memory profiling:
gem 'memory_profiler' - Call-stack flamegraphs:
gem 'stackprof'
gem 'rack-mini-profiler'- Memory profiling:
View rack-mini-profiler options via query string
masterYou can view the available configuration options and diagnostics settings by appending thepp=helpquery string to your request URL.Use Snapshots Sampling to detect rare performance issues
masterSnapshots sampling enables invisible profiling on one request every $N$ requests to capture performance metrics for later review.
Configuration
- Set
snapshot_every_n_requeststo a value $> 0$. - View collected snapshots at
/mini-profiler-resources/snapshots(or your configuredbase_url_path). - Snapshots are grouped by HTTP method/path (or
controller#actionin Rails).
Snapshots Transporter
You can aggregate snapshots from multiple sources by configuring a transporter:
snapshots_transport_destination_url: The destination URL.snapshots_transport_auth_key: The secure key for authorization (sent viaMini-Profiler-Transport-Authheader).snapshots_transport_gzip_requests: Set totrueto enable gzip compression.
Adding Custom Fields to Snapshots
Use the following method to attach application-specific metadata (like user ID or app version) to a snapshot:
Rack::MiniProfiler.add_snapshot_custom_field(<key>, <value>)- Set