惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园 - 司徒正美
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cyberwarzone
Cyberwarzone
小众软件
小众软件
T
Threatpost
Latest news
Latest news
J
Java Code Geeks
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
P
Privacy & Cybersecurity Law Blog
T
Tenable Blog
L
Lohrmann on Cybersecurity
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
S
Schneier on Security
T
The Blog of Author Tim Ferriss
V
V2EX
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
罗磊的独立博客
IT之家
IT之家
雷峰网
雷峰网
H
Help Net Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
C
Cybersecurity and Infrastructure Security Agency CISA
I
InfoQ
GbyAI
GbyAI
博客园 - 叶小钗
PCI Perspectives
PCI Perspectives
The GitHub Blog
The GitHub Blog
Martin Fowler
Martin Fowler
H
Heimdal Security Blog
Spread Privacy
Spread Privacy
博客园_首页
A
About on SuperTechFans
T
Tailwind CSS Blog
The Register - Security
The Register - Security

Nic Lin's Blog

謝明真 - 高效領導力的課後筆記 NFT 開發實戰!基礎智能合約入門 (3) NFT 開發實戰!基礎智能合約入門 (2) NFT 開發實戰!基礎智能合約入門 (1) 如何自我檢測 log4j CVE 漏洞 Rails 如何在資料寫入時記錄來源 IP 位置 如何經營工程師 Youtube 頻道 - Part 8 營收篇 如何經營工程師 Youtube 頻道 - Part 7 酸民文化篇 如何經營工程師 Youtube 頻道 - Part 5 設備器材篇 如何經營工程師 Youtube 頻道 - Part 4 後製剪輯篇 如何經營工程師 Youtube 頻道 - Part 3 文案企劃篇 如何經營工程師 Youtube 頻道 - Part 2 設備器材篇 如何經營工程師 Youtube 頻道 - Part 1 制訂頻道方向篇 如何經營工程師 Youtube 頻道 - Part 0 Rails 中避免 race condition 的最佳實踐(二) Rails 中避免 race condition 的最佳實踐(一) 10 分鐘整合 google sheet 做自動化開發功能週報 經營 Side Project 300 天所帶來的收穫及挑戰 我的 Youtube 影片製作流程 API 設計時必須注意的 HTTP header 底線問題 如何提升你的程式可讀性之實務技巧(三) 如何提升你的程式可讀性之實務技巧(二) 如何提升你的程式可讀性之實務技巧(一) Ruby 中使用 freeze 優化效能的時機 避免 React 中的 useEffect 無限 render 在 Rails 內輕量使用 Vue Component 的最佳實踐 如何在區域網路用 Docker 架設有 SSL 的 Gitlab 從被問到問人,那些我常問的面試問題 [Rails] 如何漂亮寫出可維護的 query (Maintainable Rails Query) 在已知長度情況下優化 slice 的性能 [ReactNative] 如何在 iOS APP 上主動要求用戶評分 Rails 的 scope 為什麼用 lambda? Proc 與 lambda 不同之處 淺談 Active Record 的 Lazy load 特性 Rails 專案搭配 Github Actions 進行 RSpec 自動化測試 JavaScript 中 require, import 的差別及效能 React 效能優化基本招 ES6 箭頭函式 (Arrow functions) 2 個月擁有 6000 用戶 Side project 這樣做(一) 如何讓自己成為失敗的軟體工程師 如何用 Rack::Attack 阻擋 DDOS / 惡意流量 用 OpenSSL 自簽開發用 HTTPS SSL 憑證 為機器加上登入訊息,在 ubuntu 設置登入歡迎詞 Ruby Memoization 性能優化之記憶化 淺談 SSH agent forwarding 和 proxy command 的安全風險與應用 [Rails] Service / Library / Concern 的差異 避免過度的 Defensive Programming 防禦性程式設計 1:1 攪亂器,如何用 Ruby 做可逆推序號 Rails 中的欄位及方法命名原則 [Rails] 用 puma-dev 作為本地開發伺服器 (支援 https 自簽憑證) 將 Rails 專案從手動部屬遷移使用 Capistrano 自動化部屬 工程師提昇自己的教學和簡報技術的方法 [筆記] Rails 3.2 升級 Rails 6.beta 經驗分享 Class method 氾濫帶來什麼問題 RDBMS 課程心得與筆記 常用的 Rails 開發規範 Rest-Client 如何做 Basic Authentication 驗證 [Rails] 何為 tld_lebgth? 遵循 Semantic Versioning 軟體開發語意化版本管理 請直接在 MySQL 裡面直接用 utf8mb4 取代 utf8 如何解決在 awesome print 中遇到 ActionController::Parameters unable to convert unpermitted 如何在 Mac 上升級 PostgreSQL 並遷移資料 如何解決 Mysql2::Error: Incorrect string value 讀書心得 - 「信任因子:信任如何影響大腦運作、激勵員工、達到組織目標」 我是如何寫部落格筆記的 讀書心得 - 「先問,為什麼?:顛覆慣性思考的黃金圈理論,啟動你的感召領導力」 [Rails] 解決 Reset Password 帶來的 token 洩漏問題 我的軟體工程師生涯:如何挑選適合你的公司 Rails 中的 delegate 用法 淺述 SSR SPA 優缺點 Rails 非同步工作請用 Global ID [React] Class Component 傳遞 props 的 2 種方式 好用的隱私權政策 URL 自動生成 Rails 5.1 之後的 tag helper Rails 5.2 Encrypted Credentials 最近面試被給的建議和書單 一般架構需要用到 K8S 嗎 透過 commit SHA 找 github Pull request 從零搭建,如何讓 Rails 跑在 Kubernetes(k8s)(二) React Stateless Functional Components 搞懂 React 中的 state 和 props 物件導向基本原則 SOLID (Ruby Sample) 在以太坊智能合約上是可以預測隨機數的 在台灣租屋必須注意的事 Rails 5 簡單雙向加解密 如何用 ABA 培養自律型員工 不要在 rake task 中定義 method, 請用 RAKE::DSL rails 非hash只想用array輸出page 如何處理陣列裡有重複的值 [Rails] 如何重設你的專案名稱 Ruby on Rails install on Mac 安裝步驟 使用 Friendly_id 與 Babosa 美化你的Rails 網址 Junior Rails 兩個月實戰心得 Devise使用Google實作登入 [iterm2] 如何新增alias 一個新鮮人找尋Rails工作的面試經驗 如何讓兩個資料表建立關聯 routing 的 namespace strong parameter user story 的格式 user story 是什麼?
不停機 migration 避免鎖表的幾種操作
Nic Lin · 2019-08-10 · via Nic Lin's Blog

