Base operations of Rails are handled by a tight-knit set of Railties.
One such Railtie is responsible is to load information about database connections.
This is done on application boot using the SHOW FULL FIELDS
SQL query.
However, this is a very expensive operation.
For applications that run across multiple servers,
this can lead to a significant performance degradation.
Rails offers schema cache in these scenarios which can be used to avoid the expensive SHOW FULL FIELDS
query.
The cache file is nothing but a Rails readable file which contains the schema information.
This file can be generated using the rails db:schema:cache:dump
command.
Before
Rails loads the schema cache on application boot. Though this is a very expensive operation, it is done only once on load, hence, it can be managed. Once loaded, the information sits in a shared memory which can be accessed by all the processes.
The Railtie also checks the version of the schema cache file
and if it is not the same as the current version of the latest record in the schema_migrations
table, it will reload the schema cache.
This can be managed by setting the check_schema_cache_dump_version
config option.
However, this option
has been classified as a “misfeature”
and may be removed in the future.
After
Rails 7 now uses a config option to switch between eager
and lazy schema cache loading.
This PR introduced the config option config.active_record.lazily_load_schema_cache
which can be set to true
to enable lazy loading of the schema cache.
It is set to false in the default behavior.
Setting the option to true
will skip the Railtie during boot
and only load the schema cache when the ActiveRecord::Base.connection
is accessed.
The default cache file is db/schema_cache.yml
.
This can be configured using the schema_cache_path
config option.
It must be noted that applications can still continue dumping the cache like normal. This change is only related to loading form cache.