All Revision Notes

COM6002 Big Data Management · Week 6

Distributed Database Systems

COM6002 · Week 6 · Source: 6-DDB.pptx (54 slides)

Contents · 16 sections

🎯 本講重點 (Learning outcomes)

  • Why distributed:data 的分佈性、Reliability & Availability、Scalability、Economic benefits;Location transparency
  • 三大 challenges:Security、Distributed Query Processing、Distributed Transaction Management
  • Fragmentation (Sharding):Horizontal / Vertical / Mixed;HF vs VF 的優點;Replication 的 benefits & costs
  • Distributed Query Processing 四步:Decomposition → Optimization & Localization → Local Execution → Result Reconstruction
  • Distributed 2PL:Centralized、Primary copy、Distributed (majority vote);distributed deadlock detection 的難處
  • Timestamp-based concurrency control:Wound-Wait、Wait-Die、Timestamp Ordering (T/O) + Thomas Write Rule、MVTO / MVCC
  • Raft consensus(leader / followers / heartbeat / majority)
  • CAP theorem(C in CAP ≠ C in ACID)、CA / CP / AP、BASE、NewSQL

⭐ 考試必溫 Top-5

  1. HF vs VF:定義、邊條 query 用邊種較好(slide 11 Q1 / Q2)、優點(UNION vs JOIN、data locality、security)
  2. 三種 distributed 2PL 的運作同 pros / cons(single point of failure、network congestion、message 數量、deadlock detection)
  3. Wound-Wait vs Wait-Die:規則(邊個 wait、邊個 rollback)、點解冇 deadlock、abort rate / abort cost 比較表
  4. T/O 的 Read / Write rules(RTS、WTS、Thomas Write Rule)同 MVTO 例題(slide 37–38 讀邊個 version、write 會唔會 abort)
  5. CAP theorem:三個定義、CA / CP / AP 例子(MongoDB write majority vs minimal write)、CAP 的 C vs ACID 的 C、BASE 三個字母

1. Why distributed?

Week 1 講過 Scale up(買更勁的一部機)同 Scale out(加多幾部機)。Distributed database 就係 scale out 用喺 database 上面。Slide 2 列出四個原因:

⭐ 考試重點:Why distributed?
原因Slide 原文解釋
Distributed Nature of DataData naturally resides where it is generated香港分行的交易喺香港產生、倫敦分行的喺倫敦產生;data 本身就係分散的
Increased Reliability and Availability (RA)Failure of one site does not halt the entire system;Data is replicated across multiple nodes一個 site 壞咗,其他 site 仍有 copy,系統照行
Improved Performance (Scalability)Queries can be executed in parallel across multiple sites;Processing closer to the data reduces network latency多部機 parallel 做 query;喺 data 附近處理,少咗 network 來回
Economic BenefitsConnect smaller, cheaper machines vs a single, monolithic mainframe好多部平機加埋,往往比一部超級 mainframe 更抵
🖼️ Slide 3 圖片

Dell HK 網站兩部 1U rack server(Premium Customization)嘅價錢:PowerEdge R450(3rd generation Intel Xeon Scalable processors)HK$232,835.61;PowerEdge R670(two-socket,high-performance computing)HK$362,304.46。一部 server 已經要二三十萬港幣,高階型號再貴五成幾,所以 scale up 好快就會好貴。

2. Distributed database system 與 Location transparency

Distributed database system:Host the database on multiple machines (nodes)。Goal:As if it were a single, centralized database,即係 user 用起上嚟要好似只得一個 database,唔使理 data 實際放喺邊部機。

Example concern:Location transparency,user 唔需要知道 data 喺邊個 location。Slide 4 的 idea:Map the domain name to different locations (IP addresses) depending on the requester's location。例如同一個 db.example.com,香港 user 解析到香港 node 的 IP,歐洲 user 解析到歐洲 node 的 IP(即 DNS-based routing)。User 只記一個名,系統自動帶佢去最近的 site。

3. Challenges

Designing, implementing, and maintaining distributed systems is inherently difficult。三大挑戰:

⭐ 考試重點:Three challenges
  • Security:Protecting data distributed across multiple sites and networks(多咗 site、多咗 network 傳輸 → 多咗攻擊點)
  • Distributed Query Processing:Minimizing network traffic while optimizing response time(見 Section 6)
  • Distributed Transaction Management:Ensuring ACID across network boundaries(見 Section 7–10)

4. Fragmentation and Replication

Fragmentation is also known as Sharding:Partitioning a table into smaller, non-overlapping subsets。設計時要決定:

  • What data to store(點樣切)
  • Where to store it(放喺邊個 site)
  • How many copies to keep(Replication,見 4.4)

4.1 Types of Fragmentation

⭐ 考試重點:HF / VF / Mixed
TypeDefinitionExample systems / notes
Horizontal Fragmentation (HF)Splitting a relation by rows (records)MongoDB, Google Spanner
Vertical Fragmentation (VF)Splitting a relation by columns (attributes)For RDBMS, this can be implemented at application level;Example:MonetDB
Mixed FragmentationApplying both horizontal and vertical fragmentationMost complex, most flexible

4.2 Example data(slides 8–10)

Table T(10 個 employees):

EmployeeIDNameDepartmentSalaryStartDateIsFullTime
101Alice JohnsonSales$60,0002022-08-15True
102Bob SmithMarketing$75,0002021-05-20True
103Charlie BrownEngineering$95,0002023-01-10True
104Diana PrinceHR$55,0002024-03-01False
105Ethan HuntEngineering$110,0002020-11-25True
106Fiona GlenanneSales$62,0002023-09-01False
107George CostanzaMarketing$70,0002022-04-12True
108Hannah BakerHR$58,0002024-01-20True
109Ian MalcolmEngineering$105,0002021-07-01True
110Jessica DaySales$59,0002023-05-18False

