SlideShare a Scribd company logo
Huy Nguyen
CTO, Cofounder - Holistics Software
Cofounder, Grokking Vietnam
PostgreSQL Internals 101
/post:gres:Q:L/
About Me
Education:
● Pho Thong Nang Khieu, Tin 04-07
● National University of Singapore (NUS), Computer Science Major.
Work:
● Software Engineer Intern, SenseGraphics (Stockholm, Sweden)
● Software Engineer Intern, Facebook (California, US)
● Data Infrastructure Engineer, Viki (Singapore)
Now:
● Co-founder & CTO, Holistics Software
● Co-founder, Grokking Vietnam
huy@holistics.io facebook.com/huy bit.ly/huy-linkedin
● This talk covers a very small part of
PostgreSQL concepts/internals
● As with any RDBMS, PostgreSQL is a
complex system, and it’s still evolving.
● Mainly revolve around explaining
“Uber’s MySQL vs PostgreSQL”
article.
● Not Covered: Memory Management,
Query Planning, Replication, etc...
Agenda
● Uber’s Article
● Table Heap
● B-Tree Index
● MVCC
● MySQL Structure
● PostgreSQL vs MySQL
(Uber Use-case)
● Index-only Scan
● Heap-only Tuple (HOT)
Uber migrating from PostgreSQL to MySQL
Uber’s Use Case
● Table with lots of indexes (cover almost/all columns)
● Lots of UPDATEs
⇒ MySQL handles this better than PostgreSQL
● Read more here
● Everything is under base
directory ($PGDATA).
/var/lib/postgresql/
9.x/main
● Each database is a folder
name after its oid
Physical Structure
http://www.interdb.jp/pg/pgsql01.html
demodb=# select oid, relname, relfilenode
from pg_class where relname = 'test';
oid | relname | relfilenode
--------+---------+-------------
416854 | test | 416854
(1 row)
Physical Structure
Each table’s data is in 1 or multiple files (max 1GB each)
TRUNCATE table;
vs
DELETE FROM table;
demodb=# select oid, relname, relfilenode from pg_class where relname = 'test';
oid | relname | relfilenode
--------+---------+-------------
416854 | test | 416854
(1 row)
demodb=# truncate test;
TRUNCATE TABLE
INSERT 0 1
demodb=# select oid, relname, relfilenode from pg_class where relname = 'test';
oid | relname | relfilenode
--------+---------+-------------
416854 | test | 416857
(1 row)
Tuple Address (ctid)
ctid id name
(0, 2) 1 Alice
(0, 5) 2 Bob
(1, 3) 3 Charlie
ctid (tuple ID): a pair of (block,
location) to position the tuple in the
data file.
Heap Table Structure
Page: a block of content, default to 8KB
each.
Line pointers: 4-byte number address,
holds pointer to each tuple.
For tuple with size > 2KB, a special
storage method called TOAST is used.
● Problem: Someone reading data, while someone else is
writing to it
● Reader might see inconsistent piece of data
● MVCC: Allow reads and writes to happen concurrently
MVCC - Multi-version Concurrency Control
MVCC - Table
xmin xmax id name
1 5 1 Alice
2 3 2 Bob
3 2 Robert
4 3 Charlie
1. INSERT Alice
2. INSERT Bob
3. UPDATE Bob → Robert
4. INSERT Charlie
5. DELETE Alice
● xmin: transaction ID that inserts this tuple
● xmax: transaction that removes this tuple
INSERT
1
http://www.interdb.jp/pg/pgsql05.html
DELETE
1
http://www.interdb.jp/pg/pgsql05.html
UPDATE
http://www.interdb.jp/pg/pgsql05.html
Because each UPDATE creates new tuple (and marks old tuple
deleted), lots of UPDATEs will soon increase the table’s physical
size.
Table Bloat
Index (B-tree)
H
B
A C
Balanced search tree.
Root node and inner nodes
contain keys and pointers to lower
level nodes
Leaf nodes contain keys and
pointers to the heap (ctid)
When table has new tuples, new
tuple is added to index tree.
Heap
ctid
D
A1
…. ….
Write Amplifications
● Each UPDATE inserts new
tuple.
● New index tuples
● ⇒ multiple writes
● Extra overhead to
Write-ahead Log (WAL)
● Carried over through
network
● Applied on Slave
H
B
A C
Heap
ctid
D
A1
…. ….
MySQL / InnoDB
● MVCC: Inline update of tuples
● Table Layout: B+ tree on Primary Key
● Index: points to primary key
MySQL data is B+ Tree (on
primary key)
Leaf nodes contain actual rows
data
MySQL Table (B+ tree)
H
B
A C
row
data
...
primary key
MySQL Index
● MySQL: the node’s value
store primary key
● A lookup on secondary
index requires 2 index
traversals: secondary index
+ primary index.
H
B
A C
Table
D
A1
…. ….
primary key
https://blog.jcole.us/2013/01/10/btree-index-structures-in-innodb/
PostgreSQL vs MySQL (Uber case)
PostgreSQL MySQL
MVCC New Tuple Per UPDATE Inline update of tuple (with
rollback segments)
Index Lookup Store physical address (ctid) By primary key
Table Layout Heap-table structure Primary-key table structure
PostgreSQL vs MySQL (Uber case)
PostgreSQL MySQL
select on primary key log(N) + heap read log(n) + direct read
update Update all indexes;
1 data write
Do not update indexes;
2 data writes
select on index key log(n) + O(1) heap read log(n) + log(n) primary index
read
sequential scan Page sequential scan Index-order scan
Index-only Scan (Covering Index)
Index on (product_id, revenue)
SELECT SUM(revenue) FROM table WHERE product_id = 123
If the index itself has all the data needed,
no Heap Table lookup is required.
Visibility Map
Per table’s page
VM[i] is set: all tuples in page i are
visible to current transactions
VM is only updated by VACUUM
https://www.slideshare.net/pgdayasia/introduction-to-vacuum-freezing-and-xid
Heap-only Tuple (HOT)
● No new index needs to be updated
Conditions:
● Must not update a column that’s
indexed
● New tuple must be in the same
page
http://slideplayer.com/slide/9883483/
● Clean up dead tuples
● Freeze old tuples (prevent
transactions wraparound)
● VACUUM only frees old tuples
● VACUUM FULL reclaims old disk
spaces, but blocks writes
VACUUM
● Add a new column (safe)
● Add a column with a default (unsafe)
● Add a column that is non-nullable (unsafe)
● Drop a column (safe)
● Add a default value to an existing column (safe)
● Add an index (unsafe)
Safe & Unsafe Operations In PostgreSQL
http://leopard.in.ua/2016/09/20/safe-and-unsafe-operations-postgresql
References
● Why Uber Engineering switched from PostgreSQL to MySQL -
https://eng.uber.com/mysql-migration/
● PostgreSQL Documentations -
https://www.postgresql.org/docs/current/static/
● The Internals of PostgreSQL
http://www.interdb.jp/pg/
● http://leopard.in.ua/2016/09/20/safe-and-unsafe-operations-postgresql
● http://slideplayer.com/slide/9883483/
● https://www.slideshare.net/pgdayasia/introduction-to-vacuum-freezing-and
-xid
Huy Nguyen
Physical Structure
https://www.postgresql.org/docs/current/static/storage-file-layout.html
Transaction Isolation
BEGIN TRANSACTION;
SELECT * FROM table;
SELECT pg_sleep(10);
SELECT * FROM table;
COMMIT;
under READ COMMITTED, the second SELECT may return any data. A
concurrent transaction may update the record, delete it, insert new records.
The second select will always see the new data.
under REPEATABLE READ the second SELECT is guaranteed to see the
rows that has seen at first select unchanged. New rows may be added by a
concurrent transaction in that one minute, but the existing rows cannot be
deleted nor changed.
under SERIALIZABLE reads the second select is guaranteed to see exactly
the same rows as the first. No row can change, nor deleted, nor new rows
could be inserted by a concurrent transaction.
https://stackoverflow.com/questions/4034976/difference-between-read-commit-and-repeatable-read
PostgreSQL Processes
There are multiple processes handling different
use cases.
● postmaster process: handles database
cluster management.
● Many backend processes (one for each
connection)
● Background processes: stats collector,
autovacuum, checkpoint, WAL writer, etc.
http://www.interdb.jp/pg/pgsql02.html
Database Cluster
● database cluster: a database
instance in a single machine.
● A database contains many
database objects (schema, table,
index, view, function, etc)
● Each object is represented by an
oid
Database Cluster
Database 1 Database 2 Database n...
tables indexes
views,
materialized
views
functions
schema
sequences
...
role
(user/group

More Related Content

What's hot (20)

PDF
08 subprograms
baran19901990
 
PDF
Concurrency
Sri Prasanna
 
PPTX
Understanding DPDK
Denys Haryachyy
 
PPTX
Bgp protocol
Smriti Tikoo
 
PPTX
Application Layer
Dr Shashikant Athawale
 
PPTX
Cyclic Redundancy Check in Computers Network
ShivangiTak1
 
PDF
Overview of SCTP (Stream Control Transmission Protocol)
Peter R. Egli
 
PPTX
Link state routing protocol
Aung Thu Rha Hein
 
PPTX
Routing Information Protocol
Kashif Latif
 
PPT
Ftp
Pablo
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PPT
Using an FTP client - Client server computing
lordmwesh
 
PDF
Building beautiful apps with Google flutter
Ahmed Abu Eldahab
 
PDF
TCP - IP Presentation
Harish Chand
 
PDF
MPLS Tutorial
kennedy Ochieng Ndire
 
PDF
Sun RPC (Remote Procedure Call)
Peter R. Egli
 
PPTX
Compiler construction tools
Akhil Kaushik
 
08 subprograms
baran19901990
 
Concurrency
Sri Prasanna
 
Understanding DPDK
Denys Haryachyy
 
Bgp protocol
Smriti Tikoo
 
Application Layer
Dr Shashikant Athawale
 
Cyclic Redundancy Check in Computers Network
ShivangiTak1
 
Overview of SCTP (Stream Control Transmission Protocol)
Peter R. Egli
 
Link state routing protocol
Aung Thu Rha Hein
 
Routing Information Protocol
Kashif Latif
 
Ftp
Pablo
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
Using an FTP client - Client server computing
lordmwesh
 
Building beautiful apps with Google flutter
Ahmed Abu Eldahab
 
TCP - IP Presentation
Harish Chand
 
MPLS Tutorial
kennedy Ochieng Ndire
 
Sun RPC (Remote Procedure Call)
Peter R. Egli
 
Compiler construction tools
Akhil Kaushik
 

Similar to Grokking TechTalk #20: PostgreSQL Internals 101 (20)

PDF
Наш ответ Uber’у
IT Event
 
PPTX
Migrating To PostgreSQL
Grant Fritchey
 
PPTX
PostgreSQL Terminology
Showmax Engineering
 
PDF
Our answer to Uber
Alexander Korotkov
 
PDF
12 in 12 – A closer look at twelve or so new things in Postgres 12
BasilBourque1
 
PDF
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
anandology
 
PDF
PostgreSQL 9.0 & The Future
Aaron Thul
 
PDF
An evening with Postgresql
Joshua Drake
 
KEY
PostgreSQL
Reuven Lerner
 
ODP
Introduction to PostgreSQL
Jim Mlodgenski
 
PPTX
PostgreSQL as NoSQL
Himanchali -
 
PDF
Bn 1016 demo postgre sql-online-training
conline training
 
PDF
Pg big fast ugly acid
Federico Campoli
 
PDF
PostgreSQL, your NoSQL database
Reuven Lerner
 
PPTX
PostgreSQL - Object Relational Database
Mubashar Iqbal
 
PDF
Postgres for MySQL (and other database) people
Command Prompt., Inc
 
PDF
PostgreSQL Prologue
Md. Golam Hossain
 
PPTX
PostgreSQL- An Introduction
Smita Prasad
 
PDF
Demystifying PostgreSQL
NOLOH LLC.
 
PDF
Demystifying PostgreSQL (Zendcon 2010)
NOLOH LLC.
 
Наш ответ Uber’у
IT Event
 
Migrating To PostgreSQL
Grant Fritchey
 
PostgreSQL Terminology
Showmax Engineering
 
Our answer to Uber
Alexander Korotkov
 
12 in 12 – A closer look at twelve or so new things in Postgres 12
BasilBourque1
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
anandology
 
PostgreSQL 9.0 & The Future
Aaron Thul
 
An evening with Postgresql
Joshua Drake
 
PostgreSQL
Reuven Lerner
 
Introduction to PostgreSQL
Jim Mlodgenski
 
PostgreSQL as NoSQL
Himanchali -
 
Bn 1016 demo postgre sql-online-training
conline training
 
Pg big fast ugly acid
Federico Campoli
 
PostgreSQL, your NoSQL database
Reuven Lerner
 
PostgreSQL - Object Relational Database
Mubashar Iqbal
 
Postgres for MySQL (and other database) people
Command Prompt., Inc
 
PostgreSQL Prologue
Md. Golam Hossain
 
PostgreSQL- An Introduction
Smita Prasad
 
Demystifying PostgreSQL
NOLOH LLC.
 
Demystifying PostgreSQL (Zendcon 2010)
NOLOH LLC.
 
Ad

More from Grokking VN (20)

PDF
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking VN
 
PDF
Grokking Techtalk #45: First Principles Thinking
Grokking VN
 
PDF
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking VN
 
PDF
Grokking Techtalk #43: Payment gateway demystified
Grokking VN
 
PPTX
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking VN
 
PPTX
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking VN
 
PDF
Grokking Techtalk #39: Gossip protocol and applications
Grokking VN
 
PDF
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking VN
 
PDF
Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking VN
 
PPTX
Grokking Techtalk #37: Data intensive problem
Grokking VN
 
PPTX
Grokking Techtalk #37: Software design and refactoring
Grokking VN
 
PDF
Grokking TechTalk #35: Efficient spellchecking
Grokking VN
 
PDF
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking VN
 
PDF
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking VN
 
PDF
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking VN
 
PDF
SOLID & Design Patterns
Grokking VN
 
PDF
Grokking TechTalk #31: Asynchronous Communications
Grokking VN
 
PDF
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking VN
 
PDF
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking VN
 
PDF
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking VN
 
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking VN
 
Grokking Techtalk #45: First Principles Thinking
Grokking VN
 
Grokking Techtalk #42: Engineering challenges on building data platform for M...
Grokking VN
 
Grokking Techtalk #43: Payment gateway demystified
Grokking VN
 
Grokking Techtalk #40: Consistency and Availability tradeoff in database cluster
Grokking VN
 
Grokking Techtalk #40: AWS’s philosophy on designing MLOps platform
Grokking VN
 
Grokking Techtalk #39: Gossip protocol and applications
Grokking VN
 
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking VN
 
Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking VN
 
Grokking Techtalk #37: Data intensive problem
Grokking VN
 
Grokking Techtalk #37: Software design and refactoring
Grokking VN
 
Grokking TechTalk #35: Efficient spellchecking
Grokking VN
 
Grokking Techtalk #34: K8S On-premise: Incident & Lesson Learned ZaloPay Mer...
Grokking VN
 
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Grokking VN
 
Grokking TechTalk #33: Architecture of AI-First Systems - Engineering for Big...
Grokking VN
 
SOLID & Design Patterns
Grokking VN
 
Grokking TechTalk #31: Asynchronous Communications
Grokking VN
 
Grokking TechTalk #30: From App to Ecosystem: Lessons Learned at Scale
Grokking VN
 
Grokking TechTalk #29: Building Realtime Metrics Platform at LinkedIn
Grokking VN
 
Grokking TechTalk #27: Optimal Binary Search Tree
Grokking VN
 
Ad

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 

Grokking TechTalk #20: PostgreSQL Internals 101

  • 1. Huy Nguyen CTO, Cofounder - Holistics Software Cofounder, Grokking Vietnam PostgreSQL Internals 101 /post:gres:Q:L/
  • 2. About Me Education: ● Pho Thong Nang Khieu, Tin 04-07 ● National University of Singapore (NUS), Computer Science Major. Work: ● Software Engineer Intern, SenseGraphics (Stockholm, Sweden) ● Software Engineer Intern, Facebook (California, US) ● Data Infrastructure Engineer, Viki (Singapore) Now: ● Co-founder & CTO, Holistics Software ● Co-founder, Grokking Vietnam [email protected] facebook.com/huy bit.ly/huy-linkedin
  • 3. ● This talk covers a very small part of PostgreSQL concepts/internals ● As with any RDBMS, PostgreSQL is a complex system, and it’s still evolving. ● Mainly revolve around explaining “Uber’s MySQL vs PostgreSQL” article. ● Not Covered: Memory Management, Query Planning, Replication, etc... Agenda ● Uber’s Article ● Table Heap ● B-Tree Index ● MVCC ● MySQL Structure ● PostgreSQL vs MySQL (Uber Use-case) ● Index-only Scan ● Heap-only Tuple (HOT)
  • 4. Uber migrating from PostgreSQL to MySQL
  • 5. Uber’s Use Case ● Table with lots of indexes (cover almost/all columns) ● Lots of UPDATEs ⇒ MySQL handles this better than PostgreSQL ● Read more here
  • 6. ● Everything is under base directory ($PGDATA). /var/lib/postgresql/ 9.x/main ● Each database is a folder name after its oid Physical Structure http://www.interdb.jp/pg/pgsql01.html
  • 7. demodb=# select oid, relname, relfilenode from pg_class where relname = 'test'; oid | relname | relfilenode --------+---------+------------- 416854 | test | 416854 (1 row) Physical Structure Each table’s data is in 1 or multiple files (max 1GB each)
  • 9. demodb=# select oid, relname, relfilenode from pg_class where relname = 'test'; oid | relname | relfilenode --------+---------+------------- 416854 | test | 416854 (1 row) demodb=# truncate test; TRUNCATE TABLE INSERT 0 1 demodb=# select oid, relname, relfilenode from pg_class where relname = 'test'; oid | relname | relfilenode --------+---------+------------- 416854 | test | 416857 (1 row)
  • 10. Tuple Address (ctid) ctid id name (0, 2) 1 Alice (0, 5) 2 Bob (1, 3) 3 Charlie ctid (tuple ID): a pair of (block, location) to position the tuple in the data file.
  • 11. Heap Table Structure Page: a block of content, default to 8KB each. Line pointers: 4-byte number address, holds pointer to each tuple. For tuple with size > 2KB, a special storage method called TOAST is used.
  • 12. ● Problem: Someone reading data, while someone else is writing to it ● Reader might see inconsistent piece of data ● MVCC: Allow reads and writes to happen concurrently MVCC - Multi-version Concurrency Control
  • 13. MVCC - Table xmin xmax id name 1 5 1 Alice 2 3 2 Bob 3 2 Robert 4 3 Charlie 1. INSERT Alice 2. INSERT Bob 3. UPDATE Bob → Robert 4. INSERT Charlie 5. DELETE Alice ● xmin: transaction ID that inserts this tuple ● xmax: transaction that removes this tuple
  • 17. Because each UPDATE creates new tuple (and marks old tuple deleted), lots of UPDATEs will soon increase the table’s physical size. Table Bloat
  • 18. Index (B-tree) H B A C Balanced search tree. Root node and inner nodes contain keys and pointers to lower level nodes Leaf nodes contain keys and pointers to the heap (ctid) When table has new tuples, new tuple is added to index tree. Heap ctid D A1 …. ….
  • 19. Write Amplifications ● Each UPDATE inserts new tuple. ● New index tuples ● ⇒ multiple writes ● Extra overhead to Write-ahead Log (WAL) ● Carried over through network ● Applied on Slave H B A C Heap ctid D A1 …. ….
  • 20. MySQL / InnoDB ● MVCC: Inline update of tuples ● Table Layout: B+ tree on Primary Key ● Index: points to primary key
  • 21. MySQL data is B+ Tree (on primary key) Leaf nodes contain actual rows data MySQL Table (B+ tree) H B A C row data ... primary key
  • 22. MySQL Index ● MySQL: the node’s value store primary key ● A lookup on secondary index requires 2 index traversals: secondary index + primary index. H B A C Table D A1 …. …. primary key
  • 24. PostgreSQL vs MySQL (Uber case) PostgreSQL MySQL MVCC New Tuple Per UPDATE Inline update of tuple (with rollback segments) Index Lookup Store physical address (ctid) By primary key Table Layout Heap-table structure Primary-key table structure
  • 25. PostgreSQL vs MySQL (Uber case) PostgreSQL MySQL select on primary key log(N) + heap read log(n) + direct read update Update all indexes; 1 data write Do not update indexes; 2 data writes select on index key log(n) + O(1) heap read log(n) + log(n) primary index read sequential scan Page sequential scan Index-order scan
  • 26. Index-only Scan (Covering Index) Index on (product_id, revenue) SELECT SUM(revenue) FROM table WHERE product_id = 123 If the index itself has all the data needed, no Heap Table lookup is required.
  • 27. Visibility Map Per table’s page VM[i] is set: all tuples in page i are visible to current transactions VM is only updated by VACUUM https://www.slideshare.net/pgdayasia/introduction-to-vacuum-freezing-and-xid
  • 28. Heap-only Tuple (HOT) ● No new index needs to be updated Conditions: ● Must not update a column that’s indexed ● New tuple must be in the same page http://slideplayer.com/slide/9883483/
  • 29. ● Clean up dead tuples ● Freeze old tuples (prevent transactions wraparound) ● VACUUM only frees old tuples ● VACUUM FULL reclaims old disk spaces, but blocks writes VACUUM
  • 30. ● Add a new column (safe) ● Add a column with a default (unsafe) ● Add a column that is non-nullable (unsafe) ● Drop a column (safe) ● Add a default value to an existing column (safe) ● Add an index (unsafe) Safe & Unsafe Operations In PostgreSQL http://leopard.in.ua/2016/09/20/safe-and-unsafe-operations-postgresql
  • 31. References ● Why Uber Engineering switched from PostgreSQL to MySQL - https://eng.uber.com/mysql-migration/ ● PostgreSQL Documentations - https://www.postgresql.org/docs/current/static/ ● The Internals of PostgreSQL http://www.interdb.jp/pg/ ● http://leopard.in.ua/2016/09/20/safe-and-unsafe-operations-postgresql ● http://slideplayer.com/slide/9883483/ ● https://www.slideshare.net/pgdayasia/introduction-to-vacuum-freezing-and -xid
  • 34. Transaction Isolation BEGIN TRANSACTION; SELECT * FROM table; SELECT pg_sleep(10); SELECT * FROM table; COMMIT; under READ COMMITTED, the second SELECT may return any data. A concurrent transaction may update the record, delete it, insert new records. The second select will always see the new data. under REPEATABLE READ the second SELECT is guaranteed to see the rows that has seen at first select unchanged. New rows may be added by a concurrent transaction in that one minute, but the existing rows cannot be deleted nor changed. under SERIALIZABLE reads the second select is guaranteed to see exactly the same rows as the first. No row can change, nor deleted, nor new rows could be inserted by a concurrent transaction. https://stackoverflow.com/questions/4034976/difference-between-read-commit-and-repeatable-read
  • 35. PostgreSQL Processes There are multiple processes handling different use cases. ● postmaster process: handles database cluster management. ● Many backend processes (one for each connection) ● Background processes: stats collector, autovacuum, checkpoint, WAL writer, etc. http://www.interdb.jp/pg/pgsql02.html
  • 36. Database Cluster ● database cluster: a database instance in a single machine. ● A database contains many database objects (schema, table, index, view, function, etc) ● Each object is represented by an oid Database Cluster Database 1 Database 2 Database n... tables indexes views, materialized views functions schema sequences ... role (user/group