Database Sharding in Rails Applications – Vitalik Danchenko | Ruby Meditation #23

Ruby Meditation
Ruby MeditationRuby Meditation
DATABASE SHARDING
IN RAILS APPLICATIONS
RUBY MEDITATION #23
September 2018
Work: @Talkable
Ruby: since 2012
Rails: since v3.2
Open Source: about 0 contributions
@justmacc
@vitalikdanchenko
ABOUT ME
ABOUT ME
Hobby: Running
Marathon Finisher: 4 times
Marathon PB: 3:05:10
ABOUT ME
A LITTLE BIT ABOUT SCALING
DATABASE SHARDING
A LOT OF DIAGRAMS
ALMOST NO CODE
AGENDA
CAN RAILS SCALE?
CAN RAILS SCALE?
— @busterarm at Hacker News
"TWITTER SCALE" WASN'T
SO MUCH A RUBY/RAILS
PROBLEM AS IT WAS AN
RDBMS
”
“
https://news.ycombinator.com/item?id=17217210
CAN RAILS SCALE?
SCALING
SCALABILITY VS PERFORMANCE
SCALING
SCALING
Rails Application
WEB WORKERS
DATABASE
SCALING
Rails Application
WEB WORKERS
BACKGROUND
JOBS
DATABASE
SCALING
Rails Application
WEB WORKERS
BACKGROUND JOBS
DATABASE
SCALING
Rails Application
WEB WORKERS
BACKGROUND JOBS
DATABASE
SCALING
Rails Application
WEB WORKERS
BACKGROUND JOBS DATABASE
SCALING
Rails Application
WEB WORKERS
DATABASE
BACKGROUND JOBS
SCALING
Rails Application
WEB
WORKERS
DATABASE
WEB
WORKERS
WEB
WORKERS
WEB
WORKERS
JOBS JOBS
JOBS JOBS
SCALING
SCALING
DATABASE
DATABASE SCALING
DATABASE
MASTER
DATABASE
SLAVE
DATABASE SCALING
DATABASE
MASTER
DATABASE
SLAVE
DATABASE
SLAVE
DATABASE
SLAVE
DATABASE SCALING
DATABASE
PARTIAL DATA
DATABASE
PARTIAL DATA
DATABASE
PARTIAL DATA
DATABASE SHARDING
FUNCTIONAL EXPRESSIONAL METADATA
Separate
Modules
id % N
year
country
row -> shard
DATABASE SHARDING
THEORETICAL PART
PRACTICAL PART
DATABASE SHARDING IN RAILS
MULTIPLE DATABASES MODEL
1 class ShardedBase < ActiveRecord::Base
2 establish_connection SHARD_DB_CONFIG
3 self.abstract_class = true
4 end
5
6 class Post < ShardedBase
7 end
8
9 class Comment < ShardedBase
10 end
DATABASE SHARDING IN RAILS
GEMS
• thiagopradi/octopus
• hsgubert/rails-sharding
• zendesk/active_record_shards
1 ActiveRecord::Base.on_shard(:number_two) do
2 Post.find_by(author: author)
3 end
DATABASE SHARDING IN TALKABLE
STEP BY STEP
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard?
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard?
BY CUSTOMER
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded?
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded?
THE LARGEST
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1 class Visitor < ShardedRecord
2 has_many :purchases
3 end
4
5 class Purchase < ShardedRecord
6 belongs_to :person
7 has_one :referral
8 end
9
10 class Referral < ShardedRecord
11 has_many :rewards
12 end
13
14 class Reward < ShardedRecord
15 belongs_to :incentive
16 end
DATABASE SHARDING IN TALKABLE
STEP BY STEP
DATABASE
NOT SHARDED
CONFIG DATA
DATABASE
SHARD #1
REFERRAL DATA
DATABASE
SHARD #2
REFERRAL DATA
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins
1 module ShardingJoinFinder
2 TABLE_REFERENCE = /(^|s+)(join|from)s+`?([a-z_]+)`?/i
3
4 def execute(query, name = nil)
5 ensure_sharding_match(query)
6 super(query, name)
7 end
8
9 def select_all(query, *args)
10 ensure_sharding_match(query)
11 super
12 end
13
14 def ensure_sharding_match(query)
15 query.scan(TABLE_REFERENCE).map(&:last)
16 sharded, unsharded = klasses.partition(&:is_sharded?)
17 raise Error if sharded.any? && unsharded.any?
18 end
19 end
20
21 ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend(ShardingJ
22 ActiveRecord::Relation.prepend(ShardingJoinFinder)
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management — gem
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management — gem
5. Add utility helpers
1 class DatabaseUtils
2 class SlaveError < StandardError; end
3
4 class << self
5 def use_shard(shard, &block); end
6 def current_shard; end
7 def uses_slave?; end
8 def config_for(slave: uses_slave?, shard: current_shard); end
9 def connection(slave: uses_slave?, shard: current_shard); end
10 def sharded_tables; end
11 def on_all_shards(&block); end
12 def processlist; end
13 def slave_lag_for(connection); end
14 end
15 end
1 Rails.application.console do
2 def shard(shard)
3 shard = shard.database_shard if shard.respond_to?(:database_shard)
4 DatabaseUtils.use_shard!(shard)
5 end
6 end
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management — gem
5. Add utility helpers — depends on individual needs
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management — gem
5. Add utility helpers — depends on individual needs
6. Migrate
1 production:
2 host: 'master.production.com'
3 database: 'primary'
4 slave:
5 host: 'slave.production.com'
6 database: 'primary'
7
8 shards:
9 1:
10 host: 'master.production.com'
11 database: 'shard_1'
12 slave:
13 host: 'slave.production.com'
14 database: 'shard_1'
15 2:
16 host: 'shard_2.production.com'
17 database: 'shard_2'
18 slave:
19 host: 'slave.shard_2.production.com'
20 database: 'shard_2'
1 production:
2 host: 'master.production.com'
3 database: 'primary'
4 slave:
5 host: 'slave.production.com'
6 database: 'primary'
7
8 shards:
9 1:
10 host: 'shard1.production.com'
11 database: 'shard_1'
12 slave:
13 host: 'slave.shard_1.production.com'
14 database: 'shard_1'
15 2:
16 host: 'shard_2.production.com'
17 database: 'shard_2'
18 slave:
19 host: 'slave.shard_2.production.com'
20 database: 'shard_2'
DATABASE SHARDING IN TALKABLE
STEP BY STEP
1. How to shard? — expressional + metadata
2. Which tables have to be sharded? — config vs referral
3. Get rid of joins — joins detector
4. Introduce connection management — gem
5. Add utility helpers — depends on individual needs
6. Migrate — profit!!!
MySQL PostgreSQL
Vites Citus
Jetpants ???
ScaleBase
DATABASE SHARDING SOLUTIONS
PROS CONS
Easier to Manage Not Easy to Implement
Smaller and Faster Lost Abilities
Reduces Costs
DATABASE SHARDING
CONCLUSION
DATABASE SHARDING
CONCLUSION
• Do not shard your data until you really need it
• Choose a sharding model that fits your context (project)
• Each additional shard increases the chance of a random
crash
When: 08:00 am
Where: 46°28'44.5"N 30°45'41.0"E
How far: doesn’t matter
How fast: doesn’t matter
SUNDAY MORNING RUN
Q&A
1 of 52

Recommended

Amjad's MIS_Resume by
Amjad's MIS_ResumeAmjad's MIS_Resume
Amjad's MIS_ResumeAmjad Khan
2.5K views4 slides
Curriculum Vitae (Muhammad Naveed)2 by
Curriculum Vitae (Muhammad Naveed)2Curriculum Vitae (Muhammad Naveed)2
Curriculum Vitae (Muhammad Naveed)2Muhammad Naveed
493 views3 slides
Cv yassine mohammadi 2 by
Cv yassine mohammadi 2Cv yassine mohammadi 2
Cv yassine mohammadi 2YASSINEMohammadi1
207 views1 slide
RESUME(MIS EXECUTIVE) by
RESUME(MIS EXECUTIVE)RESUME(MIS EXECUTIVE)
RESUME(MIS EXECUTIVE)Dharmendar singh
1.6K views2 slides
Modèles de lettre de motivation by
Modèles de lettre de motivationModèles de lettre de motivation
Modèles de lettre de motivationkawtarino
52.1K views5 slides
Sudarsh-Nanjappa-Reference-Letter-Ala-WMU by
Sudarsh-Nanjappa-Reference-Letter-Ala-WMUSudarsh-Nanjappa-Reference-Letter-Ala-WMU
Sudarsh-Nanjappa-Reference-Letter-Ala-WMUSudarsh Nanjappa
1.1K views1 slide

More Related Content

Similar to Database Sharding in Rails Applications – Vitalik Danchenko | Ruby Meditation #23

Databricks spark-knowledge-base-1 by
Databricks spark-knowledge-base-1Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1Rahul Kumar
727 views22 slides
Using ArcGIS Server with Ruby on Rails by
Using ArcGIS Server with Ruby on RailsUsing ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on RailsDave Bouwman
3K views98 slides
Otimizando Aplicações em Rails by
Otimizando Aplicações em RailsOtimizando Aplicações em Rails
Otimizando Aplicações em RailsJuan Maiz
474 views39 slides
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad... by
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Provectus
127 views63 slides
Mist - Serverless proxy to Apache Spark by
Mist - Serverless proxy to Apache SparkMist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache SparkВадим Челышов
139 views63 slides
Design Summit - Rails 4 Migration - Aaron Patterson by
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonManageIQ
762 views123 slides

Similar to Database Sharding in Rails Applications – Vitalik Danchenko | Ruby Meditation #23(20)

Databricks spark-knowledge-base-1 by Rahul Kumar
Databricks spark-knowledge-base-1Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1
Rahul Kumar727 views
Using ArcGIS Server with Ruby on Rails by Dave Bouwman
Using ArcGIS Server with Ruby on RailsUsing ArcGIS Server with Ruby on Rails
Using ArcGIS Server with Ruby on Rails
Dave Bouwman3K views
Otimizando Aplicações em Rails by Juan Maiz
Otimizando Aplicações em RailsOtimizando Aplicações em Rails
Otimizando Aplicações em Rails
Juan Maiz474 views
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad... by Provectus
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Provectus127 views
Design Summit - Rails 4 Migration - Aaron Patterson by ManageIQ
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron Patterson
ManageIQ762 views
M|18 How MariaDB Server Scales with Spider by MariaDB plc
M|18 How MariaDB Server Scales with SpiderM|18 How MariaDB Server Scales with Spider
M|18 How MariaDB Server Scales with Spider
MariaDB plc2.2K views
Quick Guide to Refresh Spark skills by Ravindra kumar
Quick Guide to Refresh Spark skillsQuick Guide to Refresh Spark skills
Quick Guide to Refresh Spark skills
Ravindra kumar220 views
Connecting the Worlds of Java and Ruby with JRuby by Nick Sieger
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
Nick Sieger4.2K views
Spark streaming by Noam Shaish
Spark streamingSpark streaming
Spark streaming
Noam Shaish1.3K views
Sinatra and JSONQuery Web Service by vvatikiotis
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
vvatikiotis1.9K views
Introduction To Ruby On Rails by Steve Keener
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On Rails
Steve Keener1.1K views
Leveraging a distributed architecture to your advantage by Michelangelo van Dam
Leveraging a distributed architecture to your advantageLeveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantage
Rails MVC by Sergiy Koshovyi by Pivorak MeetUp
Rails MVC by Sergiy KoshovyiRails MVC by Sergiy Koshovyi
Rails MVC by Sergiy Koshovyi
Pivorak MeetUp236 views
Developing node-mdb: a Node.js - based clone of SimpleDB by Rob Tweed
Developing node-mdb: a Node.js - based clone of SimpleDBDeveloping node-mdb: a Node.js - based clone of SimpleDB
Developing node-mdb: a Node.js - based clone of SimpleDB
Rob Tweed1.9K views
Buildingplatforms by codebits
BuildingplatformsBuildingplatforms
Buildingplatforms
codebits537 views
Introduction to cloudforecast by Masahiro Nagano
Introduction to cloudforecastIntroduction to cloudforecast
Introduction to cloudforecast
Masahiro Nagano1.6K views

More from Ruby Meditation

Is this Legacy or Revenant Code? - Sergey Sergyenko | Ruby Meditation 30 by
Is this Legacy or Revenant Code? - Sergey Sergyenko  | Ruby Meditation 30Is this Legacy or Revenant Code? - Sergey Sergyenko  | Ruby Meditation 30
Is this Legacy or Revenant Code? - Sergey Sergyenko | Ruby Meditation 30Ruby Meditation
207 views22 slides
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky... by
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...Ruby Meditation
462 views141 slides
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29 by
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29Ruby Meditation
210 views49 slides
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ... by
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Ruby Meditation
1.6K views59 slides
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28 by
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28 How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28 Ruby Meditation
366 views23 slides
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28 by
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28Ruby Meditation
459 views20 slides

More from Ruby Meditation(20)

Is this Legacy or Revenant Code? - Sergey Sergyenko | Ruby Meditation 30 by Ruby Meditation
Is this Legacy or Revenant Code? - Sergey Sergyenko  | Ruby Meditation 30Is this Legacy or Revenant Code? - Sergey Sergyenko  | Ruby Meditation 30
Is this Legacy or Revenant Code? - Sergey Sergyenko | Ruby Meditation 30
Ruby Meditation207 views
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky... by Ruby Meditation
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...
Life with GraphQL API: good practices and unresolved issues - Roman Dubrovsky...
Ruby Meditation462 views
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29 by Ruby Meditation
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29
Where is your license, dude? - Viacheslav Miroshnychenko | Ruby Meditation 29
Ruby Meditation210 views
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ... by Ruby Meditation
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Ruby Meditation1.6K views
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28 by Ruby Meditation
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28 How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28
How to cook Rabbit on Production - Bohdan Parshentsev | Ruby Meditation 28
Ruby Meditation366 views
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28 by Ruby Meditation
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
How to cook Rabbit on Production - Serhiy Nazarov | Ruby Meditation 28
Ruby Meditation459 views
Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh... by Ruby Meditation
Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh...Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh...
Reinventing the wheel - why do it and how to feel good about it - Julik Tarkh...
Ruby Meditation462 views
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby... by Ruby Meditation
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Ruby Meditation475 views
Use cases for Serverless Technologies - Ruslan Tolstov (RUS) | Ruby Meditatio... by Ruby Meditation
Use cases for Serverless Technologies - Ruslan Tolstov (RUS) | Ruby Meditatio...Use cases for Serverless Technologies - Ruslan Tolstov (RUS) | Ruby Meditatio...
Use cases for Serverless Technologies - Ruslan Tolstov (RUS) | Ruby Meditatio...
Ruby Meditation320 views
The Trailblazer Ride from the If Jungle into a Civilised Railway Station - Or... by Ruby Meditation
The Trailblazer Ride from the If Jungle into a Civilised Railway Station - Or...The Trailblazer Ride from the If Jungle into a Civilised Railway Station - Or...
The Trailblazer Ride from the If Jungle into a Civilised Railway Station - Or...
Ruby Meditation285 views
What/How to do with GraphQL? - Valentyn Ostakh (ENG) | Ruby Meditation 27 by Ruby Meditation
What/How to do with GraphQL? - Valentyn Ostakh (ENG) | Ruby Meditation 27What/How to do with GraphQL? - Valentyn Ostakh (ENG) | Ruby Meditation 27
What/How to do with GraphQL? - Valentyn Ostakh (ENG) | Ruby Meditation 27
Ruby Meditation1.1K views
New features in Rails 6 - Nihad Abbasov (RUS) | Ruby Meditation 26 by Ruby Meditation
New features in Rails 6 -  Nihad Abbasov (RUS) | Ruby Meditation 26New features in Rails 6 -  Nihad Abbasov (RUS) | Ruby Meditation 26
New features in Rails 6 - Nihad Abbasov (RUS) | Ruby Meditation 26
Ruby Meditation577 views
Security Scanning Overview - Tetiana Chupryna (RUS) | Ruby Meditation 26 by Ruby Meditation
Security Scanning Overview - Tetiana Chupryna (RUS) | Ruby Meditation 26Security Scanning Overview - Tetiana Chupryna (RUS) | Ruby Meditation 26
Security Scanning Overview - Tetiana Chupryna (RUS) | Ruby Meditation 26
Ruby Meditation299 views
Teach your application eloquence. Logs, metrics, traces - Dmytro Shapovalov (... by Ruby Meditation
Teach your application eloquence. Logs, metrics, traces - Dmytro Shapovalov (...Teach your application eloquence. Logs, metrics, traces - Dmytro Shapovalov (...
Teach your application eloquence. Logs, metrics, traces - Dmytro Shapovalov (...
Ruby Meditation455 views
Best practices. Exploring - Ike Kurghinyan (RUS) | Ruby Meditation 26 by Ruby Meditation
Best practices. Exploring - Ike Kurghinyan (RUS) | Ruby Meditation 26Best practices. Exploring - Ike Kurghinyan (RUS) | Ruby Meditation 26
Best practices. Exploring - Ike Kurghinyan (RUS) | Ruby Meditation 26
Ruby Meditation204 views
Road to A/B testing - Alexey Vasiliev (ENG) | Ruby Meditation 25 by Ruby Meditation
Road to A/B testing - Alexey Vasiliev (ENG) | Ruby Meditation 25Road to A/B testing - Alexey Vasiliev (ENG) | Ruby Meditation 25
Road to A/B testing - Alexey Vasiliev (ENG) | Ruby Meditation 25
Ruby Meditation577 views
Concurrency in production. Real life example - Dmytro Herasymuk | Ruby Medita... by Ruby Meditation
Concurrency in production. Real life example - Dmytro Herasymuk | Ruby Medita...Concurrency in production. Real life example - Dmytro Herasymuk | Ruby Medita...
Concurrency in production. Real life example - Dmytro Herasymuk | Ruby Medita...
Ruby Meditation511 views
Data encryption for Ruby web applications - Dmytro Shapovalov (RUS) | Ruby Me... by Ruby Meditation
Data encryption for Ruby web applications - Dmytro Shapovalov (RUS) | Ruby Me...Data encryption for Ruby web applications - Dmytro Shapovalov (RUS) | Ruby Me...
Data encryption for Ruby web applications - Dmytro Shapovalov (RUS) | Ruby Me...
Ruby Meditation299 views
Rails App performance at the limit - Bogdan Gusiev by Ruby Meditation
Rails App performance at the limit - Bogdan GusievRails App performance at the limit - Bogdan Gusiev
Rails App performance at the limit - Bogdan Gusiev
Ruby Meditation418 views
GDPR. Next Y2K in 2018? - Anton Tkachov | Ruby Meditation #23 by Ruby Meditation
GDPR. Next Y2K in 2018? - Anton Tkachov | Ruby Meditation #23GDPR. Next Y2K in 2018? - Anton Tkachov | Ruby Meditation #23
GDPR. Next Y2K in 2018? - Anton Tkachov | Ruby Meditation #23
Ruby Meditation179 views

Recently uploaded

The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
80 views25 slides
Zero to Automated in Under a Year by
Zero to Automated in Under a YearZero to Automated in Under a Year
Zero to Automated in Under a YearNetwork Automation Forum
15 views23 slides
Voice Logger - Telephony Integration Solution at Aegis by
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at AegisNirmal Sharma
39 views1 slide
Five Things You SHOULD Know About Postman by
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About PostmanPostman
33 views43 slides
Design Driven Network Assurance by
Design Driven Network AssuranceDesign Driven Network Assurance
Design Driven Network AssuranceNetwork Automation Forum
15 views42 slides
Future of AR - Facebook Presentation by
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentationssuserb54b561
14 views27 slides

Recently uploaded(20)

Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma39 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman33 views
Future of AR - Facebook Presentation by ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56114 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi127 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10248 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely21 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker37 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views

Database Sharding in Rails Applications – Vitalik Danchenko | Ruby Meditation #23

  • 1. DATABASE SHARDING IN RAILS APPLICATIONS RUBY MEDITATION #23 September 2018
  • 2. Work: @Talkable Ruby: since 2012 Rails: since v3.2 Open Source: about 0 contributions @justmacc @vitalikdanchenko ABOUT ME
  • 4. Hobby: Running Marathon Finisher: 4 times Marathon PB: 3:05:10 ABOUT ME
  • 5. A LITTLE BIT ABOUT SCALING DATABASE SHARDING A LOT OF DIAGRAMS ALMOST NO CODE AGENDA
  • 8. — @busterarm at Hacker News "TWITTER SCALE" WASN'T SO MUCH A RUBY/RAILS PROBLEM AS IT WAS AN RDBMS ” “ https://news.ycombinator.com/item?id=17217210 CAN RAILS SCALE?
  • 24. FUNCTIONAL EXPRESSIONAL METADATA Separate Modules id % N year country row -> shard DATABASE SHARDING
  • 26. DATABASE SHARDING IN RAILS MULTIPLE DATABASES MODEL 1 class ShardedBase < ActiveRecord::Base 2 establish_connection SHARD_DB_CONFIG 3 self.abstract_class = true 4 end 5 6 class Post < ShardedBase 7 end 8 9 class Comment < ShardedBase 10 end
  • 27. DATABASE SHARDING IN RAILS GEMS • thiagopradi/octopus • hsgubert/rails-sharding • zendesk/active_record_shards 1 ActiveRecord::Base.on_shard(:number_two) do 2 Post.find_by(author: author) 3 end
  • 28. DATABASE SHARDING IN TALKABLE STEP BY STEP
  • 29. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard?
  • 30. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? BY CUSTOMER
  • 31. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata
  • 32. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded?
  • 33. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? THE LARGEST
  • 34. DATABASE SHARDING IN TALKABLE STEP BY STEP 1 class Visitor < ShardedRecord 2 has_many :purchases 3 end 4 5 class Purchase < ShardedRecord 6 belongs_to :person 7 has_one :referral 8 end 9 10 class Referral < ShardedRecord 11 has_many :rewards 12 end 13 14 class Reward < ShardedRecord 15 belongs_to :incentive 16 end
  • 35. DATABASE SHARDING IN TALKABLE STEP BY STEP DATABASE NOT SHARDED CONFIG DATA DATABASE SHARD #1 REFERRAL DATA DATABASE SHARD #2 REFERRAL DATA
  • 36. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins
  • 37. 1 module ShardingJoinFinder 2 TABLE_REFERENCE = /(^|s+)(join|from)s+`?([a-z_]+)`?/i 3 4 def execute(query, name = nil) 5 ensure_sharding_match(query) 6 super(query, name) 7 end 8 9 def select_all(query, *args) 10 ensure_sharding_match(query) 11 super 12 end 13 14 def ensure_sharding_match(query) 15 query.scan(TABLE_REFERENCE).map(&:last) 16 sharded, unsharded = klasses.partition(&:is_sharded?) 17 raise Error if sharded.any? && unsharded.any? 18 end 19 end 20 21 ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend(ShardingJ 22 ActiveRecord::Relation.prepend(ShardingJoinFinder)
  • 38. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector
  • 39. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management
  • 40. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management — gem
  • 41. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management — gem 5. Add utility helpers
  • 42. 1 class DatabaseUtils 2 class SlaveError < StandardError; end 3 4 class << self 5 def use_shard(shard, &block); end 6 def current_shard; end 7 def uses_slave?; end 8 def config_for(slave: uses_slave?, shard: current_shard); end 9 def connection(slave: uses_slave?, shard: current_shard); end 10 def sharded_tables; end 11 def on_all_shards(&block); end 12 def processlist; end 13 def slave_lag_for(connection); end 14 end 15 end 1 Rails.application.console do 2 def shard(shard) 3 shard = shard.database_shard if shard.respond_to?(:database_shard) 4 DatabaseUtils.use_shard!(shard) 5 end 6 end
  • 43. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management — gem 5. Add utility helpers — depends on individual needs
  • 44. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management — gem 5. Add utility helpers — depends on individual needs 6. Migrate
  • 45. 1 production: 2 host: 'master.production.com' 3 database: 'primary' 4 slave: 5 host: 'slave.production.com' 6 database: 'primary' 7 8 shards: 9 1: 10 host: 'master.production.com' 11 database: 'shard_1' 12 slave: 13 host: 'slave.production.com' 14 database: 'shard_1' 15 2: 16 host: 'shard_2.production.com' 17 database: 'shard_2' 18 slave: 19 host: 'slave.shard_2.production.com' 20 database: 'shard_2'
  • 46. 1 production: 2 host: 'master.production.com' 3 database: 'primary' 4 slave: 5 host: 'slave.production.com' 6 database: 'primary' 7 8 shards: 9 1: 10 host: 'shard1.production.com' 11 database: 'shard_1' 12 slave: 13 host: 'slave.shard_1.production.com' 14 database: 'shard_1' 15 2: 16 host: 'shard_2.production.com' 17 database: 'shard_2' 18 slave: 19 host: 'slave.shard_2.production.com' 20 database: 'shard_2'
  • 47. DATABASE SHARDING IN TALKABLE STEP BY STEP 1. How to shard? — expressional + metadata 2. Which tables have to be sharded? — config vs referral 3. Get rid of joins — joins detector 4. Introduce connection management — gem 5. Add utility helpers — depends on individual needs 6. Migrate — profit!!!
  • 48. MySQL PostgreSQL Vites Citus Jetpants ??? ScaleBase DATABASE SHARDING SOLUTIONS
  • 49. PROS CONS Easier to Manage Not Easy to Implement Smaller and Faster Lost Abilities Reduces Costs DATABASE SHARDING CONCLUSION
  • 50. DATABASE SHARDING CONCLUSION • Do not shard your data until you really need it • Choose a sharding model that fits your context (project) • Each additional shard increases the chance of a random crash
  • 51. When: 08:00 am Where: 46°28'44.5"N 30°45'41.0"E How far: doesn’t matter How fast: doesn’t matter SUNDAY MORNING RUN
  • 52. Q&A