優化 Rails效率 by Richard Schneeman


筆記整理自 My Server for Aiur: How Starcraft Taught Me To Scale by Richard Schneeman
 http://www.youtube.com/watch?v=4wvtvc0C2SY


1. Don't queue web requests

2. 監測 Database/language/GC哪一端拖垮效率

3. Measure in production

*N+1 query

*在 Production config中加入監測指令
config/production.rb

config.
active_record.
auto_explain_threshold_in_seconds =
1

4. Add indexes

*New Relic
*Scout

5. Cache Expensive query

*Memcache  [Building a Rails 3 Application with the Memcache Add-on]
*Rails.cache & Rails.cache.fetch("cache_key")
不要濫用

6. View Caching

cache最小單位
cache_digests gem  <--rails4

7. avoid premature optimization
incremental improvement
Fast day Friday <--focus on speed every Friday

8. Split up Web/Workers/Datastore
將Database/web server分在不同的機器
Workers用第三方機器,或者改用排程,在空檔進行
active_queue <--Rails 4

9. 不夠用的時候怎麼辦
Scale UP
Scale Out : Ephemeral Web machines  不在 Server儲存 State
$ heroku ps:scale web=6  
將state存在database/session/s3

10. Database怎麼 Scale

Master DB <-->Slave DBs
Split data to multiple DB machine
*Shared Data還是沒辦法 (facebook用MySQL, Instagram用 PostgreSQL)
建議閱讀: 7 databases in 7 weeks

11. Client side優化
JS, CSS:CDN,GZIP,縮小檔案大小
Content Distribution Network :Images/JS/CSS在各國 server
可使用 AkamaiCloudfront, 設定為
config/production.rb
config.action_controller.asset_host =
ENV["cloudfront_url"]

Browser caching
*Expires headers 把這些資訊在cache中保留久一點
config/production.rb
confib.static_cache_conrol=
"public, max-age=2593000"
*Rails assets fingerprints
config/production.rb
confib.assets.digest = true
建立MD5檔案
一般檔案: headers.css
有 fingerprint的檔案: headers.91234j12342341.css
Browser將會以新檔案對待

12. 總結
使用YSlow工具來測量前端表現 [Chrome , FireFox, 官網]
Don't block page parsing
Measure memcache, More-Instances!!



講者更多Rails教材: http://www.youtube.com/watch?feature=player_embedded&v=KDwElEeakuU

留言