基本上在商業應用中,我們會盡可能的避免停機操作,試想光 CloudFlare 因為 bad deploy 當機幾分鐘至一個小時就會引發一連串的災難,在商場上每分每秒都是錢,為了避免不必要的損失,軟體工程常常會面臨到所謂的 zero downtime 操作。

但像資料庫的結構設計不可能一開始就符合大型架構,所以這過程通常都是不停的升級遷移,才有了符合現在設計的樣貌,所以不可避免的停機還是會發生的,通常幾個原因

  1. 應用程式的 code 不能同時兼容 migration 前 / 後的資料庫
  2. 因為資料量大,在跑 migration 時造成的長時間鎖表

讓程式碼能夠對應 migration 前 / 後的資料庫

通常步驟會是分好幾次部署,確保是兼容運行

  1. 讓程式碼能夠同時對應新的作法及舊的作法
  2. 進行 migrate
  3. 刪除為了向下兼容的作法

舉例來說,要刪除 table 中的 column 時

class RemoveStatusFromUsers < ActiveRecord::Migration
  def change
    remove_column :users, :status, :string
  end
end

在刪除前通常會確定 code 裡面已經沒有用到,是個作廢的欄位,但要注意的是 ActiveRecord 會在 rails 啟動時先緩存所有的 column,也就是說

當你正在刪除 column 時,如果有人要執行類似 user.save ,其實是會噴錯的

ERROR: column "status" does not exist

但通常跑完 migration 時也會重新啟動 rails server 所以這問題比較少發生,但如果是併發比較高的應用,可能要避免這種事情發生

可以先到 User model 裡面加上

# For Rails 5+
class User < ApplicationRecord
  self.ignored_columns = ["status"]
end

# For Rails < 5
class User < ActiveRecord::Base
  def self.columns
    super.reject { |c| c.name == "status" }
  end
end

這時候在去跑 migration,就可以避免上述的情況發生,然後再確保 migration 順利運行完後,將這個為了向下兼容的 code 刪除,就完成了 zero downtime migration 的操作了

