Digital University Kerala

SQL Lab Notes

PostgreSQL for Data Analytics

Course Instructor:Dr. Ajith Kumar
Academic Year: 2026-2028
Class Notes/Module 4A
Module 4A · CO4 · Lecture notes: Module IV · Labs 6, 7

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.

🎯 After this module you can
  • ▸ 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
🏫 Examples use

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.

Set up the database first →

One-time setup for this module's lab

Run in psql, connected to university_labsql
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;                       -- 10

4.1 Architectures for Parallel Databases

📖 Definition · Parallel database system
A database system that uses many processors and disks at the same time to load data, build indexes and evaluate queries faster. Its goal is performance on large data; a distributed database's goal is spreading data across sites (4.4).

Parallel architectures differ in what the processors (P) share: the memory (M), the disks (D), or nothing at all.

Shared memory
PPPP
interconnection network
M
DD
All processors use one memory and one set of disks.
Shared disk
PPPP
MMMM
interconnection network
DDD
Each processor has its own memory; all share the disks.
Shared nothing
PMD
PMD
PMD
interconnection network
Each node has its own processor, memory and disk.
Figure 4.1 — The three parallel database architectures
Shared memoryShared diskShared nothing
SharedMemory and disksDisks onlyNothing — nodes talk over the network
AdvantagesSimple; processors communicate fast through memoryA failed processor does not stop the system; memory is not a bottleneckScales to hundreds of nodes; only data a node lacks crosses the network
DisadvantagesThe memory bus becomes a bottleneck; adding processors slows the others; cache coherency neededThe disk interconnect becomes a bottleneck; inter-processor communication is slowReading another node’s data is costly; data must be partitioned well
Scales toTens of processorsMore than shared memoryHundreds or thousands of nodes
ExamplesA multi-core server running PostgreSQLOracle RAC; DEC VMScluster running RdbTeradata, Tandem; Greenplum and Citus (built on PostgreSQL)
🏫 Example · PostgreSQL on one server is a shared-memory system

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:

Parallelism settingssql
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)
✅ Remember
  • ▸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

📖 Definition
Parallel query evaluation runs query work on several processors at once. Inter-query parallelism runs different queries at the same time; intra-query parallelism splits one query across processors.
Inter-query parallelismIntra-query parallelism
What runs in parallelDifferent queries or transactionsParts of the same query
ImprovesThroughput — more queries finished per secondResponse time — each query finishes sooner
Example6 students each run a 3-second query: on 6 processors all 6 finish in about 3 s instead of 18 sOne 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.

🏫 Example · intra-query parallelism in PostgreSQL
A million-row practice table in the lab4 schema (about 50 MB)sql
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: two workers plus the leader each scan a third of the tablesql
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.

✅ Remember
  • ▸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

📖 Definition
In a shared-nothing system each relational operation is split so that every processor works on its own partition of the data. Data is partitioned by round-robin, hash (a hash of a key) or range (value ranges of a key).
OperationHow it is parallelized
ScanningEach processor reads the pages of its own partition; the results are merged.
Bulk loadingRows are partitioned to the nodes and loaded in parallel; sorting for index building is done in parallel too.
Sorting1) 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.
JoiningPartition 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.