Horizontal Fragmentation(slide 9):按 rows 切開兩份。Fragment 1 = EmployeeID 101–105(EmployeeID≤105\text{EmployeeID} \le 105),Fragment 2 = 106–110(EmployeeID>105\text{EmployeeID} > 105)。每個 fragment 都有齊全部 6 個 columns。

Vertical Fragmentation(slide 10):按 columns 切開兩份。Fragment A = (EmployeeID, Name, Department, Salary),Fragment B = (EmployeeID, StartDate, IsFullTime)。每個 fragment 都有齊 10 個 rows。

⚠️ 易忽略

留意 VF 的兩個 fragments 都保留咗 EmployeeID。Primary key 一定要喺每個 vertical fragment 都出現,否則之後冇辦法用 JOIN 砌返原本的 table。所以 VF 的「non-overlapping」只係指非 key columns 唔重疊。

-- Horizontal fragmentation:按條件切 rows
CREATE TABLE T_site1 AS SELECT * FROM T WHERE EmployeeID <= 105;
CREATE TABLE T_site2 AS SELECT * FROM T WHERE EmployeeID > 105;
-- 重組:UNION(fragments 不重疊,用 UNION ALL 已足夠)
SELECT * FROM T_site1 UNION ALL SELECT * FROM T_site2;

-- Vertical fragmentation:按 columns 切,每份都要保留 key
CREATE TABLE T_A AS SELECT EmployeeID, Name, Department, Salary FROM T;
CREATE TABLE T_B AS SELECT EmployeeID, StartDate, IsFullTime FROM T;
-- 重組:JOIN on key
SELECT * FROM T_A JOIN T_B ON T_A.EmployeeID = T_B.EmployeeID;

4.3 Example queries:HF 定 VF 好?(slide 11)

⭐ 考試重點:揀 fragmentation 要睇 query
Query較好原因
Q1: SELECT * FROM T WHERE EmployeeID = 107HF要成條 record(所有 columns)。HF 下只需去 Site 2 一個地方攞一條完整 record;VF 下要去兩個 fragments 再 JOIN
Q2: SELECT COUNT(*) FROM T WHERE Salary > 50000VF只需要 Salary 一個 column。VF 下只讀 Fragment A(4 columns),唔使讀 StartDate、IsFullTime;HF 下兩個 site 都要掃全部 columns

(Q2 答案 = 10,因為全部人 salary 都 > 50,000。)

4.4 Comparisons:HF vs VF 優點(slide 12)

⭐ 考試重點:Advantages
Advantages of HFAdvantages of VF
High Data Locality:The entire record is stored in one (most frequently accessed) site。Example:account records in Hong Kong stored in HK databaseQueries only read the columns they need
Simpler Reconstruction:UNION (in HF) vs JOIN (in VF)Enhanced Security:Sensitive columns (e.g., salary) can be isolated to a high-security server
Easier to implement
Queries that target different sets of records can run in parallel across different sites
💡 直覺理解

UNION 只係將兩疊紙疊埋一齊,好平;JOIN 要逐條 record 配對 key,貴好多(Week 3/4 講過 JOIN 要 index 或 sort 先夠快)。所以 HF 重組簡單得多。VF 就似 column store(Week 5 的 VertiPaq 都係 column-based):analytics query 通常只睇幾個 columns,所以 VF 有著數。

4.5 Trade-offs of Replication(slide 13)

⭐ 考試重點:Replication benefits vs costs
BenefitsCosts
Availability:If one copy fails, others are availableUpdate Overhead:Every update must be propagated to all copies (increased network traffic)
Reduced Latency:Queries can access the closest copyConcurrency Control:Ensuring all copies remain mutually consistent is complex (Consistency vs. Availability)
Parallelism:Read queries can be executed in parallel
💡 直覺理解

Replication 對 read 有利(多個 copy 可揀最近、可 parallel),對 write 不利(要寫晒所有 copy、仲要保持一致)。所以 read-heavy 的 data 適合多 copy,write-heavy 的就要小心。「Consistency vs. Availability」呢個 tension 就係之後 CAP theorem 的伏筆(Section 12)。

5. Overview of Distributed Query Processing

Goal:Transform a high-level query (e.g., SQL) into a series of local operations and inter-site data transfers that minimize cost。

⭐ 考試重點

Dominant Cost Factor = Network communication (latency and volume) → 目標係 Minimize data transfer。喺單機 database,cost 主要係 disk I/O;喺 distributed database,傳 data 過 network 先係最貴的部分。

5.1 Steps of Distributed Query Processing(slide 15)

⭐ 考試重點:Four steps
  1. Query Decomposition:Translating the high-level query into local queries
  2. Distributed Optimization and Localization:Determine which specific site (fragment) holds the required data;Query transformation where appropriate
  3. Local Execution:Local DBMS at each site executes the localized sub-query on its fragment
  4. Result Reconstruction:Reconstruct the global result from local results

5.2 Example 1:WHERE EmployeeID = 107(slides 16–17)

用返 HF 例子:Site 1 放 EmployeeID≤105\text{EmployeeID} \le 105,Site 2 放 EmployeeID>105\text{EmployeeID} > 105。User 對住 global view(成個 T)落 query:

SELECT * FROM T WHERE EmployeeID = 107
  • Query Decomposition / Localization:107 > 105 → Only Site 2 is relevant,只將 query send 去 Site 2
  • Local Execution:Site 2 執行,得到 (107, George Costanza, Marketing, $70,000, 2022-04-12, True)
  • Result Reconstruction:Not necessary as there is only one local result
🖼️ Slide 16 圖片

