Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Data Migration with Confidence
Search
Juanito Fatas
June 22, 2017
Programming
3
860
Data Migration with Confidence
At RedDotRubyConf 2017
Juanito Fatas
June 22, 2017
Tweet
Share
More Decks by Juanito Fatas
See All by Juanito Fatas
My Open Source Journey
juanitofatas
1
3k
NSDanger
juanitofatas
1
160
How to build deppbot
juanitofatas
3
550
Introducing Danger
juanitofatas
0
280
Twemoji 3.0 in the making and announcement beyond SG50
juanitofatas
0
640
Continuous Updates
juanitofatas
0
120
Ruby Asia and dat bacon cannon
juanitofatas
1
230
Update Early, Update Often
juanitofatas
1
1k
RSpec for Practical Rubyist
juanitofatas
11
770
Other Decks in Programming
See All in Programming
HTML/CSS超絶浅い説明
yuki0329
0
180
PHPで学ぶプログラミングの教訓 / Lessons in Programming Learned through PHP
nrslib
4
1k
各クラウドサービスにおける.NETの対応と見解
ymd65536
0
240
2025.01.17_Sansan × DMM.swift
riofujimon
1
250
Итераторы в Go 1.23: зачем они нужны, как использовать, и насколько они быстрые?
lamodatech
0
1.3k
PHPとAPI Platformで作る本格的なWeb APIアプリケーション(入門編) / phpcon 2024 Intro to API Platform
ttskch
0
370
ドメインイベント増えすぎ問題
h0r15h0
2
550
Monixと常駐プログラムの勘どころ / Scalaわいわい勉強会 #4
stoneream
0
340
return文におけるstd::moveについて
onihusube
1
1.4k
歴史と現在から考えるスケーラブルなソフトウェア開発のプラクティス
i10416
0
290
CQRS+ES の力を使って効果を感じる / Feel the effects of using the power of CQRS+ES
seike460
PRO
0
230
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
750
Featured
See All Featured
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
Building Applications with DynamoDB
mza
92
6.1k
Code Reviewing Like a Champion
maltzj
521
39k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
8
1.2k
Why Our Code Smells
bkeepers
PRO
335
57k
Become a Pro
speakerdeck
PRO
26
5.1k
Done Done
chrislema
182
16k
jQuery: Nuts, Bolts and Bling
dougneiner
62
7.6k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
113
50k
A Modern Web Designer's Workflow
chriscoyier
693
190k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
7
560
Transcript
Data Migration with Confidence Juanito Fatas RedDotRubyConf 2017
@JuanitoFatas Ramen Specialist
Spanish name From Taiwan Live in Tokyo
I became a salaryman #
Cookpad Global Cookpad Japan
Made in Japan $
Reserve for local jokes %
Data Migration?
Schema Migration Data Migration
Schema Migration Alter Schemas over time https://en.wikipedia.org/wiki/Schema_migration
Data Migration https://en.wikipedia.org/wiki/Data_migration Transfer data from to A System B
System
Existing Data Migration
None
Data Migration to Existing System
Data Migration with Confidence @JuanitoFatas Specialist of cookpad RedDotRubyConf 2017
Why Migration?
Rewrote for Clients
New Partner joins company
Data Migration
~ Get All Data to our system Simple Goal
~ Import data Modeling Migrate After migrate
~ Get the Data Provider API Data Dump
Provider API & Generic Migration Code ✅
Data Dump & Generic Migration Code
HOWTO Data Migration
~ Start with a rake task
~
~ lib/tasks/data_migration.rake
~ lib/data_migration.rb
~ Import dump to local
~ GBs-size file
monthly users 62 30M countries ~
~ Add delay to the SQL dump for production
~ Add sleep() before INSERT INTO
~ Editing huge file
~ +
~
~ Enumerable#lazy https://ruby-doc.org/core-2.4.1/Enumerable.html#method-i-lazy
~
~
~ set accordingly for staging & production
~ Modeling Database
~
~ With these 5 methods, you can model anything.
~ Map data to your current system
~ Sometimes as easy as
~ As HTML in the recipes table field ‘steps’ ,
Sometimes…
~
~
~ Setup Test Suite
~
~
~ - Why Tests? The migration code only used once
~ Better code through boring tests
~ TDD to Get Things Done
~ Modeling Tests Repeat
Migration
~ Use all methods that raises exception
~ Fail Fast to find all errors
~ Example Migrate Recipes
~
~
None
~
~ Add more migrators to migrate
~ Data Integrity
~ Transaction
~ Idempotent Operation
~
~ Run Migration many times
~ Produce the Same Result
~ f(x) = f(x)
~ Upsert Update or Insert
~ MySQL ON DUPLICATE KEY UPDATE PostgreSQL ON CONFLICT UPDATE
PostgreSQL 9.5+ seamusabshere/upsert
~
~ Data Accuracy
~ Manually Check
~ Automated Check
~ Example Check users with most Recipes
~
~
~
~
~
~ To check more things Add more Checker objects
~ Use many small objects to compose
~ Objects Everywhere
For better object design
For better object design
Background Jobs
Workers = CPU cores
Designated Queues
None
None
Log Every Unexpected Error
None
None
For Better handling of Errors
Run against all data to be migrated
Fix every error you can before real migration
~ Tools
Retry mechanism
Foreign Key Constraints Locks
MySQL deadlock Results in
Automatic Retry # Rails 4: ActiveRecord::StatementInvalid
Make sure what should be Retry
retry_on discard_on ActiveJob::Exceptions
Automatic Retry
Examine & Retry
In Resque
None
Status Reporting
None
None
Report every minute
Monitoring CPU Usage
None
~ Performance
Performance is a Rabbit hole
Preload associations
Minimize scope of transaction
Transaction Isolation Levels https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html https://www.postgresql.org/docs/current/static/transaction-iso.html
Avoid unnecessary callbacks
None
Example You can touch http://api.rubyonrails.org/classes/ActiveRecord/NoTouching/ClassMethods.html#method-i-no_touching after migration
Process multiple records in one job
None
Cache data in Memory
Cache data in Redis
Migrate Important things first
First 10000 users w/ most recipes
IO bound
Scale up the Database
Decrease the workers /0
Bulk Insert Bulk Upsert* * Only MySQL supports bulk upsert
zdennis/activerecord-import
Every change to make it fast
Run the WHOLE migration again
Keep CPU usage max at 75% all
~ Post Migration
Update all necessities
Redirects
Redirect tables Cookpad Redirect programs Server redirects Provider
Redirection Service cookpad/mirin
~ Stories
Cases of Email
Remove duplicate emails before migration
Remove invalid emails before migration
downcase all the emails
~ Get Site Dump
~ 100GB generated on EC2* EC2 has bandwidth limits
~ scp takes days ONLY if nothing failed within days
~ delivers encrypted disk
Migrate Millions of records
AR + transaction bulk in/upsert activerecord-import load data in file
Weeks Month-ish
Run low priority job to migrate them
When migrated User signed in
Migrate their data in high priority
None
Migrate 100K photos
How our image work
Design so it produces the same hash 4
Set the designated hash during migration instead of upload, generate
hash
Benchmark how long to finish all
X days?
Migrate them X days before in low priority
99% photos won’t change
Migrate users password to secure auth
Figure out what algorithm(s) was(ere) used
When migrated user signed in
System’s password auth will fail
Fallback to Legacy Auth
None
When password matched from legacy auth
Set his password through secure password scheme
None
Migration ~ The Future
Migration done in Ghost Table fashion
Data Dump & Generic Migration Code Only need to modeling
database
~ Takeaways
Rails provides sharp tools thanks to rails core team
Use Small objects to make your code more readable &
maintainable
Abstraction is the God of Programming! “ ” — Matthew
Mongeau @halogenandtoast
Schedule >> Fast
Schedule >> Fast Integrity >> schedule
Data Migration sounds hard
Keep it Simple Made it Easy
Do the Simplest Things “ ” — Winston Teo Yon
Wei @winstonyw
Enjoy ☕ Thank you!