Processor 1: student_id mod 3 = 0
students with ids 3, 6
enrollments of those students
→ joins its own pair locally
Processor 2: student_id mod 3 = 1
students with ids 1, 4
enrollments of those students
→ joins its own pair locally
Processor 3: student_id mod 3 = 2
students with ids 2, 5
enrollments of those students
→ joins its own pair locally
The same hash function sends each student and all their enrollments to the same processor; the three results are simply combined.
Figure 4.2 — A parallel hash join of students and enrollments on 3 processors
🏫 Example · parallel sort and parallel join in PostgreSQL
Parallel sort: each process sorts its share; Gather Merge merges the sorted streamssql
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_log
Parallel hash join: both sides scanned in parallel, one shared hash tablesql
EXPLAIN (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 b
When one table is tiny, each worker simply gets its own copy of itsql
EXPLAIN (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 worker

That last plan is the fragment-and-replicate (broadcast) strategy: split the big table, copy the small one everywhere — no need to partition both.

✅ Remember
  • ▸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

📖 Definition · Distributed database (DDB)
A collection of multiple, logically inter-related databases spread over a computer network. A distributed DBMS (DDBMS) is the software that manages it and makes the distribution transparent — users see one database.

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.

GoalMeaning
ReliabilityIf one site fails, the others keep working.
AvailabilityData stays reachable — from a replica — even when a site is down.
PerformanceData sits close to where it is used, and sites work in parallel.
Local autonomyEach site controls and manages its own data.
ScalabilityGrow by adding sites, not by replacing one big server.
TransparencyThe user need not know…
Locationwhere (at which site) the data is stored
Fragmentationthat a table is split into fragments
Replicationthat copies of the data exist
Network / failureabout the network, or that a site has failed
TypeDescriptionSub-types
HomogeneousEvery site runs the same DBMS (same vendor) and similar software; sites know each other and cooperate; users see a single databaseAutonomous — independent DBMSs integrated by an application, sharing updates by messages. Non-autonomous — a central (master) DBMS coordinates updates
HeterogeneousSites run different DBMSs, data models, schemas or operating systems; query and transaction processing are harder; sites may not know each otherFederated — independent systems integrated to act as one. Un-federated — accessed through a central coordinating module
Global schema — what users see
one university database: students, courses, enrollments…
Site 1 · Main campus
PostgreSQL · CS students, courses
Site 2 · Regional centre
PostgreSQL · DA students
Site 3 · Admin office
PostgreSQL · fees, payments
Figure 4.3 — A distributed database: one global view over local databases at several sites
✅ Remember
  • ▸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

📖 Definition
A DDBMS architecture describes how work is divided between the sites. Designs vary along three dimensions: distribution (where the data is), autonomy (how independently each site runs) and heterogeneity (how different the sites are).
ArchitectureHow it worksNotes
Client-serverClients handle the user interface; servers manage data, process queries and run transactions. Single-server/multi-client or multi-server/multi-clientA 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 answersUses four schema levels: global conceptual, local conceptual, local internal, and external (user views)
Middleware / multi-DBMSA separate software layer accepts a query that spans many servers and coordinates them; the servers themselves need no multi-site abilitiesGood for integrating legacy systems. Multi-DBMS schema levels: multi-database view, conceptual and internal; local view, conceptual and internal
🏫 Example · PostgreSQL as a collaborating server

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.

✅ Remember
  • ▸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

📖 Definition · Fragmentation
Splitting a relation into smaller pieces — fragments — that can be stored at different sites, usually where each piece is used most.
KindSplits the table byDefined withRebuilt with
HorizontalRows — each fragment is a subset of the rowsA selection: σ dept = ’CS’ (students)UNION of the fragments
Derived horizontalRows of a child table, following its parent’s fragmentsA semijoin: enrollments of CS studentsUNION
VerticalColumns — each fragment is a subset of the columns plus the primary keyA projection: π student_id, full_name, email (students)JOIN on the primary key
Hybrid (mixed)Both: rows, then columns (or the reverse)Selection + projectionJOINs and UNIONs
Correctness ruleMeaning
CompletenessEvery row (or column) of the table appears in at least one fragment — nothing is lost.
ReconstructionThe original table can be rebuilt exactly: UNION for horizontal, a lossless JOIN for vertical.
DisjointnessA row appears in only one horizontal fragment; for vertical fragments only the key is repeated.
Horizontal — by department (rows)
CS fragment → Site 1: Aarav, Rohan, Kevin
DA fragment → Site 2: Diya, Ananya
MA fragment → Site 3: Fatima
Vertical — by use (columns)
contact (student_id, full_name, email) → front office
academic (student_id, join_year, dept_id) → academic section
Figure 4.4 — Horizontal and vertical fragments of students
🏫 Example · horizontal fragments with partitioning
One partition per department — each could live on a different sitesql
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 |        1
Only the fragment that can hold the answer is read (partition pruning)sql
EXPLAIN (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)
Completeness: a row that fits no fragment is refusedsql
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).
🏫 Example · vertical fragments, rebuilt by a join
Split students by columns; both fragments keep the keysql
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;                                                      -- 0

Correction 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.

✅ Remember
  • ▸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

📖 Definition · Replication
Storing copies of a table or fragment at several sites — for higher availability and faster reads, at the price of keeping the copies consistent when data changes.
📖 Definition · Allocation
Deciding which site stores each fragment and each copy, based on where the data is read and updated, and how much the network costs.
Design alternativeWhat is stored whereGood for
Non-replicated, non-fragmentedEach whole table at exactly one site, near where it is used mostFew queries join tables from different sites
Fully replicatedEvery site holds a copy of the whole databaseMany reads, few updates — reads are local, but every update must reach every site
Partially replicatedCopies of some tables or fragments, placed by access frequencyMixed workloads
FragmentedEach fragment at one site, with no copiesData that is naturally local; better parallelism
MixedFragment first, then replicate some fragmentsLarge real systems
Synchronous replicationAsynchronous replication
When copies are updatedInside the same transaction — the commit waits for the replicasAfter the commit, in the background
Copies areAlways identicalBriefly stale (replication lag)
CostSlower commits; a down replica can block updatesFast commits; a failure can lose the latest changes
In PostgreSQLsynchronous_standby_names setThe 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.

🏫 Example · an asynchronous replica, simulated with a materialized view

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.

The copy is stale until it is refreshedsql
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)
On a real primary server, replicas are listed here (empty on a single server)sql
SELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;
🏫 Example · an allocation decision
FragmentReads/day at Site 1Reads/day at Site 2Updates/dayDecision
Course catalogue5,0004,0005Replicate at both sites — read everywhere, rarely changed
CS students3,00020200Store only at Site 1
DA students302,500150Store only at Site 2
Fee payments10103,000One copy, at the admin site — replication would make every update expensive
✅ Remember
  • ▸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

