Module 4A · Distributed Databases
The first part of syllabus Module 4 (NoSQL, the second part, is Module 4B). What happens when one database is not enough: using many processors at once (parallel databases), and spreading data across sites (distributed databases) — how to split and copy the data, how queries travel between sites, and how transactions stay correct when sites and links can fail.
- ▸ Compare shared-memory, shared-disk and shared-nothing architectures
- ▸ Explain inter- and intra-query parallelism, parallel sort and parallel join
- ▸ Describe distributed databases, their types and architectures
- ▸ Fragment, replicate and allocate data — and check a fragmentation is correct
- ▸ Estimate the network cost of a distributed query, including semijoins
- ▸ Explain distributed locking, deadlock detection, 2PC and 3PC
university_lab on one PostgreSQL server, standing in for a real cluster: a scratch schema lab4 for experiments, and a second database campus_b playing a remote site. The last section removes both.
One-time setup for this module's lab
CREATE SCHEMA lab4; -- a scratch area for Module 4A
-- needed only for the two-phase-commit example in 4.10
ALTER SYSTEM SET max_prepared_transactions = 10;
-- then restart PostgreSQL (Windows: Services → postgresql-x64-17 → Restart), and check:
SHOW max_prepared_transactions; -- 104.1 Architectures for Parallel Databases
Parallel architectures differ in what the processors (P) share: the memory (M), the disks (D), or nothing at all.
| Shared memory | Shared disk | Shared nothing | |
|---|---|---|---|
| Shared | Memory and disks | Disks only | Nothing — nodes talk over the network |
| Advantages | Simple; processors communicate fast through memory | A failed processor does not stop the system; memory is not a bottleneck | Scales to hundreds of nodes; only data a node lacks crosses the network |
| Disadvantages | The memory bus becomes a bottleneck; adding processors slows the others; cache coherency needed | The disk interconnect becomes a bottleneck; inter-processor communication is slow | Reading another node’s data is costly; data must be partitioned well |
| Scales to | Tens of processors | More than shared memory | Hundreds or thousands of nodes |
| Examples | A multi-core server running PostgreSQL | Oracle RAC; DEC VMScluster running Rdb | Teradata, Tandem; Greenplum and Citus (built on PostgreSQL) |
A single PostgreSQL server runs a separate process for each worker; they all share one block of memory (shared_buffers) and the same disks. These settings control how many processors one query may use:
SHOW max_worker_processes; -- 8: background processes the server may start
SHOW max_parallel_workers; -- 8: of those, how many may serve parallel queries
SHOW max_parallel_workers_per_gather; -- 2: helpers one query may use (plus the leader)- ▸Shared memory: P’s share M and D. Shared disk: own M, shared D. Shared nothing: own P, M and D per node.
- ▸Shared nothing scales best and is the basis of distributed databases.
- ▸Bottlenecks: the memory bus (shared memory), the disk interconnect (shared disk), the network (shared nothing).
4.2 Parallel Query Evaluation
| Inter-query parallelism | Intra-query parallelism | |
|---|---|---|
| What runs in parallel | Different queries or transactions | Parts of the same query |
| Improves | Throughput — more queries finished per second | Response time — each query finishes sooner |
| Example | 6 students each run a 3-second query: on 6 processors all 6 finish in about 3 s instead of 18 s | One 18-second report split across 6 processors finishes in about 3 s |
| Kinds | — | Intra-operation (one operator, e.g. a scan, split across processors) and inter-operation (different operators of the plan run at once, including pipelining) |
Corrections to the notes
The Module IV lecture notes use the same six-queries example for both kinds; intra-query parallelism is about one long query, as above. It also says pipelined parallelism comes from inter-query parallelism — in fact pipelining is a form of intra-query (inter-operation) parallelism: one operator passes rows to the next while both are running.
Speed-up measures the same job on more hardware (ideally: 2× processors → half the time). Scale-up measures a bigger job on proportionally more hardware (ideally: 2× data on 2× processors → the same time). Parallel query optimization picks the cheapest parallel plan, balancing the time to find a plan against the time to run it.
CREATE TABLE lab4.attendance_log AS
SELECT g AS log_id,
(g % 6) + 1 AS student_id, -- the 6 sample students
(g % 4) + 1 AS offering_id, -- the 4 offerings
DATE '2024-07-01' + (g % 150) AS class_date,
(g % 10) <> 0 AS present -- 90% present
FROM generate_series(1, 1000000) AS g;
ANALYZE lab4.attendance_log;EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT present, COUNT(*) FROM lab4.attendance_log GROUP BY present;
Finalize GroupAggregate (actual rows=2 loops=1)
-> Gather Merge (actual rows=6 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Sort (actual rows=2 loops=3)
-> Partial HashAggregate (actual rows=2 loops=3)
-> Parallel Seq Scan on attendance_log (actual rows=333333 loops=3)
Execution Time: 148.108 ms <- your times will differ
SET max_parallel_workers_per_gather = 0; -- switch parallelism off for comparison
-- same query:
HashAggregate (actual rows=2 loops=1)
-> Seq Scan on attendance_log (actual rows=1000000 loops=1)
Execution Time: 213.773 ms
RESET max_parallel_workers_per_gather;loops=3 and rows=333333 show the split: three processes each scanned a third of the rows and counted them (a partial aggregate); Gather Merge collected the partial counts and Finalize added them up.
- ▸Inter-query = many queries at once (throughput). Intra-query = one query split up (response time).
- ▸Intra-query parallelism is intra-operation (split an operator) or inter-operation (operators side by side, pipelining).
- ▸Speed-up: same job, more hardware. Scale-up: bigger job, proportionally more hardware.
4.3 Parallelizing Individual Operations: Scan, Sort, Join
| Operation | How it is parallelized |
|---|---|
| Scanning | Each processor reads the pages of its own partition; the results are merged. |
| Bulk loading | Rows are partitioned to the nodes and loaded in parallel; sorting for index building is done in parallel too. |
| Sorting | 1) Redistribute rows by range partitioning on the sort key. 2) Each processor sorts its range. 3) Read the processors in range order — the result is fully sorted. |
| Joining | Partition BOTH tables with the same hash function on the join key, so matching rows meet on the same processor; each processor joins its pair (hash join or sort-merge join); the union of the k small joins is the full join. |
Data skew
If one range holds far more rows than the others (most students joined in 2024, say), one processor does most of the work and the others wait. The fix: sample the data first and choose range boundaries that give equal-sized partitions.
EXPLAIN (COSTS OFF)
SELECT * FROM lab4.attendance_log ORDER BY class_date, log_id LIMIT 10;
Limit
-> Gather Merge
Workers Planned: 2
-> Sort
Sort Key: class_date, log_id
-> Parallel Seq Scan on attendance_logEXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM lab4.attendance_log a JOIN lab4.attendance_log b ON b.log_id = a.log_id;
Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Hash Join
Hash Cond: (a.log_id = b.log_id)
-> Parallel Seq Scan on attendance_log a
-> Parallel Hash
-> Parallel Seq Scan on attendance_log bEXPLAIN (COSTS OFF)
SELECT s.full_name, COUNT(*) AS classes_attended
FROM lab4.attendance_log a JOIN inter.students s ON s.student_id = a.student_id
WHERE a.present
GROUP BY s.full_name;
...
-> Hash Join
Hash Cond: (a.student_id = s.student_id)
-> Parallel Seq Scan on attendance_log a <- the big table is split
-> Hash
-> Seq Scan on students s <- the small table is copied to every workerThat last plan is the fragment-and-replicate (broadcast) strategy: split the big table, copy the small one everywhere — no need to partition both.
- ▸Partitioning: round-robin, hash or range.
- ▸Parallel sort: range-partition, sort each part, read parts in range order. Watch for data skew — sample to pick boundaries.
- ▸Parallel join: partition both inputs with the same hash on the join key; or broadcast a small table to all processors.
4.4 Distributed Database Concepts
Not a distributed database: a time-sharing system, a multiprocessor computer, or a single centralized database that happens to sit on one node of a network.
| Goal | Meaning |
|---|---|
| Reliability | If one site fails, the others keep working. |
| Availability | Data stays reachable — from a replica — even when a site is down. |
| Performance | Data sits close to where it is used, and sites work in parallel. |
| Local autonomy | Each site controls and manages its own data. |
| Scalability | Grow by adding sites, not by replacing one big server. |
| Transparency | The user need not know… |
|---|---|
| Location | where (at which site) the data is stored |
| Fragmentation | that a table is split into fragments |
| Replication | that copies of the data exist |
| Network / failure | about the network, or that a site has failed |
| Type | Description | Sub-types |
|---|---|---|
| Homogeneous | Every site runs the same DBMS (same vendor) and similar software; sites know each other and cooperate; users see a single database | Autonomous — independent DBMSs integrated by an application, sharing updates by messages. Non-autonomous — a central (master) DBMS coordinates updates |
| Heterogeneous | Sites run different DBMSs, data models, schemas or operating systems; query and transaction processing are harder; sites may not know each other | Federated — independent systems integrated to act as one. Un-federated — accessed through a central coordinating module |
- ▸DDB = inter-related databases over a network; DDBMS hides the distribution (transparency).
- ▸Goals: reliability, availability, performance, local autonomy, scalability.
- ▸Homogeneous (same DBMS: autonomous / non-autonomous) vs heterogeneous (different DBMSs: federated / un-federated).
4.5 Distributed DBMS Architectures
| Architecture | How it works | Notes |
|---|---|---|
| Client-server | Clients handle the user interface; servers manage data, process queries and run transactions. Single-server/multi-client or multi-server/multi-client | A single query cannot span several servers — the client must split it |
| Collaborating servers (peer-to-peer) | Every site is both client and server. A server that needs remote data generates sub-queries for the other servers and combines the answers | Uses four schema levels: global conceptual, local conceptual, local internal, and external (user views) |
| Middleware / multi-DBMS | A separate software layer accepts a query that spans many servers and coordinates them; the servers themselves need no multi-site abilities | Good for integrating legacy systems. Multi-DBMS schema levels: multi-database view, conceptual and internal; local view, conceptual and internal |
In 4.8 our university_lab server will answer a query by sending a sub-query to another database (campus_b) through postgres_fdw and combining the result with its own tables — exactly the collaborating-server idea, on a small scale.
- ▸Client-server: one query → one server. Collaborating servers: servers split queries among themselves. Middleware: a separate layer coordinates the servers.
- ▸Peer-to-peer schema levels: global conceptual, local conceptual, local internal, external.
4.6 Data Fragmentation
| Kind | Splits the table by | Defined with | Rebuilt with |
|---|---|---|---|
| Horizontal | Rows — each fragment is a subset of the rows | A selection: σ dept = ’CS’ (students) | UNION of the fragments |
| Derived horizontal | Rows of a child table, following its parent’s fragments | A semijoin: enrollments of CS students | UNION |
| Vertical | Columns — each fragment is a subset of the columns plus the primary key | A projection: π student_id, full_name, email (students) | JOIN on the primary key |
| Hybrid (mixed) | Both: rows, then columns (or the reverse) | Selection + projection | JOINs and UNIONs |
| Correctness rule | Meaning |
|---|---|
| Completeness | Every row (or column) of the table appears in at least one fragment — nothing is lost. |
| Reconstruction | The original table can be rebuilt exactly: UNION for horizontal, a lossless JOIN for vertical. |
| Disjointness | A row appears in only one horizontal fragment; for vertical fragments only the key is repeated. |
CREATE TABLE lab4.students_h (
student_id INTEGER,
full_name VARCHAR(100),
email VARCHAR(120),
join_year INTEGER,
dept_code VARCHAR(10) NOT NULL
) PARTITION BY LIST (dept_code);
CREATE TABLE lab4.students_cs PARTITION OF lab4.students_h FOR VALUES IN ('CS');
CREATE TABLE lab4.students_da PARTITION OF lab4.students_h FOR VALUES IN ('DA');
CREATE TABLE lab4.students_ma PARTITION OF lab4.students_h FOR VALUES IN ('MA');
INSERT INTO lab4.students_h
SELECT s.student_id, s.full_name, s.email, s.join_year, d.dept_code
FROM inter.students s JOIN inter.departments d ON d.dept_id = s.dept_id;
SELECT tableoid::regclass AS fragment, COUNT(*) AS students
FROM lab4.students_h GROUP BY 1 ORDER BY 1;
fragment | students
------------------+----------
lab4.students_cs | 3
lab4.students_da | 2
lab4.students_ma | 1EXPLAIN (COSTS OFF) SELECT full_name FROM lab4.students_h WHERE dept_code = 'DA';
Seq Scan on students_da students_h <- the CS and MA fragments are never touched
Filter: ((dept_code)::text = 'DA'::text)INSERT INTO lab4.students_h VALUES (99, 'Test', 'test@duk.ac.in', 2025, 'PH');
ERROR: no partition of relation "students_h" found for row
DETAIL: Partition key of the failing row contains (dept_code) = (PH).CREATE TABLE lab4.students_contact AS SELECT student_id, full_name, email FROM inter.students;
CREATE TABLE lab4.students_academic AS SELECT student_id, join_year, dept_id FROM inter.students;
-- reconstruction is lossless: rebuilt rows vs original rows, compared both ways
SELECT COUNT(*) AS rows_lost_or_added FROM (
(SELECT student_id, full_name, email, join_year, dept_id FROM inter.students
EXCEPT
SELECT c.student_id, c.full_name, c.email, a.join_year, a.dept_id
FROM lab4.students_contact c JOIN lab4.students_academic a USING (student_id))
UNION ALL
(SELECT c.student_id, c.full_name, c.email, a.join_year, a.dept_id
FROM lab4.students_contact c JOIN lab4.students_academic a USING (student_id)
EXCEPT
SELECT student_id, full_name, email, join_year, dept_id FROM inter.students)
) diff; -- 0Correction to the notes
The Module IV lecture notes' “approaches of query optimization” swaps the two definitions. Horizontal partitioning splits a table by rows; vertical partitioning splits it by columns.
- ▸Horizontal = rows (selection, rebuilt by UNION). Vertical = columns + key (projection, rebuilt by JOIN). Hybrid = both.
- ▸Correctness: completeness, reconstruction, disjointness.
- ▸Derived horizontal fragmentation splits a child table to follow its parent’s fragments.
4.7 Replication & Allocation
| Design alternative | What is stored where | Good for |
|---|---|---|
| Non-replicated, non-fragmented | Each whole table at exactly one site, near where it is used most | Few queries join tables from different sites |
| Fully replicated | Every site holds a copy of the whole database | Many reads, few updates — reads are local, but every update must reach every site |
| Partially replicated | Copies of some tables or fragments, placed by access frequency | Mixed workloads |
| Fragmented | Each fragment at one site, with no copies | Data that is naturally local; better parallelism |
| Mixed | Fragment first, then replicate some fragments | Large real systems |
| Synchronous replication | Asynchronous replication | |
|---|---|---|
| When copies are updated | Inside the same transaction — the commit waits for the replicas | After the commit, in the background |
| Copies are | Always identical | Briefly stale (replication lag) |
| Cost | Slower commits; a down replica can block updates | Fast commits; a failure can lose the latest changes |
| In PostgreSQL | synchronous_standby_names set | The default for streaming and logical replication |
With primary-copy replication one site holds the master copy and accepts updates; the others are read-only replicas. In multi-master replication any copy may be updated, and conflicts must be resolved.
A real replica needs a second server. A materialized view behaves the same way on one server: it is a copy that only catches up when refreshed — so you can watch the lag happen.
CREATE MATERIALIZED VIEW lab4.courses_replica AS SELECT * FROM inter.courses;
BEGIN;
UPDATE inter.courses SET title = 'Advanced Database Systems' WHERE course_code = 'CS201';
SELECT (SELECT title FROM inter.courses WHERE course_code = 'CS201') AS primary_copy,
(SELECT title FROM lab4.courses_replica WHERE course_code = 'CS201') AS replica;
primary_copy | replica
---------------------------+------------------
Advanced Database Systems | Database Systems <- replication lag
REFRESH MATERIALIZED VIEW lab4.courses_replica; -- the replica catches up
-- now both columns show 'Advanced Database Systems'
ROLLBACK; -- undo the change (and the refresh)SELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;| Fragment | Reads/day at Site 1 | Reads/day at Site 2 | Updates/day | Decision |
|---|---|---|---|---|
| Course catalogue | 5,000 | 4,000 | 5 | Replicate at both sites — read everywhere, rarely changed |
| CS students | 3,000 | 20 | 200 | Store only at Site 1 |
| DA students | 30 | 2,500 | 150 | Store only at Site 2 |
| Fee payments | 10 | 10 | 3,000 | One copy, at the admin site — replication would make every update expensive |
- ▸Replication = copies for availability and fast reads; the cost is keeping them consistent.
- ▸Synchronous = copies always equal, slower commits. Asynchronous = fast commits, temporary lag.
- ▸Allocate by access pattern: replicate read-mostly data; keep update-heavy data at one site.
4.8 Distributed Query Processing
| Step | What happens |
|---|---|
| 1 · Query decomposition | Parse the SQL and rewrite it as relational algebra on the global relations. |
| 2 · Data localization | Replace each global relation by its fragments, and drop fragments that cannot contribute. |
| 3 · Global optimization | Choose where each operation runs and what to ship, to minimise total cost — mainly network transfer. |
| 4 · Local optimization | Each site optimises its own part, as a centralized DBMS would. |
Join strategies and the semijoin
To join tables stored at different sites you can ship a whole table to the other site, ship both to the site that asked the query, or use a semijoin: send only the join-column values across, so that the other site returns just the rows that will match.
Site 1 stores STUDENTS: 10,000 rows × 100 bytes = 1,000,000 bytes. Site 2 stores ENROLLMENTS. A query at Site 2 asks: names of the students enrolled in offering 42. Offering 42 has 50 enrollments; a student_id is 4 bytes and a name 30 bytes.
| Strategy | Data shipped | Bytes |
|---|---|---|
| Ship STUDENTS to Site 2, join there | The whole STUDENTS table | 1,000,000 |
| Semijoin | Site 2 → Site 1: the 50 student_ids (50 × 4 = 200). Site 1 → Site 2: the 50 matching (id, name) rows (50 × 34 = 1,700) | 1,900 |
The semijoin ships about 500 times less data. It pays off whenever only a small part of one table takes part in the join.
A second database, campus_b, plays Site 2 and stores the DA department's students. university_lab reaches it through a foreign data wrapper.
CREATE DATABASE campus_b;
\c campus_b
CREATE TABLE da_students (
student_id INTEGER PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(120) NOT NULL UNIQUE,
join_year INTEGER NOT NULL
);
\c university_labCREATE EXTENSION IF NOT EXISTS postgres_fdw;
CREATE SERVER site_b FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', port '5432', dbname 'campus_b');
CREATE USER MAPPING FOR CURRENT_USER SERVER site_b
OPTIONS (user 'postgres', password 'your-postgres-password');
IMPORT FOREIGN SCHEMA public LIMIT TO (da_students) FROM SERVER site_b INTO lab4;
-- the rows are written into campus_b, over the connection
INSERT INTO lab4.da_students (student_id, full_name, email, join_year)
SELECT s.student_id, s.full_name, s.email, s.join_year
FROM inter.students s JOIN inter.departments d ON d.dept_id = s.dept_id
WHERE d.dept_code = 'DA'; -- INSERT 0 2EXPLAIN (VERBOSE, COSTS OFF)
SELECT full_name FROM lab4.da_students WHERE join_year = 2024;
Foreign Scan on lab4.da_students
Output: full_name
Remote SQL: SELECT full_name FROM public.da_students WHERE ((join_year = 2024))SELECT d.full_name, c.course_code
FROM lab4.da_students d -- at Site 2
JOIN inter.enrollments e ON e.student_id = d.student_id -- local
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
ORDER BY 1, 2;
full_name | course_code
-----------------+-------------
Ananya Krishnan | DA301
Diya Nair | CS201
Diya Nair | DA301
-- EXPLAIN VERBOSE shows: Remote SQL: SELECT student_id, full_name FROM public.da_students- ▸Steps: decomposition → data localization → global optimization → local optimization.
- ▸Distributed cost = disk I/O + CPU + network transfer (usually the biggest) − parallel gain.
- ▸Semijoin: ship only the join column, get back only matching rows — cheap when few rows match.
4.9 Distributed Transactions & Concurrency Control
Locking
| Request ↓ / held → | Shared (S) held | Exclusive (X) held |
|---|---|---|
| Shared (S) — to read | ✓ granted | ✗ waits |
| Exclusive (X) — to write | ✗ waits | ✗ waits |
Two-phase locking (2PL): a transaction first only acquires locks (growing phase), then only releases them (shrinking phase). Strict 2PL holds write locks until commit — which is what PostgreSQL does with row locks.
| Distributed lock management | How | Trade-off |
|---|---|---|
| Centralized | One site handles every lock request | Simple, but that site is a bottleneck and a single point of failure |
| Primary copy | Each data item has a primary copy; its site handles that item’s locks | Spreads the load; the primary copy’s site matters |
| Fully distributed | Each site locks the copies it stores | No single point of failure; a write must lock every copy |
Distributed deadlock
Each site keeps a local waits-for graph. A global deadlock can exist even when no local graph has a cycle — T1 waits for T2 at Site 1 while T2 waits for T1 at Site 2. Detection:
- Centralized — all sites send their local graphs to one site, which looks for a global cycle.
- Hierarchical — sites are arranged in a tree; each sends its graph to its parent.
- Timeout — abort any transaction that waits too long.
Delays in sending the graphs can make the detector see a cycle that no longer exists — a phantom deadlock, which aborts a transaction for nothing.
| Step | Window A | Window B |
|---|---|---|
| 1 | BEGIN; UPDATE inter.course_offerings SET capacity = capacity + 1 WHERE room = 'LH-3'; | |
| 2 | UPDATE inter.course_offerings SET capacity = capacity + 5 WHERE room = 'LH-3';→ waits: A holds an exclusive lock on that row | |
| 3 | COMMIT; | B finishes. Capacity is 46 (40 + 1 + 5) — no lost update |
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 55) AS query
FROM pg_stat_activity WHERE wait_event_type = 'Lock';
pid | blocked_by | wait_event_type | query
------+------------+-----------------+---------------------------------------------------------
2324 | {47512} | Lock | UPDATE inter.course_offerings SET capacity = capacity +| Step | Window A | Window B |
|---|---|---|
| 1 | BEGIN; UPDATE … WHERE room = 'LH-3'; | |
| 2 | BEGIN; UPDATE … WHERE room = 'LH-2'; | |
| 3 | UPDATE … WHERE room = 'LH-2'; → waits for B | |
| 4 | UPDATE … WHERE room = 'LH-3'; → waits for A: a cycle | |
| 5 | After 1 s (deadlock_timeout) one of them gets:ERROR: deadlock detected | The other continues. ROLLBACK both to keep the sample data. |
-- Window A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT capacity FROM inter.course_offerings WHERE room = 'LH-3'; -- 40
-- Window B (autocommit)
UPDATE inter.course_offerings SET capacity = 41 WHERE room = 'LH-3';
-- Window A
UPDATE inter.course_offerings SET capacity = capacity + 1 WHERE room = 'LH-3';
ERROR: could not serialize access due to concurrent update
ROLLBACK;
-- put it back
UPDATE inter.course_offerings SET capacity = 40 WHERE room = 'LH-3';- ▸S locks share; X locks exclude. 2PL: grow, then shrink. Strict 2PL holds write locks until commit.
- ▸Distributed lock managers: centralized, primary copy, fully distributed.
- ▸Global deadlocks need a global waits-for graph (centralized or hierarchical), or timeouts; delays cause phantom deadlocks.
4.10 Distributed Recovery: Two-Phase & Three-Phase Commit
Local recovery first. Each site recovers from its own crashes with a write-ahead log (WAL): every change is written to the log before it reaches the data files, and periodic checkpoints mark how far back recovery must start. After a crash the site redoes the logged changes since the last checkpoint.
SELECT pg_current_wal_lsn(); -- 0/6571820
INSERT INTO lab4.attendance_log VALUES (0, 1, 1, DATE '2024-07-01', true);
SELECT pg_current_wal_lsn(); -- 0/65719A8 <- the change was logged first
CHECKPOINT;
SELECT checkpoint_lsn, redo_lsn FROM pg_control_checkpoint();
-- crash recovery would start redoing from redo_lsnTwo-phase commit
The site where the transaction started is the coordinator; the other sites are participants (subordinates).
- Coordinator sends PREPARE to every participant.
- Each participant force-writes a prepare (or abort) record to its log, then votes YES (or NO).
- All YES → coordinator force-writes commit and sends COMMIT. Any NO (or a timeout) → writes abort and sends ABORT.
- Participants force-write the decision, then send ACK.
- With every ACK in, the coordinator writes an end record.
Move Diya from Site 2 (campus_b) to a Site 1 table: delete her at Site 2 and insert her at Site 1 — both or neither. PREPARE TRANSACTION is a participant's YES vote: the work is saved to disk, ready to commit, but not yet visible. (This needs the setup step at the top of the module.)
CREATE TABLE lab4.site_a_students (
student_id INTEGER PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
email VARCHAR(120) NOT NULL UNIQUE
);
\c campus_b
BEGIN;
DELETE FROM da_students WHERE email = 'diya@duk.ac.in';
PREPARE TRANSACTION 'move_diya_b'; -- Site 2 votes YES
\c university_lab
BEGIN;
INSERT INTO lab4.site_a_students
SELECT student_id, full_name, email FROM inter.students WHERE email = 'diya@duk.ac.in';
PREPARE TRANSACTION 'move_diya_a'; -- Site 1 votes YES
SELECT gid, database FROM pg_prepared_xacts ORDER BY gid;
gid | database
-------------+----------------
move_diya_a | university_lab
move_diya_b | campus_b
SELECT COUNT(*) FROM lab4.site_a_students; -- 0: prepared, not yet committedCOMMIT PREPARED 'move_diya_a';
\c campus_b
COMMIT PREPARED 'move_diya_b';
\c university_lab
SELECT COUNT(*) FROM lab4.site_a_students; -- 1: Diya is at Site 1
SELECT COUNT(*) FROM lab4.da_students WHERE email = 'diya@duk.ac.in'; -- 0: and gone from Site 2\c campus_b
BEGIN;
UPDATE da_students SET join_year = 2025 WHERE email = 'ananya@duk.ac.in';
PREPARE TRANSACTION 'fix_year_b'; -- Site 2 votes YES
\c university_lab
BEGIN;
INSERT INTO lab4.site_a_students -- Diya is already there: this must fail
SELECT student_id, full_name, email FROM inter.students WHERE email = 'diya@duk.ac.in';
ERROR: duplicate key value violates unique constraint "site_a_students_pkey"
PREPARE TRANSACTION 'fix_year_a';
ROLLBACK <- a failed transaction cannot prepare: Site 1 votes NO
\c campus_b
ROLLBACK PREPARED 'fix_year_b'; -- so the coordinator aborts Site 2 as wellThe weakness of 2PC: blocking
Once a participant has voted YES it may not decide on its own — it must wait for the coordinator. If the coordinator crashes now, the participant is in doubt and keeps holding its locks. You can see this in PostgreSQL: while fix_year_b was prepared, another session trying to change Ananya's row would wait until the decision arrived:
SET lock_timeout = '2s';
UPDATE da_students SET full_name = 'Ananya K.' WHERE email = 'ananya@duk.ac.in';
ERROR: canceling statement due to lock timeoutA prepared transaction even survives a server restart, still holding its locks, until someone runs COMMIT PREPARED or ROLLBACK PREPARED.
Three-phase commit (3PC)
3PC removes blocking when the coordinator fails by adding a step between voting and committing. After collecting all YES votes the coordinator sends PRE-COMMIT; only when enough participants have acknowledged it (more than the number of failures to be tolerated) does it force-write commit and send COMMIT. Because every pre-committed participant knows the decision will be commit, the survivors can finish the transaction without the coordinator. The cost is an extra round of messages, so 3PC is rarely used in practice.
| 2PC | 3PC | |
|---|---|---|
| Phases | Prepare → commit / abort | Prepare → pre-commit → commit |
| Messages | Fewer | An extra round |
| If the coordinator fails after the votes | Participants block (in doubt) | Participants can decide among themselves |
| Used in | Most databases (PostgreSQL’s PREPARE TRANSACTION, XA) | Mostly theory and specialised systems |
- ▸Local recovery: write-ahead log + checkpoints; redo from the last checkpoint after a crash.
- ▸2PC: Phase 1 PREPARE → votes; Phase 2 COMMIT (all YES) or ABORT (any NO) → ACKs → end.
- ▸2PC blocks if the coordinator fails after the votes; 3PC adds PRE-COMMIT to avoid that.
Tidy up after the lab
SELECT gid FROM pg_prepared_xacts; -- should be empty; finish any left with ROLLBACK PREPARED
DROP SCHEMA lab4 CASCADE; -- practice tables, fragments, replica, foreign table
DROP SERVER site_b CASCADE; -- the connection to campus_b and its user mapping
DROP DATABASE campus_b; -- Site 2
DROP EXTENSION postgres_fdw;Module 4A at a glance
| Topic | One-line answer |
|---|---|
| Parallel architectures | Shared memory, shared disk, shared nothing (scales best). |
| Parallel evaluation | Inter-query = throughput; intra-query (intra-/inter-operation) = response time. |
| Parallel operations | Partition (round-robin, hash, range); parallel sort by range; parallel join by hash or broadcast. |
| Distributed DB | Inter-related databases over a network, made transparent by a DDBMS. |
| Types | Homogeneous (autonomous / non-autonomous) vs heterogeneous (federated / un-federated). |
| Architectures | Client-server, collaborating servers (peer-to-peer), middleware / multi-DBMS. |
| Fragmentation | Horizontal (rows), vertical (columns + key), hybrid; complete, reconstructable, disjoint. |
| Replication | Copies for availability and speed; synchronous vs asynchronous; allocate by access pattern. |
| Distributed queries | Decompose, localize, optimize globally and locally; minimise shipping (semijoins). |
| Concurrency | Distributed 2PL with centralized / primary-copy / distributed lock managers; global deadlock detection. |
| Recovery | WAL locally; 2PC for atomic commit (blocks if the coordinator fails); 3PC avoids blocking. |
Practice
Measure the gain from parallelism
EasyFragment the courses horizontally
MediumFragment the faculty vertically
MediumSemijoin or not?
HardWhat if the coordinator crashes?
HardExam-style questions
- Define a distributed database.
- Differentiate inter-query and intra-query parallelism.
- What is data skew?
- State the three correctness rules of fragmentation.
- What is a semijoin?
- What is a phantom deadlock?
- Explain the parallel database architectures with diagrams.
- Explain how sorting and joins are parallelized.
- Explain fragmentation and replication, with the design alternatives.
- Explain the steps of distributed query processing, with a cost example.
- Explain distributed concurrency control and deadlock detection.
- Explain two-phase and three-phase commit.