Global view 分成兩個方塊:Site 1:EmployeeID <= 105、Site 2:EmployeeID > 105。右下角係上一頁嘅 "Horizontal Fragmentation Example" 縮圖:Site 1 有 101–105(Alice Johnson … Ethan Hunt),Site 2 有 106–110(Fiona Gleanne、George Costanza、Hannah Baker、Ian Malcolm、Jessica Day)。

5.3 Example 2:Sales 的 full-time 員工(slide 18)

SELECT Name, Salary FROM T
WHERE Department = 'Sales' AND IsFullTime = True
  • Query Decomposition:條件同 EmployeeID 無關,冇辦法排除任何 site → Send the query to both sites
  • Local Execution:Site 1 → (Alice Johnson, $60,000);Site 2 → Fiona(False)同 Jessica(False)都唔係 full-time → 空
  • Result Reconstruction:Use “Union” to get the final result → 只得 Alice Johnson, $60,000
💡 直覺理解

點樣切 fragment 會影響 query cost:WHERE 條件用到 fragmentation key(EmployeeID)就可以 prune 走無關的 site(Example 1);用其他 column 就要問晒所有 site(Example 2)。所以揀 shard key 時要睇最常用的 query 用邊個 column 做 filter。

6. Distributed transactions

Challenge:A transaction that involves data located at more than one site。Example:Transferring money between two accounts held at different sites(A 戶口喺 Site 1 扣錢、B 戶口喺 Site 2 加錢)。

Goal:Ensuring all sites agree on the outcome (commit or abort) despite network partitions or site failures。即係唔可以 Site 1 扣咗錢但 Site 2 冇加到(違反 Atomicity)。

7. Two-phase Locking (2PL) in distributed environment

Purpose:to achieve ACID in RDBMS。重溫 Week 3:growing phase 只攞 lock、shrinking phase 只放 lock;Readlock 之間 no conflict,涉及 Writelock 就 conflict。問題係:data 有幾個 copies 分散喺唔同 node,邊個負責批 lock? 三種做法:

⭐ 考試重點:Three variants
Variant邊個批 lock
Centralized 2PLOne site is designated as the central manager (for all data items)
Primary copy 2PLThere is a central manager for each data item;the central managers of different data items can be different(Stonebraker, Distributed Ingres, 1979)
Distributed 2PLMajority vote:Proceed when more than half of the nodes grant the lock(Bernstein & Goodman)

以下三個例子都用同一個 setting:transaction T1 = Read(x), Write(y);x 放喺 Node 1, 3, 7;y 放喺 Node 2, 5, 8。

(已對照 slides 21、23、25 嘅箭咀圖,下面步驟同圖一致。Slide 21:1 Readlock(x) 同 3 Writelock(y) 都指向 Centralized node;2 Read(x) 指向 Node 1;4 Write(y) 指向 Node 2、Node 5、Node 8。Slide 23:1 Readlock(x) 同 2 Read(x) 都指向 Node 3;3 Writelock(y) 指向 Node 8;4 Write(y) 指向 Node 8、Node 2、Node 5。Slide 25:1 Readlock(x) 指向 Node 3 同 Node 1;2 Read(x) 指向 Node 1;3 Writelock(y) 指向 Node 2 同 Node 5;4 Write(y) 指向 Node 8、Node 2、Node 5。)

7.1 Centralized 2PL(slides 21–22)

假設 Node 1 同 Node 2 最近 user,另有一個 Centralized node 做 lock manager:

  1. Readlock(x) → 問 Centralized node
  2. Read(x) → 去最近的 copy(Node 1)讀
  3. Writelock(y) → 問 Centralized node
  4. Write(y) → 寫晒 y 的所有 copies:Node 2, 5, 8(write 要更新所有 replicas)