📖 Definition
Turning a query on the global relations into an efficient plan on the fragments at each site. Besides disk I/O and CPU, the cost now includes the data shipped over the network — often the largest part — and the gain from sites working in parallel.
StepWhat happens
1 · Query decompositionParse the SQL and rewrite it as relational algebra on the global relations.
2 · Data localizationReplace each global relation by its fragments, and drop fragments that cannot contribute.
3 · Global optimizationChoose where each operation runs and what to ship, to minimise total cost — mainly network transfer.
4 · Local optimizationEach 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.

🏫 Example · counting the bytes

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.

StrategyData shippedBytes
Ship STUDENTS to Site 2, join thereThe whole STUDENTS table1,000,000
SemijoinSite 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.

🏫 Example · a real distributed query with postgres_fdw

A second database, campus_b, plays Site 2 and stores the DA department's students. university_lab reaches it through a foreign data wrapper.

1 · Create Site 2 and its tablesql
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_lab
2 · Connect university_lab to Site 2 and ship the DA fragment theresql
CREATE 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 2
3 · The filter is shipped to Site 2 — only matching rows come backsql
EXPLAIN (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))
4 · A join across sites — only the two needed columns are fetched from Site 2sql
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
✅ Remember
  • ▸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

📖 Definition · Distributed transaction
A transaction submitted at one site that reads or writes data at other sites. The transaction manager at the submitting site splits it into sub-transactions, one per site, and must make them all behave as one ACID transaction.

Locking

Request ↓ / held →Shared (S) heldExclusive (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 managementHowTrade-off
CentralizedOne site handles every lock requestSimple, but that site is a bottleneck and a single point of failure
Primary copyEach data item has a primary copy; its site handles that item’s locksSpreads the load; the primary copy’s site matters
Fully distributedEach site locks the copies it storesNo 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.

🏫 Example · locking, deadlock and isolation — open two psql windows
StepWindow AWindow B
1BEGIN; UPDATE inter.course_offerings SET capacity = capacity + 1 WHERE room = 'LH-3';
2UPDATE inter.course_offerings SET capacity = capacity + 5 WHERE room = 'LH-3';
→ waits: A holds an exclusive lock on that row
3COMMIT;B finishes. Capacity is 46 (40 + 1 + 5) — no lost update
While B is waiting, a third window can see who blocks whomsql
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 +
StepWindow AWindow B
1BEGIN; UPDATE … WHERE room = 'LH-3';
2BEGIN; UPDATE … WHERE room = 'LH-2';
3UPDATE … WHERE room = 'LH-2'; → waits for B
4UPDATE … WHERE room = 'LH-3'; → waits for A: a cycle
5After 1 s (deadlock_timeout) one of them gets:
ERROR: deadlock detected
The other continues. ROLLBACK both to keep the sample data.
REPEATABLE READ refuses an update based on a stale readsql
-- 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';
✅ Remember
  • ▸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

📖 Definition
Distributed recovery keeps a distributed transaction atomic: either every sub-transaction commits or none does — despite failures of sites, of network links, and lost messages. The standard tool is the two-phase commit (2PC) protocol.

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.

Watch the WAL move as you change data (your numbers will differ)sql
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_lsn

Two-phase commit

The site where the transaction started is the coordinator; the other sites are participants (subordinates).

Phase 1 · Voting (prepare)
  1. Coordinator sends PREPARE to every participant.
  2. Each participant force-writes a prepare (or abort) record to its log, then votes YES (or NO).
Phase 2 · Decision (commit / abort)
  1. All YES → coordinator force-writes commit and sends COMMIT. Any NO (or a timeout) → writes abort and sends ABORT.
  2. Participants force-write the decision, then send ACK.
  3. With every ACK in, the coordinator writes an end record.
Figure 4.5 — The two-phase commit protocol
🏫 Example · 2PC across two databases — you are the coordinator

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.)

