activerecord-turntable

by drecom

ActiveRecord Sharding Plugin

205 Stars 29 Forks Last release: Not found MIT License 705 Commits 47 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

ActiveRecord::Turntable

Gem Version Build Status Coverage Status License

ActiveRecord::Turntable is a database sharding extension for ActiveRecord.

Dependencies

activerecord(>=5.0.0, <6.0)

If you are using with older activerecord versions, use following versions.

Supported DBMS

MySQL only.

Installation

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

Terminologies

Shard

Shard is a database which is horizontal partitioned.

Cluster

Cluster of shards. i.e) set of userdb1, userdb2, userdb3. Shards in the same cluster should have the same schema structure.

Master

Default ActiveRecord::Base's connection.

Sequencer

Turntable's sequence system for clustered database.

This keeps primary key ids to be unique each shards.

Example

Example Databases Structure

One main database(default ActiveRecord::Base connection) and three user databases sharded by user_id.

                  +-------+
                  |  App  |
                  +-------+
                      |
       +---------+---------+---------+---------+
       |         |         |         |         |
  `--------` `-------` `-------` `-------` `-------`
  | Master | |UserDB1| |UserDB2| |UserDB3| | SeqDB |
  `--------` `-------` `-------` `-------` `-------`

Example Configuration

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.

  • example turntable.rb
cluster :user_cluster do
  # algorithm [algorithm name symbol(range|range_bsearch|modulo)]
  algorithm :range_bsearch

sequencer [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

  • example turntable.yml
    development:
      clusters:
        user_cluster: # 
  • database.yml
    connection_spec: &spec
      adapter: mysql2
      encoding: utf8
      reconnect: false
      pool: 5
      username: root
      password: root
      socket: /tmp/mysql.sock

development:
  &lt;<: 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

  • range, range_bsearch - distribute records by key range
  algorithm :range_bsearch

shard 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

  • modulo - distribute records by key modulo
  algorithm :modulo

shard 0, to: :user_shard_1 shard 1, to: :user_shard_2 shard 2, to: :user_shard_3

  • hash_slot - distribute records by key hashes

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 support (experimental)

Slave enabled configuration examples:

  • config/turntable.rb
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

  • config/turntable.yml
    development:
      clusters:
        user_cluster: # 
  • config/database.yml

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:string

And Edit migration file:

class CreateUsers < ActiveRecord::Migration
  # Specify cluster executes migration if you need.
  # Default, migration would be executed to all databases.
  # clusters :user_cluster

def 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:migrate

Those 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
end

class 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
    => true

Delete

    > 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`
    => 1

Sequencer

Sequencer provides generating global IDs.

Turntable has follow 3 sequencers currently:

  • :mysql - Use database table to generate ids.
  • :barrage - Use barrage gem to generate ids
  • :katsubushi - katsubushi sequencer backend

Mysql example

First, add configuration to turntable.yml and database.yml

  • database.yml
    development:
      ...
      seq: # 
  • turntable.yml
    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:

  • 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:

  • 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_transaction
method suitable shards
user = 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}_transaction
method:
User.user_cluster_transaction do
  # Transaction is opened all shards in "user_cluster"
end

Migration

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
      ....
    end

to specify shard:

    class CreateUsers < ActiveRecord::Migration
      shards :user_shard_01
      ....
    end

Limitations

  • Queries includes "ORDER BY", "GROUP BY" and "LIMIT" clauses cannot be distributed.
  • "has many through" and "habtm" relationships may returns unexpected results. ex)
    User-Friend-User
    relation

TIPS

Send query to a specific shard.

Use

with_shard
method:
    AR::Base.with_shard(shard1) do
      # something queries to shard1
    end

with_shard
method accepts following types to specify a shard:
  • ActiveRecord::Turntable::Shard object
  • AcitveRecord::Base object -
    AR::Base#turntable_shard
    will be used
  • Numeric, String - a shard key value
  • Symbol - shard name symbol

To access shard objects, use below:

  • AR::Base.connection.shards # \{shardname => shardobj,....}
  • AR::Base#turntable_shard # Returns current object's shard
  • AR::Base.connection.shardfor(shardkey_value) #=> shard

Send query to all shards

Use with_all method:

  User.with_all do
    User.order("created_at DESC").limit(3).all
  end # => Returns Array of results

Cannot specify error is raised between associations

Normally, activerecord-turntable detects shard keys on associated models, but auto-detection will fail with following conditions:

  • foreign key column != shard key column
  • Using different shard key names

For example:

class User
  # shard key:
  # foreign key: main_user_item_id
  belongs_to :main_user_item, class_name: "UserItem", required: false
end

class 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
=> #

Performance Exception

To notice queries causing performance problem, Turntable has follow options.

  • raise_on_not_specified_shard_query - raises on queries execute on all shards
  • raise_on_not_specified_shard_update - raises on updates executed on all shards

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

Thanks

ConnectionProxy, Distributed Migration implementation is inspired by Octopus and DataFabric.

License

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.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.