跑 migration 時造成的長時間鎖表

先來看一下常見的 19 種操作(來自 2015 的 paper 整理,可以看文章底部的參考來源)

ScenariosMySQL 5.5MySQL 5.6PostgreSQL 9.3PostgreSQL 9.4
Adding a non-nullable columnRead-OnlyNon-BlockingBlockingBlocking
Adding a nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Renaming a non-nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Renaming a nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Dropping a non-nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Dropping a nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Modifying the data type of a non-nullable columnN/AN/ANon-BlockingNon-Blocking
Modifying the data type of a nullable columnN/AN/ANon-BlockingNon-Blocking
Modifying the data type of a non-nullable column from integer to textN/AN/ABlockingBlocking
Making a non-nullable column nullableRead-OnlyRead-OnlyNon-BlockingNon-Blocking
Making a nullable column non-nullableRead-OnlyRead-OnlyBlockingBlocking
Modifying the default value of a non-nullable columnNon-BlockingNon-BlockingNon-BlockingNon-Blocking
Modifying the default value of a nullable columnNon-BlockingNon-BlockingNon-BlockingNon-Blocking
Creating a foreign key constraint on a non-nullable columnRead-OnlyRead-OnlyBlockingBlocking
Creating a foreign key constraint on a nullable columnRead-OnlyRead-OnlyBlockingBlocking
Creating an index on an existing non-nullable columnRead-OnlyNon-BlockingNon-BlockingNon-Blocking
Renaming an existing indexN/AN/ANon-BlockingBlocking
Dropping an existing indexBlockingNon-BlockingNon-BlockingNon-Blocking
Renaming an existing tableNon-BlockingNon-BlockingNon-BlockingNon-Blocking

以 PostgreSQL 來說,常見的鎖表操作

  • 增加 not null column 或是 default 值不為空的 column
  • 改變 column type
  • 增加或是重命名 index
  • 增加 foreign key / 限制

增加 not null column 或是 default 值不為空的 column

如果直接新增一個欄位在數據量較大的表上,會造成鎖表

add_column :users, :job_title, :string, default: "rails_developer"

所以我們可以拆幾個步驟去做

先增加 column,不要設置 default 值,再去設置 default 值可以避免鎖表

add_column :users, :job_title, :string
change_column_default :users, :job_title, "rails_developer"

但這裡要注意的是,如果資料庫裡面已經存在沒有 default 值的資料,需要額外寫一個 rake task 去補回

# Rails 5+
User.in_batches.where(job_title: nil).update_all(job_title: "rails_developer")

改變 column type

改變 type 會影響資料庫底層結構,所以通常都是鎖表,可以用比較安全的步驟進行更改

  1. 建立新的 column
  2. 將 code 設置同時寫新舊欄位
  3. 寫 task 把舊資料填到新欄位
  4. 開始用新的 column 讀資料
  5. 停止寫舊 column
  6. 完整的移除舊欄位

index 鎖表相關

打 index 請參考我之前寫過的另一篇文章 如何快速的對大資料量建立索引,避免 Downtime

避免 transaction 包在 migration 內

有些人習慣會把 migration 和 patch 資料一起做,例如

class AddPublishedToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :published, :boolean
    Post.unscoped.update_all(published: true)
  end
end

其實比較建議不要放在同一個 transaction 內

  1. migration 單獨跑 add_column
  2. 修改資料的請另外單獨寫一次性的 task
# migration
# db/migrate/xxxxxxxxx_add_published_to_posts
class AddPublishedToPosts < ActiveRecord::Migration
  def up
    add_column :posts, :published, :boolean
  end
end

# task
# lib/tasks/post.rake
namespace :post do
  task patch_post_published_column: :environment do
    Post.unscoped.update_all(published: true)
  end
end

小結

通常只修改幾個欄位大概都還可以用 zero downtime migration 的招去做

但如果是

  • 數據量龐大,只要鎖表就超久
  • 大量的欄位結構更改

建議還是有完整的計畫直接停機做比較好,畢竟 zero downtime 的作法通常都是 拆好幾個步驟去實現,當步驟一多就增加出錯的風險

這裡可以參考當初 airbnb 進行停機 migrate 的準備和作法 How We Partitioned Airbnb’s Main Database in Two Weeks

參考資源