Phase 1 — ask each site to preparesql
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 committed
Phase 2 — both voted YES, so commit at every sitesql
COMMIT 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
A NO vote: a participant fails, so the coordinator aborts everywheresql
\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 well

The 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 timeout

A 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.

2PC3PC
PhasesPrepare → commit / abortPrepare → pre-commit → commit
MessagesFewerAn extra round
If the coordinator fails after the votesParticipants block (in doubt)Participants can decide among themselves
Used inMost databases (PostgreSQL’s PREPARE TRANSACTION, XA)Mostly theory and specialised systems
✅ Remember
  • ▸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

Remove everything this module created (run in university_lab)sql
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

TopicOne-line answer
Parallel architecturesShared memory, shared disk, shared nothing (scales best).
Parallel evaluationInter-query = throughput; intra-query (intra-/inter-operation) = response time.
Parallel operationsPartition (round-robin, hash, range); parallel sort by range; parallel join by hash or broadcast.
Distributed DBInter-related databases over a network, made transparent by a DDBMS.
TypesHomogeneous (autonomous / non-autonomous) vs heterogeneous (federated / un-federated).
ArchitecturesClient-server, collaborating servers (peer-to-peer), middleware / multi-DBMS.
FragmentationHorizontal (rows), vertical (columns + key), hybrid; complete, reconstructable, disjoint.
ReplicationCopies for availability and speed; synchronous vs asynchronous; allocate by access pattern.
Distributed queriesDecompose, localize, optimize globally and locally; minimise shipping (semijoins).
ConcurrencyDistributed 2PL with centralized / primary-copy / distributed lock managers; global deadlock detection.
RecoveryWAL locally; 2PC for atomic commit (blocks if the coordinator fails); 3PC avoids blocking.

Practice

1

Measure the gain from parallelism

Easy
Run the GROUP BY query on lab4.attendance_log with EXPLAIN ANALYZE, once normally and once with max_parallel_workers_per_gather = 0. Note the execution times, the workers launched, and the loops value on the scan.
2

Fragment the courses horizontally

Medium
Create lab4.courses_h partitioned by department code with one partition per department, load it from inter.courses, and show with EXPLAIN that a query for 'MA' courses reads only one fragment.
3

Fragment the faculty vertically

Medium
Split inter.faculty into lab4.faculty_contact (faculty_id, full_name, email) and lab4.faculty_dept (faculty_id, dept_id). Prove the reconstruction is lossless.
4

Semijoin or not?

Hard
Site 1 stores FACULTY: 2,000 rows × 80 bytes. Site 2 stores COURSE_OFFERINGS. A query at Site 2 wants the names of faculty teaching in semester 2024-Odd: 1,000 offerings, taught by 400 different faculty. A faculty_id is 4 bytes and a name 30 bytes. Compare shipping FACULTY to Site 2 with a semijoin.
5

What if the coordinator crashes?

Hard
In 2PC, both participants have voted YES and then the coordinator crashes before sending its decision. What state are the participants in, what happens to their locks, and how would you finish the transaction by hand in PostgreSQL?

Exam-style questions

Short answer (2 marks)
  1. Define a distributed database.
  2. Differentiate inter-query and intra-query parallelism.
  3. What is data skew?
  4. State the three correctness rules of fragmentation.
  5. What is a semijoin?
  6. What is a phantom deadlock?
Long answer (5–10 marks)
  1. Explain the parallel database architectures with diagrams.
  2. Explain how sorting and joins are parallelized.
  3. Explain fragmentation and replication, with the design alternatives.
  4. Explain the steps of distributed query processing, with a cost example.
  5. Explain distributed concurrency control and deadlock detection.
  6. Explain two-phase and three-phase commit.