Q: What is the read cost if no locking is required? 只需直接去最近的 Node 1 讀 x,一個來回就搞掂。呢種「先唔鎖,照做」的做法叫 optimistic concurrency control(Let's go without locking)。加咗 locking 就要多一程去 Centralized node。

⭐ 考試重點:Centralized 2PL analysis
ConsPros(compared to other 2PL methods)
  • Network congestion may happen at the centralized node
  • The scale is limited to the capability of the centralized node
  • Increased cost(network cost to the centralized node is higher than to the closest node)
  • Single point of failure:What if the centralized node is down?
  • Easy to detect deadlock(所有 lock 資訊都喺同一個 node,可以直接畫 wait-for graph)
  • Easiest to implement

7.2 Primary copy 2PL(slides 23–24)

x 的 manager 係 Node 3,y 的 manager 係 Node 8:

  1. Readlock(x) → 問 x 的 primary copy Node 3
  2. Read(x) → Read from the primary copy only(Node 3);other copies serve as backup
  3. Writelock(y) → 問 y 的 primary copy Node 8
  4. Write(y) → 寫 Node 8 同其他 copies(Node 2, 5)
⭐ 考試重點:Primary copy 2PL analysis
ConsPros(compared to other 2PL methods)
  • Network congestion may happen for hot data items(熱門 item 的 manager 好忙)
  • Does not take into account geographical locations(primary copy 可能離 user 好遠,例如 Node 3 唔係最近的 Node 1)
  • Single point of failure for data items:What if the manager node is down?
  • A bit better scalability than Centralized 2PL(lock 工作分散到唔同 managers)
  • Easier to implement and more efficient than Distributed 2PL

7.3 Distributed 2PL(slides 25–26)

假設 Node 1, 2, 3, 5 比較近。x 有 3 個 copies,majority = 2;y 都係:

  1. Readlock(x) → 問最近的兩個 x copies:Node 1 同 Node 3(超過一半 = 2/3 grant 就得)
  2. Read(x) → 喺最近的 copy 讀(Node 1)
  3. Writelock(y) → 問最近的兩個 y copies:Node 2 同 Node 5
  4. Write(y) → 寫晒 Node 2, 5, 8
💡 直覺理解

點解 majority 就夠?兩個 transactions 如果都攞到「超過一半」的 lock,佢哋的 node 集合一定會重疊(3 個入面揀 2 個,兩組 2 個必定有共同 node)。重疊的 node 唔會同時 grant 兩個 conflicting locks,所以唔會兩個都成功。

⭐ 考試重點:Distributed 2PL analysis
ConsPros(compared to other 2PL methods)
  • Significantly larger number of messages in the network
  • Complex implementation
  • How to detect deadlock?
  • Improved availability by avoiding single point of failure
  • Also avoided manager that is far away(可以揀近的 nodes 投票)

7.4 三種 2PL 一覽

⭐ 考試重點:Comparison
CentralizedPrimary copyDistributed
Lock manager1 個 node 管所有 items每個 item 一個 managerMajority of copies
Read 邊個 copy最近的 copyPrimary copy only最近的 copy
Single point of failure有(整個系統)有(per data item)冇
CongestionCentral nodeHot data itemsMessages 多
Geographical locationCentral 可能好遠唔考慮可揀近的 nodes
Deadlock detectionEasyComplexComplex
ImplementationEasiest中等Most complex

7.5 Deadlock detection(slide 27)

Except Centralized 2PL, deadlock detection becomes complex。Example:

  • T1 is waiting for T2 at Site 1 (item x)
  • T2 is waiting for T1 at Site 2 (item y)

Site 1 的 local wait-for graph 只有 T1 → T2;Site 2 只有 T2 → T1。No single site is able to realize the deadlock loop without communication:要將兩邊合併成 global wait-for graph,先見到 cycle T1 → T2 → T1。

If communication is required,就有新問題:When do the sites communicate?(幾耐交換一次?太密 = network 負擔,太疏 = deadlock 拖好耐先發現)What data is exchanged?(成個 local graph?定只係部分 edges?)

8. Timestamp-based concurrency control

Modern high-performance distributed database systems prefer time-based methods。

Requirement:Each transaction gets a unique timestamp。兩種派 timestamp 的方法:

  • Centralized:A single site is responsible to assign a timestamp to each transaction(又係 single point of failure / bottleneck)
  • Distributed:Combine local timestamp with unique site identifier
TS(T)=Local_Timestamp  ∥  Site_IDTS(T) = \text{Local\_Timestamp} \;\|\; \text{Site\_ID}

∥\| 係 concatenation(駁埋)。例如 Site 3 喺 local time 1005 開始一個 transaction,Site 7 都喺 1005 開始一個:兩個 TS 分別係 1005‖3 同 1005‖7,因為 Site_ID 唔同,所以一定 unique。Local timestamp 放前面(high-order),所以比較先睇時間,時間一樣先睇 Site_ID。

⭐ 考試重點:Timestamp 慣例

Smaller timestamp = older transaction(早啲開始);larger timestamp = younger。以下所有 protocols 都係 older transactions have priority。

8.1 Wound-Wait Protocol(slide 29)

When T1 requests a lock on a data item that is currently held by T2:

  • If T1 is older (smaller timestamp) → wound:Kill T2 (T2 rollbacks)
  • If T1 is younger (larger timestamp) → wait

As the older never waits for a younger, a deadlock can never happen。

8.2 Wait-Die Protocol(slide 30)

Same rule(older has priority)。When T1 requests a lock held by T2:

  • If T1 is older (smaller timestamp) → wait
  • If T1 is younger (larger timestamp) → die(T1 rollbacks)

As the younger never waits for an older, a deadlock can never happen。

⭐ 考試重點:記法
Requester T1 vs Holder T2Wound-WaitWait-Die
T1 olderT1 wounds T2(T2 rollback)T1 waits
T1 youngerT1 waitsT1 dies(T1 rollback)
Wait 方向只有 younger 等 older只有 older 等 younger

口訣:名字的第一個字係「requester 較 old 時」的動作。Wound-Wait:old → wound、young → wait;Wait-Die:old → wait、young → die。兩個 protocol 被 rollback 的永遠係 younger 那個。

💡 點解冇 deadlock

Deadlock 需要 wait-for graph 有 cycle,例如 T1 → T2 → T1。喺 Wound-Wait,所有 wait edge 都係 younger → older,timestamp 沿住 edge 一路變細,冇可能兜返轉頭,所以冇 cycle。Wait-Die 就反過來,所有 edge 都係 older → younger,一樣冇 cycle。

8.3 Comparisons(slide 31)

⭐ 考試重點:Wound-Wait vs Wait-Die vs 2PL
  • Wound-wait(compared against Wait-Die):Lower abort rate, but more expensive aborts。Wounded transactions might have done substantial work before being aborted.
  • Wait-Die(compared against Wound-Wait):Higher abort rate, but cheaper aborts。Younger transactions die early, minimizing wasted work.
2PLWound-WaitWait-Die
GoalCorrect resultCorrect result and Prevent DeadlocksCorrect result and Prevent Deadlocks
Deadlock May Happen?YesNoNo
Unnecessary abort?NoYesYes
⚠️ 常見錯誤

「Unnecessary abort」意思係:就算根本唔會形成 deadlock,只要 timestamp 條件中咗,都會 rollback 某個 transaction。呢個係 deadlock prevention 的代價。2PL 唔會無端 abort,但可能 deadlock。

9. Timestamp Ordering (T/O) Concurrency Control

Each transaction is assigned a timestamp;each data item X is associated with two timestamp values:

⭐ 考試重點:RTS / WTS
  • Read Timestamp RTS(X)RTS(X):The timestamp of the youngest transaction that successfully read X
  • Write Timestamp WTS(X)WTS(X):The timestamp of the youngest transaction that successfully wrote (updated) X
  • Core idea:If T1 has a smaller timestamp than T2, T1 must finish before T2(結果要等同按 timestamp 次序 serial execution)

9.1 T/O Concurrency Rules(slides 33–34)

Let tt be the timestamp of the transaction.

⭐ 考試重點:T/O rules

Rule 1: Read Operation READ(X)

  • If t<WTS(X)t < WTS(X) → Too late:A younger transaction has already written X → Die (Rollback)
  • Else → RTS(X):=max⁡(RTS(X), t)RTS(X) := \max(RTS(X),\, t)

Rule 2: Write Operation WRITE(X)

  • If t<RTS(X)t < RTS(X) → Too late:A younger transaction has already read X → Die (Rollback)
  • Else if t<WTS(X)t < WTS(X) → Outdated but does not affect the correctness:The write action is simply ignored(Thomas Write Rule)→ Do nothing
  • Else → WTS(X):=tWTS(X) := t
💡 直覺理解

想像要按 timestamp 次序排隊做事。Read 太遲:你(舊)想讀 X,但後生的已經改咗 X;照道理你應該見到改之前的值,但舊值已經冇咗,所以只能 rollback。Write 太遲(有人讀咗):後生的已經讀咗 X 的舊值,你而家先寫,佢應該見到你寫的值但冇見到,所以 rollback。Write 過時(有人寫咗):後生的已經寫咗 X,按次序你的值本來就會被佢覆蓋,而中間冇人讀過你的值,所以直接當你寫咗再被蓋過,ignore 就得(Thomas Write Rule)。

9.2 Worked example(自擬)

開始時 RTS(X)=5RTS(X) = 5,WTS(X)=3WTS(X) = 3。依次處理:

Operation檢查結果RTS(X)RTS(X)WTS(X)WTS(X)
READ(X), t=4t=44<34 < 3? NoOKmax⁡(5,4)=5\max(5,4)=53
READ(X), t=2t=22<32 < 3? YesDie53
WRITE(X), t=4t=44<RTS=54 < RTS=5? YesDie53
WRITE(X), t=6t=66<56 < 5? No;6<36 < 3? NoOK,寫入56
WRITE(X), t=5t=55<55 < 5? No;5<65 < 6? YesIgnore(Thomas Write Rule)56
READ(X), t=7t=77<67 < 6? NoOK76

9.3 Analysis of T/O(slide 35)

⭐ 考試重點
ProsCons
No locking is required;No waiting is requiredHigh abort rate;May lead to cascading aborts

Cascading abort:T2 讀咗 T1 寫的值,之後 T1 被 rollback,咁 T2 讀到的係「從未正式存在」的值,T2 都要 abort;如果 T3 又讀咗 T2 寫的值,就一路連鎖落去。

10. Multiversion Timestamp Ordering (MVTO) 與 MVCC

Instead of a single copy of the data, MVTO keeps all the versions of the data(每個 version 標住寫入佢的 transaction timestamp)。

⭐ 考試重點:MVTO rules(slide 36)
  • Read never aborts:Just get the right version to read(timestamp ≤t\le t 之中最新的 version)
  • Write:Check with the youngest read timestamp → If it is too late, abort;Otherwise, add the version to the database

10.1 Example(slides 37–38)

X 的 versions:

tvalue
110
330
520
815
⭐ 考試重點:READ(X)
  • t=2t = 2 → 讀 ≤2\le 2 之中最新的 version(t = 1)→ Gets 10
  • t=6t = 6 → ≤6\le 6 之中最新的係 t = 5 → Gets 20
  • Read never fails

WRITE(X) = 40,Last read timestamp = 6:

  • t=4t = 4 → 4<64 < 6:timestamp 6 的 transaction 已經讀咗 X(佢讀的版本冇包括你的寫入),太遲 → Abort!
  • t=6t = 6(no other transaction has t = 6, it is me!)→ 讀的就係自己,冇問題 → Add a version of 40 at t = 6
  • t=7t = 7 → 7>67 > 6 → Add a version of 40 at t = 7(就算已經有 t = 8 的 version 都得,因為係多版本,插入中間就可以)
⚠️ 留意

Slide 的規則係簡化版:同「youngest read timestamp」比較。考試請跟 slide 的做法:t<t < last read timestamp 就 abort。另外 t=7t = 7 喺 basic T/O 會因為 7<WTS=87 < WTS = 8 被 ignore,但 MVTO 照樣加入 version,呢個就係多版本的分別。

10.2 Analysis of MVTO(against Basic T/O)(slide 39)

⭐ 考試重點
ProsCons
Significantly lower abort rate;Read never abortsHigher storage cost:Multiple versions of the data are kept
Garbage collection overhead:Old versions are deleted to reclaim space;Garbage collection is complex

Weakness:Write abort remains。Usually the write actions are at the end of the transaction and other transactions may have read the data(做到最尾先寫,好大機會已經有後生的讀咗 → abort,前面做的嘢都白費)。

10.3 Multi-Version Concurrency Control (MVCC)(slides 40–42)

⭐ 考試重點:MVCC vs MVTO

MVCC is the general approach while MVTO is a specific algorithm of MVCC。Note:most systems have their own adaptions about how MVCC is implemented,no single, standard MVCC algorithm。

  • MVCC used by many modern database systems:Oracle、PostgreSQL、MySQL (InnoDB)
  • MVCC in distributed database systems:BrightDB、CockroachDB、Google Cloud Spanner、TiDB、YugabyteDB、MongoDB、CouchDB

Example:MVCC in PostgreSQL(slide 42):

  • MVCC handles read-write conflicts(reader 讀舊 version,唔使等 writer)
  • Locking is used for write-write conflicts
  • Locking is also applied to:Schema changes(the entire table is locked);Explicit record locking(the SELECT FOR UPDATE statement)
-- PostgreSQL:明確鎖住要改的 record,防止其他 transaction 同時修改
BEGIN;
SELECT * FROM account WHERE id = 1 FOR UPDATE;
UPDATE account SET balance = balance - 100 WHERE id = 1;
COMMIT;
💡 直覺理解

現實系統通常係混合做法:讀用 multi-version(快、唔使等),寫同寫之間仍然用 lock(簡單、可靠)。

11. Raft algorithm:Consensus

Purpose:Handle failure in a distributed environment → Fault-tolerance protocol → Increased Availability(Ongaro & Ousterhout, 2014, “In Search of an Understandable Consensus Algorithm”)。Existing databases using Raft:BrightDB、MongoDB、TiDB、YugabyteDB。

11.1 Raft mechanism(slide 44)

  • A single Raft group is responsible for a single partition/shard
  • Key idea:There is a leader of the nodes;the nodes elect one unique leader;other nodes are followers
⚠️ Reminder(slide 強調)

Raft does not distribute the database workload。The leader node carries extra workload(e.g., synchronization)beyond handling client queries。The primary goal is to handle potential failures (fault tolerance),唔係提升 performance。

11.2 Handling request (normal situation)(slide 45)

⭐ 考試重點:Raft normal operation
  1. The client only communicates with the leader
  2. The leader will handle the request
  3. The update at the leader will also be sent to the followers
  4. Acknowledgement from majority (consensus) is required to officially declare the operation is done

例如一個 group 有 1 個 leader + 2 個 followers(共 3 個 nodes):leader 自己加一個 follower ack 就係 2/3 majority,即可宣佈完成;就算第三個 node 壞咗都唔影響。

11.3 Detecting problems(slide 46)

  • Heartbeat:The leader periodically sends heartbeats to all followers to maintain authority
  • When the leader is found “dead”(followers 收唔到 heartbeat)→ a new leader is elected
  • When a failed node recovers, it synchronizes data from the group

12. Distributed database features:CAP

⭐ 考試重點:CAP definitions(slide 47)
  • Consistency:Every read receives the most recent write or an error
  • Availability:Every request received by a non-failing node must result in a response
  • Partition tolerance:Partition refers to network partitions。The system continues to operate despite an arbitrary number of messages being dropped (or delayed) by the network between nodes。The system must be distributed!

12.1 Consistency in CAP vs ACID(slide 48)

⭐ 考試重點:They are different!
C in CAPC in ACID
About data freshness。The problem arises in a distributed environment, where the most up-to-date data may reside in one site but not all the sitesAbout data correctness(transaction 令 database 由一個 consistent state 去另一個 consistent state,例如轉帳前後總金額不變)

12.2 CAP Theorem(slide 49)

⭐ 考試重點

Any distributed database system can provide at most two of the following three features:C, A, P。

  • 2000:Brewer 提出時係 conjecture(PODC 2000)
  • 2002:Seth Gilbert & Nancy Lynch (MIT) published a formal proof → 成為 theorem

12.3 Category of database systems(slide 50)

⭐ 考試重點:CA / CP / AP
Category意思Example / 口吻
CA冇 P,即係唔係 distributedTraditional centralized DBMS
CP(sacrifice A)Distributed system,有 P,揀 C“If I can't be sure this is the latest answer, I'll return an error (unavailability)”
AP(sacrifice C)Distributed system,有 P,揀 A“I will always return an answer (availability), but I can't promise it's the latest one (potential inconsistency)”

With P(distributed system)→ 一定要喺 C 同 A 之間做 tradeoff。

💡 直覺理解

想像香港同倫敦兩個 site 之間條網線斷咗(network partition)。有人喺倫敦改咗 X,香港 user 而家想讀 X。香港只有兩個選擇:(1) 答「暫時唔知最新值」,回 error,即係保 C、犧牲 A;(2) 照答手上的舊值,即係保 A、犧牲 C。冇第三個選擇,呢個就係 CAP 的核心。

12.4 Which system is CP / AP?(slide 51)

In fact, many systems can be configured to adapt to either goal! Example:MongoDB

⭐ 考試重點:MongoDB example
SettingCategory運作
Write majority settingCPWrites must go to majority sites;the system becomes unavailable when majority sites can't communicate
Minimal write settingAPWrites require acknowledgement from the primary site only;when the primary site is disconnected from others, another site may stand up and act as the new primary site (with the old data)

Note:As a transaction may read an old data, ACID is not guaranteed!

13. From ACID to BASE (for AP)

Not every application requires ACID。Discussion:Is it a big deal when a transaction reads an old value? Example scenario:application 由 database summarize 新聞,生成一篇「summary news」。如果漏咗幾條最新新聞,問題大唔大?其實唔大,下次再 summarize 就會包埋。

⭐ 考試重點:BASE

Basically Available, Soft-state, Eventually-consistent:A relaxed version of ACID(for AP systems)。

  • Basically available:Reading and writing operations are available as much as possible (using all nodes of a database cluster);might not be consistent (a read might not get the latest write)
  • Soft-state:Without consistency guarantees, after some amount of time, we only have some probability of knowing the state, since it might not yet have converged
  • Eventually consistent:If we execute some writes and then the system functions long enough, we can know the state of the data;any further reads of that data item will return the same value

Note:ACID is still very important in some scenarios, like bank account transactions!

⚠️ 易混淆

BASE 唔係「冇 consistency」,而係 eventually consistent:短時間內唔同 node 可能答唔同值,但停止寫入一段時間後,所有 node 會收斂到同一個值。揀 ACID 定 BASE 要睇應用:銀行轉帳用 ACID;社交媒體 like 數、新聞摘要可以用 BASE。

14. NewSQL system

NewSQL:A new class of modern distributed RDBMS。The aim is to achieve:

  • High scalability
  • Distributed ACID(essentially CP)
  • Use the familiar SQL language
⚠️ Note(slide 強調)

NewSQL is not a language like SQL! 佢係一類 database system 的名稱。前面 slides 提過的 CockroachDB、TiDB、YugabyteDB、Google Spanner 都係常見的 NewSQL 例子(用 MVCC + Raft 做到 distributed ACID)。

自我測驗 Self-test

Q1. 用 slide 8 的 employee table:(a) SELECT Name, StartDate FROM T WHERE EmployeeID = 103;(b) SELECT AVG(Salary) FROM T。各自 HF 定 VF 較好?點解?

(a) HF 較好:用 EmployeeID 可以 localize 到 Site 1(103≤105103 \le 105),一個 site 就攞到成條 record。VF 下 Name 喺 Fragment A、StartDate 喺 Fragment B,要讀兩個 fragments 再 JOIN。(b) VF 較好:只需 Salary 一個 column,但要掃晒所有 rows。VF 只讀 (EmployeeID, Name, Department, Salary) fragment,唔使讀其他 columns;HF 要兩個 site 都掃全部 columns,再合併兩邊的 sum 同 count。

Q2. 點解 HF 的 reconstruction 比 VF 簡單?VF 每個 fragment 一定要包含咩?

HF 用 UNION(將 rows 疊埋),VF 要用 JOIN(按 key 配對 rows),JOIN 貴好多。VF 每個 fragment 都要包含 primary key(例如 EmployeeID),否則冇辦法 JOIN 返原本的 table。

Q3. 列出 Replication 的 3 個 benefits 同 2 個 costs。

Benefits:Availability(一個 copy 壞咗仲有其他)、Reduced Latency(讀最近的 copy)、Parallelism(read queries 可以 parallel)。Costs:Update Overhead(每次 update 要 propagate 去所有 copies,network traffic 增加)、Concurrency Control(保持所有 copies 一致好複雜,涉及 Consistency vs. Availability)。

Q4. Distributed query processing 的 dominant cost 係咩?列出四個步驟。

Network communication(latency and volume),所以目標係 minimize data transfer。四步:Query Decomposition → Distributed Optimization and Localization → Local Execution → Result Reconstruction。

Q5. x 放喺 Node 1, 3, 7。用 Distributed 2PL 讀 x,最少要幾多個 nodes grant readlock?相比 Centralized 2PL 有咩好處同壞處?

超過一半:3 個 copies 要 2 個 grant。好處:冇 single point of failure,improved availability;可以揀近的 nodes,避免 manager 好遠。壞處:messages 大幅增加、implementation 複雜、deadlock detection 困難。Centralized 2PL 則容易 detect deadlock、最易實作,但有 congestion、scale 受 central node 限制、single point of failure。

Q6. 點解除咗 Centralized 2PL,distributed deadlock detection 都好難?用 slide 例子解釋。

T1 喺 Site 1 等 T2(item x),T2 喺 Site 2 等 T1(item y)。每個 site 的 local wait-for graph 都只有一條 edge,冇 cycle;要合併兩個 site 的資料先見到 T1 → T2 → T1。所以 sites 之間要 communicate,又引出「幾時溝通」同「交換咩 data」的問題。Centralized 2PL 所有 lock 資訊都喺一個 node,所以容易。

Q7. TS(TA)=10TS(T_A) = 10,TS(TB)=20TS(T_B) = 20。TBT_B 持有 X 的 lock,TAT_A 申請 X 的 lock。分別用 Wound-Wait 同 Wait-Die,會發生咩?反過來(TAT_A 持有、TBT_B 申請)又點?

TAT_A 較 old(timestamp 細)。TAT_A 申請:Wound-Wait → TAT_A wound TBT_B,TBT_B rollback;Wait-Die → TAT_A wait。TBT_B 申請:Wound-Wait → TBT_B(younger)wait;Wait-Die → TBT_B die(rollback)。兩種 protocol 被 rollback 的都係 younger 的 TBT_B。

Q8. Wound-Wait 同 Wait-Die 邊個 abort rate 較低?邊個 abort 較平?點解?

Wound-Wait abort rate 較低,但 abort 較貴:被 wound 的 transaction 可能已經做咗好多嘢。Wait-Die abort rate 較高,但 abort 較平:younger 喺一開始申請 lock 時就 die,浪費的工作少。兩者都可以 prevent deadlock,但都有 unnecessary abort;2PL 冇 unnecessary abort,但可能 deadlock。

Q9. Basic T/O:RTS(X)=8RTS(X) = 8,WTS(X)=6WTS(X) = 6。依次處理 (a) WRITE(X) t=7t=7;(b) READ(X) t=5t=5;(c) WRITE(X) t=9t=9;(d) WRITE(X) t=8t=8。

(a) 7<RTS=87 < RTS = 8 → Die(younger 已讀咗 X)。(b) 5<WTS=65 < WTS = 6 → Die(younger 已寫咗 X)。(c) 9≥89 \ge 8 而且 9≥69 \ge 6 → 寫入,WTS(X)=9WTS(X) = 9。(d) 8<RTS=88 < RTS = 8? No;8<WTS=98 < WTS = 9? Yes → Thomas Write Rule,ignore(do nothing)。最後 RTS=8RTS = 8,WTS=9WTS = 9。

Q10. MVTO:X 的 versions 有 (t=1, 10)、(t=3, 30)、(t=5, 20)、(t=8, 15)。READ(X) t=4t=4 同 t=9t=9 各讀到咩?如果 last read timestamp = 6,WRITE(X) t=5t=5 會點?

t=4t=4 → ≤4\le 4 最新的係 t = 3 → 30。t=9t=9 → t = 8 → 15。WRITE t=5t=5:5<65 < 6,timestamp 6 的 transaction 已經讀咗 → abort。(Read never aborts,但 write abort 仍然存在,呢個就係 MVTO 的 weakness。)

Q11. CAP 的 C 同 ACID 的 C 有咩分別?點解 traditional centralized DBMS 叫做 CA?

CAP 的 C 講 data freshness:每次 read 都攞到最新的 write(或 error)。ACID 的 C 講 data correctness:transaction 保持 database 喺 consistent state。Centralized DBMS 冇 network partition 的問題(唔係 distributed,冇 P),所以可以同時有 C 同 A。

Q12. MongoDB 點樣可以 configure 成 CP 或 AP?AP setting 有咩風險?

CP:write majority setting,writes 要去 majority sites;majority 溝通唔到時系統 unavailable。AP:minimal write setting,只需 primary site acknowledge;primary 斷線時,另一個 site 可能頂上做新 primary,但佢手上係舊 data,transaction 可能讀到舊值,所以 ACID is not guaranteed。

Q13. BASE 三個字代表咩?舉一個適合同一個唔適合 BASE 的應用。

Basically Available(盡量用所有 nodes 提供讀寫,但 read 可能唔係最新)、Soft-state(未收斂前只能以某個概率知道 state)、Eventually consistent(系統運作夠耐後,之後所有 reads 回傳同一個值)。適合:新聞摘要,漏幾條新聞問題唔大。唔適合:bank account transactions,必須用 ACID。

Q14. Raft 的目的係咩?佢會唔會分散 database workload?描述 normal request 的流程。

目的係 fault tolerance / handle failure,提高 availability。佢唔會分散 workload,leader 仲要負擔額外的 synchronization 工作。流程:client 只同 leader 溝通 → leader 處理 request → update 傳去 followers → 收到 majority acknowledgement 先正式宣佈完成。Leader 定期發 heartbeat;followers 發現 leader「死咗」就選新 leader;恢復的 node 從 group 同步 data。

一頁總結 Cheat sheet

⭐ 考前速記
  • Why distributed:data 本身分散、Reliability & Availability(replication)、Scalability(parallel、近 data)、Economic(平機 vs mainframe)
  • Goal:as if a single centralized DB;Location transparency(domain name 按 requester 位置 map 去唔同 IP)
  • Challenges:Security、Distributed Query Processing、Distributed Transaction Management (ACID)
  • Fragmentation = Sharding(non-overlapping);HF = rows(MongoDB、Spanner);VF = columns(MonetDB、RDBMS 喺 application level);Mixed = 最複雜最 flexible
  • HF:data locality、UNION 重組、易實作、parallel;VF:只讀需要的 columns、sensitive columns 隔離(security);VF fragments 要保留 key
  • Q1(by ID 攞整條 record)→ HF;Q2(COUNT on Salary)→ VF
  • Replication:+ availability、latency、read parallelism;− update overhead、consistency 難(C vs A)
  • Query processing:dominant cost = network → minimize data transfer;Decomposition → Optimization & Localization → Local Execution → Reconstruction (UNION)
  • Centralized 2PL:一個 manager;易 detect deadlock、最易實作;congestion、scale 受限、成本高、SPOF
  • Primary copy 2PL:每 item 一個 manager,只讀 primary;hot items congestion、唔理地理位置、per-item SPOF;scalability 稍好
  • Distributed 2PL:majority vote(> half);冇 SPOF、可揀近 nodes;messages 多、複雜、deadlock detection 難
  • Distributed deadlock:每個 site 只見局部 wait-for graph,要 communication(幾時?交換乜?)
  • Timestamp:unique;TS=Local_Timestamp ∥ Site_IDTS = \text{Local\_Timestamp} \,\|\, \text{Site\_ID};細 = old = 優先
  • Wound-Wait:old 申請 → wound younger;young 申請 → wait。Wait-Die:old → wait;young → die。都係 younger 被 rollback、冇 deadlock、有 unnecessary abort
  • Wound-Wait:abort 少但貴;Wait-Die:abort 多但平
  • T/O:READ t<WTSt < WTS → die,否則 RTS=max⁡(RTS,t)RTS = \max(RTS, t);WRITE t<RTSt < RTS → die,t<WTSt < WTS → ignore(Thomas Write Rule),否則 WTS=tWTS = t;no lock、no wait;high abort、cascading aborts
  • MVTO:keep all versions;read 攞 ≤t\le t 最新 version,never aborts;write 若 t<t < youngest read TS → abort,否則加 version;+ abort 少;− storage、garbage collection;write abort 仍在
  • MVCC = general approach,MVTO = specific algorithm;冇 standard algorithm;Oracle、PostgreSQL、MySQL;PostgreSQL:MVCC 處理 read-write,lock 處理 write-write、schema change、SELECT FOR UPDATE
  • Raft:fault tolerance,唔分散 workload;一個 group 管一個 shard;elect one leader + followers;client 只同 leader 講;majority ack;heartbeat;新 leader election;恢復的 node 同步
  • CAP:C = most recent write or error;A = non-failing node 必回應;P = network partition 下照運作(必須 distributed);最多揀兩個(Brewer 2000 conjecture → Gilbert & Lynch 2002 proof)
  • CAP 的 C = freshness;ACID 的 C = correctness
  • CA = centralized DBMS;CP = 唔肯定就回 error;AP = 一定答但可能舊;MongoDB:write majority = CP,minimal write = AP(ACID not guaranteed)
  • BASE = Basically Available, Soft-state, Eventually consistent(relaxed ACID for AP);銀行仍要 ACID
  • NewSQL = distributed RDBMS:high scalability + distributed ACID(CP)+ SQL;NewSQL 唔係一種 language