ActiveRecord Sharding Plugin
ActiveRecord::Turntable is a database sharding extension for ActiveRecord.
activerecord(>=5.0.0, <6.0)
If you are using with older activerecord versions, use following versions.
MySQL only.
Add to Gemfile:
gem 'activerecord-turntable', '~> 4.4.1'
Run a bundle install:
bundle install
Run install generator:
bundle exec rails g active_record:turntable:install
generator creates
#{Rails.root}/config/turntable.yml
Shard is a database which is horizontal partitioned.
Cluster of shards. i.e) set of userdb1, userdb2, userdb3. Shards in the same cluster should have the same schema structure.
Default ActiveRecord::Base's connection.
Turntable's sequence system for clustered database.
This keeps primary key ids to be unique each shards.
One main database(default ActiveRecord::Base connection) and three user databases sharded by user_id.
+-------+ | App | +-------+ | +---------+---------+---------+---------+ | | | | | `--------` `-------` `-------` `-------` `-------` | Master | |UserDB1| |UserDB2| |UserDB3| | SeqDB | `--------` `-------` `-------` `-------` `-------`
Edit DSL type configuration file(config/turntable.rb) or YAML configuration file(turntable.yml). And add database connection settings to database.yml.
See below example config.
cluster :user_cluster do # algorithm [algorithm name symbol(range|range_bsearch|modulo)] algorithm :range_bsearchsequencer [sequence name] [sequence type] [*options hash]
sequencer :user_seq, :mysql, connection: :user_seq
shard [range], to: [connection names in database.yml]
shard 1...100, to: :user_shard_1 shard 100...200, to: :user_shard_2 shard 200...2000000000, to: :user_shard_3
If you are using modulo algorithm, pass integer sequence start with zero.
shard 0, to: :user_shard_1
shard 1, to: :user_shard_2
shard 2, to: :user_shard_3
end
development: clusters: user_cluster: #
connection_spec: &spec adapter: mysql2 encoding: utf8 reconnect: false pool: 5 username: root password: root socket: /tmp/mysql.sockdevelopment: <<: database: sample_app_development seq: sequence database definition user_seq_1: sample_app_user_seq_development shards: shards user_shard_1: sample_app_user1_development user_shard_2: sample_app_user2_development user_shard_3: sample_app_user3_development>
About algorithms
algorithm :range_bsearchshard 1...20_000, to: :user_shard_1 shard 20_000...40_000, to: :user_shard_2 shard 40_000...60_000, to: :user_shard_1 shard 60_000...80_000, to: :user_shard_2 shard 80_000...10_000_000, to: :user_shard_3
algorithm :moduloshard 0, to: :user_shard_1 shard 1, to: :user_shard_2 shard 2, to: :user_shard_3
default hash function is
Zlib.crc32(key.to_s)
algorithm :hash_slot # Or specify hash function # algorithm :hash_slot, hash_func: ->(key) { Zlib.adler32(key.to_s) }shard 0...4096, to: :user_shard_1 shard 4096...8192, to: :user_shard_2 shard 8192...12288, to: :user_shard_3 shard 12288...16384, to: :user_shard_4
Slave enabled configuration examples:
cluster :user_cluster do ...shard [range], to: [connection names in database.yml]
shard 1...100, to: :user_shard_1, slaves: [:user_shard_1_1] shard 100...200, to: :user_shard_2, slaves: [:user_shard_2_1] shard 200...2000000000, to: :user_shard_3, slaves: [:user_shard_3_1] end
development: clusters: user_cluster: #
Add slave connection settings under
shards.
... shards: user_shard_1: <<: database: turntable_user_shard_1_test user_shard_1_1: turntable_user_shard_1_1_test user_shard_2: turntable_user_shard_2_test user_shard_2_1: turntable_user_shard_2_1_test user_shard_3: turntable_user_shard_3_test user_shard_3_1: turntable_user_shard_3_1_test>Slave usage:
User.with_slave { # `User` model will use slave databases within this block. }User.with_master {
User
model will use master database within this block.}
Example Migration
Generate a model:
bundle exec rails g model user name:stringAnd Edit migration file:
class CreateUsers < ActiveRecord::Migration # Specify cluster executes migration if you need. # Default, migration would be executed to all databases. # clusters :user_clusterdef change create_table :users do |t| t.string :name t.timestamps end create_sequence_for(:users) #
Then please execute rake tasks:
bundle exec rake db:create bundle exec rake db:migrateThose rake tasks would be executed to shards too.
Example Model
Add turntable [shardkeyname] to the model class:
class User < ApplicationRecord turntable :user_cluster, :id sequencer :user_seq has_one :status endclass Status < ApplicationRecord turntable :user_cluster, :user_id sequencer :user_seq belongs_to :user end
Usage
Creating
> User.create(name: "hoge") (0.0ms) [Shard: user_seq_1] BEGIN (0.3ms) [Shard: user_seq_1] UPDATE `users_id_seq` SET id=LAST_INSERT_ID(id+1) (0.8ms) [Shard: user_seq_1] COMMIT (0.1ms) [Shard: user_seq_1] SELECT LAST_INSERT_ID() (0.1ms) [Shard: user_shard_1] BEGIN [ActiveRecord::Turntable] Sending method: insert, sql: #<:insertmanager:0x007f8503685b48>, shards: ["user_shard_1"] SQL (0.8ms) [Shard: user_shard_1] INSERT INTO `users` (`created_at`, `id`, `name`, `updated_at`) VALUES ('2012-04-10 03:59:42', 2, 'hoge', '2012-04-10 03:59:42') (0.4ms) [Shard: user_shard_1] COMMIT => #Retrieving
> user = User.find(2) [ActiveRecord::Turntable] Sending method: select_all, sql: #<:selectmanager:0x007f850466e668>, shards: ["user_shard_1"] User Load (0.3ms) [Shard: user_shard_1] SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 => #Updating
> user.update_attributes(name: "hogefoo") (0.1ms) [Shard: user_shard_1] BEGIN [ActiveRecord::Turntable] Sending method: update, sql: UPDATE `users` SET `name` = 'hogefoo', `updated_at` = '2012-04-10 04:07:52' WHERE `users`.`id` = 2, shards: ["user_shard_1"] (0.3ms) [Shard: user_shard_1] UPDATE `users` SET `name` = 'hogefoo', `updated_at` = '2012-04-10 04:07:52' WHERE `users`.`id` = 2 (0.8ms) [Shard: user_shard_1] COMMIT => trueDelete
> user.destroy (0.2ms) [Shard: user_shard_1] BEGIN [ActiveRecord::Turntable] Sending method: delete, sql: #<:deletemanager:0x007f8503677ea8>, shards: ["user_shard_1"] SQL (0.3ms) [Shard: user_shard_1] DELETE FROM `users` WHERE `users`.`id` = 2 (1.7ms) [Shard: user_shard_1] COMMIT => #Counting
> User.count [ActiveRecord::Turntable] Sending method: select_value, sql: #<:selectmanager:0x007f9e82ccebb0>, shards: ["user_shard_1", "user_shard_2", "user_shard_3"] (0.8ms) [Shard: user_shard_1] SELECT COUNT(*) FROM `users` (0.3ms) [Shard: user_shard_2] SELECT COUNT(*) FROM `users` (0.2ms) [Shard: user_shard_3] SELECT COUNT(*) FROM `users` => 1Sequencer
Sequencer provides generating global IDs.
Turntable has follow 3 sequencers currently:
First, add configuration to turntable.yml and database.yml
development: ... seq: #
development: clusters: user_cluster: #Add below to the migration:
create_sequence_for(:users) #Next, add sequencer definition to the model:
class User < ApplicationRecord turntable :id sequencer :user_seq #Barrage example
First, add barrage gem to your Gemfile:
gem 'barrage'Then, add configuration to turntable.yml:
development: clusters: user_cluster: #Next, add sequencer definition to the model:
class User < ApplicationRecord turntable :id sequencer :barrage_seq #Katsubushi example
katsubushi is available as a sequence server. ActiveRecord::Turntable accesses katsubushi via Dalli.
First, add dalli gem to your Gemfile:
gem 'dalli'Then, add configuration to turntable.yml:
development: clusters: user_cluster: #Next, add sequencer definition to the model:
class User < ApplicationRecord turntable :id sequencer :katsubushi_seq #Transactions
Turntable has some transaction support methods.
shards_transaction
Pass AR::Base instances,
shards_transactionmethod suitable shardsuser = User.find(2) user3 = User.create(name: "hoge3")User.shards_transaction([user, user3]) do user.name = "hogehoge" user3.name = "hogehoge3" user.save! user3.save! end
cluster_transaction
When executing transaction on all shards in the cluster, use
#{cluster_name}_transactionmethod:User.user_cluster_transaction do # Transaction is opened all shards in "user_cluster" endMigration
If you specify cluster or shard, migration will be executed to the cluster(or shard) and master database.
Default, migrations will be executed to all databases.
to specify cluster:
class CreateUsers < ActiveRecord::Migration clusters :user_cluster .... endto specify shard:
class CreateUsers < ActiveRecord::Migration shards :user_shard_01 .... endLimitations
User-Friend-Userrelation
Use
with_shardmethod:
AR::Base.with_shard(shard1) do # something queries to shard1 end
with_shardmethod accepts following types to specify a shard:
AR::Base#turntable_shardwill be used
To access shard objects, use below:
Use with_all method:
User.with_all do User.order("created_at DESC").limit(3).all end # => Returns Array of results
Normally, activerecord-turntable detects shard keys on associated models, but auto-detection will fail with following conditions:
For example:
class User # shard key: # foreign key: main_user_item_id belongs_to :main_user_item, class_name: "UserItem", required: false endclass UserItem
shard key name: :user_id
turntable :user_cluster, :user_id end
This example raises CannotSpecifyShardError
> user.main_user_item User Load [Shard: master] (0.4ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1 [ActiveRecord::Turntable] Error on Building Fader: SELECT `user_items`.* FROM `user_items` WHERE `user_items`.`id` = 2198059200000 LIMIT 1, on_method: select_all, err: cannot specifyshard for query: SELECT "user_items".* FROM `user_items` WHERE (`user_items`.`id` = 2198059200000) LIMIT 1 ActiveRecord::Turntable::CannotSpecifyShardError: cannot specify shard for query: SELECT "user_items".* FROM `user_items` WHERE (`user_items`.`id` = 2198059200000) LIMIT 1
Use foreignshardkey option to pass a shard key condition:
-belongs_to :main_user_item, class_name: "UserItem" +belongs_to :main_user_item, class_name: "UserItem", foreign_shard_key: :id
> user.main_user_item User Load [Shard: master] (0.2ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1 [ActiveRecord::Turntable] Sending method: select_all, sql: #<:selectmanager:0x007f8080bd0670>, shards: ["user_shard_1"] Changing UserItem's shard to user_shard_1 UserItem Load [Shard: user_shard_1] (0.2ms) SELECT `user_items`.* FROM `user_items` WHERE `user_items`.`user_id` = 1 AND `user_items`.`id` = 2198059200000 LIMIT 1 Changing UserItem's shard to master => #
To notice queries causing performance problem, Turntable has follow options.
Add to turntable.yml or turntable.rb:
development: .... raise_on_not_specified_shard_query: true raise_on_not_specified_shard_update: true
# Write on top level raise_on_not_specified_shard_query true raise_on_not_specified_shard_update true
ConnectionProxy, Distributed Migration implementation is inspired by Octopus and DataFabric.
activerecord-turntable is released under the MIT license:
Copyright (c) 2012 Drecom Co.,Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.