How to setup Rails schema cache with Unicorn, Octopus, and Postgresql

Viewed 345

I have this setup:

I want to make use of Rails' schema cache feature because whenever a worker starts, my database is hit with queries similar to below:

SELECT a.attname
FROM
  (SELECT indrelid,
          indkey,
          generate_subscripts(indkey, $1) idx
   FROM pg_index
   WHERE indrelid = $2::regclass
     AND indisprimary ) i
JOIN pg_attribute a ON a.attrelid = i.indrelid
AND a.attnum = i.indkey[i.idx]
ORDER BY i.idx;

I created the schema cache file db/schema_cache.yml with rake db:schema:cache:dump and enabled the setting config.active_record.use_schema_cache_dump = true. However, my database is still hit by those queries when I check with:

SELECT interval '1 millisecond' * total_time AS total_exec_time,
       to_char((total_time/sum(total_time) OVER()) * 100, 'FM90D0') || '%' AS prop_exec_time,
       to_char(calls, 'FM999G999G999G990') AS ncalls,
       interval '1 millisecond' * (blk_read_time + blk_write_time) AS sync_io_time,
       query AS query
FROM pg_stat_statements
WHERE userid =
    (SELECT usesysid
     FROM pg_user
     WHERE usename = CURRENT_USER
     LIMIT 1)
ORDER BY total_time DESC
LIMIT 100;

I have these configs for by unicorn worker which I have removed after reading this github issue: https://github.com/rails/rails/issues/35770. Now it seems that the queries are not run when a worker start but if I access the database (e.g. calling an endpoint which read something from the database), those queries would be run on my database again.

before_fork do |server, worker|
  if defined?(Octopus) && Octopus.enabled?
    ActiveRecord::Base.connection_proxy.clear_all_connections!
  else
    ActiveRecord::Base.connection.disconnect!
  end
end

after_fork do |server, worker|
  ActiveRecord::Base.establish_connection
  ActiveRecord::Base.connection_proxy.initialize_shards(Octopus.config) if defined?(Octopus) && Octopus.enabled?
end

Is there something wrong with my setup that I haven't realized yet? Or do I need to do some extra steps for things to work?

Thanks in advance!

0 Answers
Related