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
- HF vs VF:定義、邊條 query 用邊種較好(slide 11 Q1 / Q2)、優點(UNION vs JOIN、data locality、security)
- 三種 distributed 2PL 的運作同 pros / cons(single point of failure、network congestion、message 數量、deadlock detection)
- Wound-Wait vs Wait-Die:規則(邊個 wait、邊個 rollback)、點解冇 deadlock、abort rate / abort cost 比較表
- T/O 的 Read / Write rules(RTS、WTS、Thomas Write Rule)同 MVTO 例題(slide 37–38 讀邊個 version、write 會唔會 abort)
- 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 列出四個原因:
| 原因 | Slide 原文 | 解釋 |
|---|---|---|
| Distributed Nature of Data | Data 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 Benefits | Connect smaller, cheaper machines vs a single, monolithic mainframe | 好多部平機加埋,往往比一部超級 mainframe 更抵 |
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。三大挑戰:
- 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
| Type | Definition | Example 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 Fragmentation | Applying both horizontal and vertical fragmentation | Most complex, most flexible |
4.2 Example data(slides 8–10)
Table T(10 個 employees):
| EmployeeID | Name | Department | Salary | StartDate | IsFullTime |
|---|---|---|---|---|---|
| 101 | Alice Johnson | Sales | $60,000 | 2022-08-15 | True |
| 102 | Bob Smith | Marketing | $75,000 | 2021-05-20 | True |
| 103 | Charlie Brown | Engineering | $95,000 | 2023-01-10 | True |
| 104 | Diana Prince | HR | $55,000 | 2024-03-01 | False |
| 105 | Ethan Hunt | Engineering | $110,000 | 2020-11-25 | True |
| 106 | Fiona Glenanne | Sales | $62,000 | 2023-09-01 | False |
| 107 | George Costanza | Marketing | $70,000 | 2022-04-12 | True |
| 108 | Hannah Baker | HR | $58,000 | 2024-01-20 | True |
| 109 | Ian Malcolm | Engineering | $105,000 | 2021-07-01 | True |
| 110 | Jessica Day | Sales | $59,000 | 2023-05-18 | False |
Horizontal Fragmentation(slide 9):按 rows 切開兩份。Fragment 1 = EmployeeID 101–105(),Fragment 2 = 106–110()。每個 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)
| Query | 較好 | 原因 |
|---|---|---|
Q1: SELECT * FROM T WHERE EmployeeID = 107 | HF | 要成條 record(所有 columns)。HF 下只需去 Site 2 一個地方攞一條完整 record;VF 下要去兩個 fragments 再 JOIN |
Q2: SELECT COUNT(*) FROM T WHERE Salary > 50000 | VF | 只需要 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 of HF | Advantages 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 database | Queries 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 有著數。
COM6001 pandas:HF 就係 row filtering df[df.EmployeeID <= 105],重組用 pd.concat([f1, f2])(= UNION);VF 就係 column selection df[['EmployeeID','Salary']],重組用 pd.merge(a, b, on='EmployeeID')(= JOIN)。
4.5 Trade-offs of Replication(slide 13)
| Benefits | Costs |
|---|---|
| Availability:If one copy fails, others are available | Update Overhead:Every update must be propagated to all copies (increased network traffic) |
| Reduced Latency:Queries can access the closest copy | Concurrency 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)
- Query Decomposition:Translating the high-level query into local queries
- Distributed Optimization and Localization:Determine which specific site (fragment) holds the required data;Query transformation where appropriate
- Local Execution:Local DBMS at each site executes the localized sub-query on its fragment
- Result Reconstruction:Reconstruct the global result from local results
5.2 Example 1:WHERE EmployeeID = 107(slides 16–17)
用返 HF 例子:Site 1 放 ,Site 2 放 。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
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)。
Week 3 講過單機的 transaction、ACID、2PL 同 deadlock(wait-for graph)。Week 3 slide 已預告「Other methods:Timestamp ordering、MVCC、Raft algorithm」,今個星期就逐個講,而且係擺喺 distributed 環境入面講。
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? 三種做法:
| Variant | 邊個批 lock |
|---|---|
| Centralized 2PL | One site is designated as the central manager (for all data items) |
| Primary copy 2PL | There is a central manager for each data item;the central managers of different data items can be different(Stonebraker, Distributed Ingres, 1979) |
| Distributed 2PL | Majority 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:
- Readlock(x) → 問 Centralized node
- Read(x) → 去最近的 copy(Node 1)讀
- Writelock(y) → 問 Centralized node
- 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。
| Cons | Pros(compared to other 2PL methods) |
|---|---|
|
|
7.2 Primary copy 2PL(slides 23–24)
x 的 manager 係 Node 3,y 的 manager 係 Node 8:
- Readlock(x) → 問 x 的 primary copy Node 3
- Read(x) → Read from the primary copy only(Node 3);other copies serve as backup
- Writelock(y) → 問 y 的 primary copy Node 8
- Write(y) → 寫 Node 8 同其他 copies(Node 2, 5)
| Cons | Pros(compared to other 2PL methods) |
|---|---|
|
|
7.3 Distributed 2PL(slides 25–26)
假設 Node 1, 2, 3, 5 比較近。x 有 3 個 copies,majority = 2;y 都係:
- Readlock(x) → 問最近的兩個 x copies:Node 1 同 Node 3(超過一半 = 2/3 grant 就得)
- Read(x) → 喺最近的 copy 讀(Node 1)
- Writelock(y) → 問最近的兩個 y copies:Node 2 同 Node 5
- Write(y) → 寫晒 Node 2, 5, 8
點解 majority 就夠?兩個 transactions 如果都攞到「超過一半」的 lock,佢哋的 node 集合一定會重疊(3 個入面揀 2 個,兩組 2 個必定有共同 node)。重疊的 node 唔會同時 grant 兩個 conflicting locks,所以唔會兩個都成功。
| Cons | Pros(compared to other 2PL methods) |
|---|---|
|
|
7.4 三種 2PL 一覽
| Centralized | Primary copy | Distributed | |
|---|---|---|---|
| Lock manager | 1 個 node 管所有 items | 每個 item 一個 manager | Majority of copies |
| Read 邊個 copy | 最近的 copy | Primary copy only | 最近的 copy |
| Single point of failure | 有(整個系統) | 有(per data item) | 冇 |
| Congestion | Central node | Hot data items | Messages 多 |
| Geographical location | Central 可能好遠 | 唔考慮 | 可揀近的 nodes |
| Deadlock detection | Easy | Complex | Complex |
| Implementation | Easiest | 中等 | 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?)
Week 3 Q6 用 wait-for graph 搵 cycle 判斷 deadlock。喺 distributed 環境,每個 site 只得 graph 的一部分,所以先需要 communication,或者改用下一節「根本唔會 deadlock」的 timestamp 方法。
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
係 concatenation(駁埋)。例如 Site 3 喺 local time 1005 開始一個 transaction,Site 7 都喺 1005 開始一個:兩個 TS 分別係 1005‖3 同 1005‖7,因為 Site_ID 唔同,所以一定 unique。Local timestamp 放前面(high-order),所以比較先睇時間,時間一樣先睇 Site_ID。
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 T2 | Wound-Wait | Wait-Die |
|---|---|---|
| T1 older | T1 wounds T2(T2 rollback) | T1 waits |
| T1 younger | T1 waits | T1 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 需要 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(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.
| 2PL | Wound-Wait | Wait-Die | |
|---|---|---|---|
| Goal | Correct result | Correct result and Prevent Deadlocks | Correct result and Prevent Deadlocks |
| Deadlock May Happen? | Yes | No | No |
| Unnecessary abort? | No | Yes | Yes |
「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:
- Read Timestamp :The timestamp of the youngest transaction that successfully read X
- Write Timestamp :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 be the timestamp of the transaction.
Rule 1: Read Operation READ(X)
- If → Too late:A younger transaction has already written X → Die (Rollback)
- Else →
Rule 2: Write Operation WRITE(X)
- If → Too late:A younger transaction has already read X → Die (Rollback)
- Else if → Outdated but does not affect the correctness:The write action is simply ignored(Thomas Write Rule)→ Do nothing
- Else →
想像要按 timestamp 次序排隊做事。Read 太遲:你(舊)想讀 X,但後生的已經改咗 X;照道理你應該見到改之前的值,但舊值已經冇咗,所以只能 rollback。Write 太遲(有人讀咗):後生的已經讀咗 X 的舊值,你而家先寫,佢應該見到你寫的值但冇見到,所以 rollback。Write 過時(有人寫咗):後生的已經寫咗 X,按次序你的值本來就會被佢覆蓋,而中間冇人讀過你的值,所以直接當你寫咗再被蓋過,ignore 就得(Thomas Write Rule)。
9.2 Worked example(自擬)
開始時 ,。依次處理:
| Operation | 檢查 | 結果 | ||
|---|---|---|---|---|
| READ(X), | ? No | OK | 3 | |
| READ(X), | ? Yes | Die | 5 | 3 |
| WRITE(X), | ? Yes | Die | 5 | 3 |
| WRITE(X), | ? No;? No | OK,寫入 | 5 | 6 |
| WRITE(X), | ? No;? Yes | Ignore(Thomas Write Rule) | 5 | 6 |
| READ(X), | ? No | OK | 7 | 6 |
9.3 Analysis of T/O(slide 35)
| Pros | Cons |
|---|---|
| No locking is required;No waiting is required | High 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)。
- Read never aborts:Just get the right version to read(timestamp 之中最新的 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:
| t | value |
|---|---|
| 1 | 10 |
| 3 | 30 |
| 5 | 20 |
| 8 | 15 |
- → 讀 之中最新的 version(t = 1)→ Gets 10
- → 之中最新的係 t = 5 → Gets 20
- Read never fails
WRITE(X) = 40,Last read timestamp = 6:
- → :timestamp 6 的 transaction 已經讀咗 X(佢讀的版本冇包括你的寫入),太遲 → Abort!
- (no other transaction has t = 6, it is me!)→ 讀的就係自己,冇問題 → Add a version of 40 at t = 6
- → → Add a version of 40 at t = 7(就算已經有 t = 8 的 version 都得,因為係多版本,插入中間就可以)
Slide 的規則係簡化版:同「youngest read timestamp」比較。考試請跟 slide 的做法: last read timestamp 就 abort。另外 喺 basic T/O 會因為 被 ignore,但 MVTO 照樣加入 version,呢個就係多版本的分別。
10.2 Analysis of MVTO(against Basic T/O)(slide 39)
| Pros | Cons |
|---|---|
| Significantly lower abort rate;Read never aborts | Higher 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 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 UPDATEstatement)
-- 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
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)
- The client only communicates with the leader
- The leader will handle the request
- The update at the leader will also be sent to the followers
- 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
Raft 的「majority ack」同 Section 7.3 Distributed 2PL 的「majority vote」、同 Section 12 MongoDB 的「write majority」係同一個思路:只要超過一半 nodes 同意,任何兩個 majority 必定有重疊,系統就唔會出現兩個互相矛盾的決定。
12. Distributed database features:CAP
- 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)
| C in CAP | C 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 sites | About 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)
| Category | 意思 | Example / 口吻 |
|---|---|---|
| CA | 冇 P,即係唔係 distributed | Traditional 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
| Setting | Category | 運作 |
|---|---|---|
| Write majority setting | CP | Writes must go to majority sites;the system becomes unavailable when majority sites can't communicate |
| Minimal write setting | AP | Writes 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 就會包埋。
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
NewSQL is not a language like SQL! 佢係一類 database system 的名稱。前面 slides 提過的 CockroachDB、TiDB、YugabyteDB、Google Spanner 都係常見的 NewSQL 例子(用 MVCC + Raft 做到 distributed ACID)。
Week 1:scale out 好難,因為要處理 machine failure 同協調。今個星期就係答案:Fragmentation + Replication 解決 data 放邊;2PL / timestamp / MVCC 解決 concurrency;Raft 解決 failure;CAP 說明有啲取捨避唔到。Week 5 的 OLTP 需要 ACID,所以適合 CP / NewSQL;OLAP 讀舊少少的 data 問題唔大,可以接受 BASE。
自我測驗 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(),一個 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. ,。 持有 X 的 lock, 申請 X 的 lock。分別用 Wound-Wait 同 Wait-Die,會發生咩?反過來( 持有、 申請)又點?
較 old(timestamp 細)。 申請:Wound-Wait → wound , rollback;Wait-Die → wait。 申請:Wound-Wait → (younger)wait;Wait-Die → die(rollback)。兩種 protocol 被 rollback 的都係 younger 的 。
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:,。依次處理 (a) WRITE(X) ;(b) READ(X) ;(c) WRITE(X) ;(d) WRITE(X) 。
(a) → Die(younger 已讀咗 X)。(b) → Die(younger 已寫咗 X)。(c) 而且 → 寫入,。(d) ? No;? Yes → Thomas Write Rule,ignore(do nothing)。最後 ,。
Q10. MVTO:X 的 versions 有 (t=1, 10)、(t=3, 30)、(t=5, 20)、(t=8, 15)。READ(X) 同 各讀到咩?如果 last read timestamp = 6,WRITE(X) 會點?
→ 最新的係 t = 3 → 30。 → t = 8 → 15。WRITE :,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;;細 = 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 → die,否則 ;WRITE → die, → ignore(Thomas Write Rule),否則 ;no lock、no wait;high abort、cascading aborts
- MVTO:keep all versions;read 攞 最新 version,never aborts;write 若 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