Created
April 21, 2025 15:28
-
-
Save kirs/d8d83f8a13c0fef5ef1b3fdfb2c378c8 to your computer and use it in GitHub Desktop.
Rails sharding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord < ActiveRecord::Base | |
primary_abstract_class | |
connects_to database: { writing: :primary } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SQLite. Versions 3.8.0 and up are supported. | |
# gem install sqlite3 | |
# | |
# Ensure the SQLite 3 gem is defined in your Gemfile | |
# gem "sqlite3" | |
# | |
default: &default | |
adapter: sqlite3 | |
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> | |
timeout: 5000 | |
development: | |
primary: | |
<<: *default | |
database: storage/development_primary.sqlite3 | |
<% 0.upto(10).map do |i| %> | |
"primary_shard_<%= i %>": | |
<<: *default | |
database: storage/development_primary_shard_<%= i %>.sqlite3 | |
migrations_paths: db/migrate_shard | |
<% end %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveSupport::IsolatedExecutionState.isolation_level = :fiber | |
# per fiber | |
ActiveRecord::Base.connected_to(role: :writing, shard: :shard_0) do | |
Post.with_connection do |conn| | |
conn.execute("select * from posts") | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ShardedRecord < ApplicationRecord | |
self.abstract_class = true | |
connects_to shards: { | |
shard_0: { writing: :primary_shard_0 }, | |
shard_1: { writing: :primary_shard_1 } | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment