Monday, June 14, 2021

TRYING OUT POSTGRES BLOOM INDEXES

 First – if the word “Bloom” doesn’t yet resonate with you in Postgres context, I’d recommend to read my previous introductory post on the topic here. This one is a follow up with an aim to set up a simple demo use case to exemplify “fields of application” for Bloom and to also gauge pros/cons/performance in comparison to B-tree.

So to get started, we would first need some kind of “close to real life” test case to visualize and remember the problem better in our heads. As explained in the previous post – for Bloom to make sense, we would need a query/table with many columns which are queried in random combinations… but with only integer/text data types and equality operators, options are a bit limited. After scrolling around a bit I couldn’t spot any suitable test sets (for example from here), so I decided still to look at the ceiling and pictured a simple table from an online car dealership domain where Bloom would be a good fit in addition to being easily digestible for our brains.

The online car dealership

Schema (a single table) is described below, with the amount of distinct values in the comment. Choosing a domain where values are not too distinct should be a good example as B-tree indexes are not too effective there and we should benefit from Bloom. Also note the table is well normalized – we’re only dealing with numeric type codes and natural values so we can generate test data easily with random brand_codes from 0..199 etc. As size for test data – I decided to generate 5 million test rows (cars listed for sale, could even be a realistic number for bigger countries), giving us a 365 MB table which would fit nicely into shared buffers, removing disk access factor from the tests.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
create table vehicle (
 
id bigserial primary key,
 
brand_code int not null,  -- n_distinct 200, imagine “brand_code”=0 => “Audi”
 
model_code int not null,  -- n_distinct 25, “model_code”=0 => “Q7”
 
color_code int not null,  -- n_distinct 25, “color_code”=0 => “silver” etc...
 
year int not null,                   -- n_distinct 26
 
body_type_code int not null,          -- n_distinct 10
 
doors int not null,                 -- n_distinct 5
 
seats int not null,                  -- n_distinct 9
 
gearbox_code int not null,               -- n_distinct 3
 
fuel_type_code int not null,    -- n_distinct 10
 
aircon_type_code int not null    -- n_distinct 4
 
);
 
 
 
insert into vehicle (brand_code, model_code, color_code, year, body_type_code, doors, seats, gearbox_code, fuel_type_code, aircon_type_code)
 
select
 
random()*200, --brand
 
random()*25, --model
 
random()*25, --color
 
random()*26 + 1990, --year
 
random()*10, --body_type
 
random()*4 + 1, --doors
 
random()*8 + 1, --seats
 
random()*3, --gearbox
 
random()*10, --fuel
 
random()*4 --aircon
 
from
 
generate_series(1, 5*1e6);  --  5 mio rows
 
 
analyze vehicle;

Building the indexes

Again – idea for our “application” was that users issue queries using equality filters on many columns, meaning all columns need to be indexed for fast response times. So we index separately all columns with B-tree and then one Bloom index for all columns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CREATE INDEX ON vehicle(brand_code, model_code);
 
CREATE INDEX ON vehicle(color_code);
 
CREATE INDEX ON vehicle(year);
 
CREATE INDEX ON vehicle(body_type_code);
 
CREATE INDEX ON vehicle(doors);
 
CREATE INDEX ON vehicle(seats);
 
CREATE INDEX ON vehicle(gearbox_code);
 
CREATE INDEX ON vehicle(fuel_type_code);
 
CREATE INDEX ON vehicle(aircon_type_code);
 
 
 
CREATE INDEX bloom_80_bits ON vehicle USING bloom (brand_code,model_code,color_code,year,body_type_code,doors,seats,gearbox_code,fuel_type_code,aircon_type_code);

And the resulting index sizes: all B-tree indexes yield 107 MB, totalling to 963 MB, and Bloom yields 77 MB. Pretty impressive already – remember they should basically provide comparable outcomes for our queries!

Running a test query

Now to the interesting part – will queries profit from the Bloom index? Note that here I’m imposing some behaviour on our “users” for my contrived use case –  I will not use all 10 columns and leave out brand/model from the query as together they’re too selective, probably giving no chance to the “lossy” Bloom index. This could be translated so that our “users” are being pragmatic, knowing what  features they would want for their cars and set on utility first, not a flashy brand name 🙂 Note that selected code values are randomly chosen but as we have a random distribution with limited distinct values, playing with different numbers didn’t change the outcome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
select * from vehicle
 
where color_code = 12
 
and year > 2010
 
and body_type_code = 5
 
and doors = 4
 
and gearbox_code = 2
 
and fuel_type_code = 5
 
and aircon_type_code = 2;

* Run 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Bitmap Heap Scan on vehicle  (cost=22376.30..28976.90 rows=8 width=48) (actual time=130.326..132.075 rows=13 loops=1)
 
Recheck Cond: ((color_code = 12) AND (body_type_code = 5) AND (fuel_type_code = 5))
 
Filter: ((year > 2010) AND (doors = 4) AND (gearbox_code = 2) AND (aircon_type_code = 2))
 
Rows Removed by Filter: 2113
 
Heap Blocks: exact=2072
 
->  BitmapAnd  (cost=22376.30..22376.30 rows=1971 width=0) (actual time=129.832..129.832 rows=0 loops=1)
 
->  Bitmap Index Scan on vehicle_color_code_idx  (cost=0.00..3487.43 rows=188667 width=0) (actual time=50.499..50.499 rows=199791 loops=1)
 
Index Cond: (color_code = 12)
 
->  Bitmap Index Scan on vehicle_body_type_code_idx  (cost=0.00..9244.93 rows=500333 width=0) (actual time=33.992..33.992 rows=499668 loops=1)
 
Index Cond: (body_type_code = 5)
 
->  Bitmap Index Scan on vehicle_fuel_type_code_idx  (cost=0.00..9643.43 rows=522000 width=0) (actual time=33.622..33.622 rows=500561 loops=1)
 
Index Cond: (fuel_type_code = 5)
 
Planning time: 0.642 ms
 
Execution time: 132.150 ms

To my surprise still the B-tree indexes were used with a 130 ms average runtime for 5 runs. Hmm. Here we can see though that Postgres is smart enough to pick the most selective indexes and does a bitmap merge on only three indexes. Ok, seems that to test out Bloom we need to disable/delete the normal indexes still.

* Run 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Bitmap Heap Scan on vehicle  (cost=139220.00..139377.59 rows=8 width=48) (actual time=67.600..67.673 rows=13 loops=1)
 
Recheck Cond: ((color_code = 12) AND (body_type_code = 5) AND (doors = 4) AND (gearbox_code = 2) AND (fuel_type_code = 5) AND (aircon_type_code = 2))
 
Rows Removed by Index Recheck: 37
 
Filter: (year > 2010)
 
Rows Removed by Filter: 28
 
Heap Blocks: exact=78
 
->  Bitmap Index Scan on bloom_80_bits  (cost=0.00..139220.00 rows=40 width=0) (actual time=67.576..67.576 rows=78 loops=1)
 
Index Cond: ((color_code = 12) AND (body_type_code = 5) AND (doors = 4) AND (gearbox_code = 2) AND (fuel_type_code = 5) AND (aircon_type_code = 2))
 
Planning time: 0.270 ms
 
Execution time: 67.728 ms

Hurray, finally some progress after disabling the indexes! Seems that Bloom in our use case actually is a better choice – it is 2x faster and ~10x more space efficient! Only sad thing is that Postgres cannot correctly estimate that yet so one needs to point it out ourselves. But why is that? Because of the cost estimation mechanics of the Postgres planner. We can see that total cost (penalty points calculated for every operation) is bigger for the Bloom case (29K vs 139K)… albeit Bloom is faster in real time. And main costs come from Bitmap Index Scan on the Bloom index and the fact that currently the whole index needs to be scanned and all the 5 million signatures compared! One could of course fine tune parameters like cpu_tuple_cost etc. so that the planner would give Bloom the advantage, but that’s another topic and could heavily affect other well-working queries. For comparison by the way, a full table scan for our query (set enable_bitmapscan to off) takes about 500ms.

Tuning Bloom signature length

So after first “feedback” from Bloom I decided to see what is the practical outcome of changing the signature length. Trying out a relatively small value of 32 and a bit bigger 128, yielded sizes of 48 MB and 106 MB (5 Mio rows still). Note that the index size really doesn’t change linearly with the signature size as physical location info (6 bytes) already takes a considerable toll for every Bloom index entry.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
krl@postgres=# \di+ bloom_*
 
List of relations
 
Schema │      Name      │ Type  │ Owner │  Table   │  Size  │ Description
 
────────┼────────────────┼───────┼───────┼──────────┼────────┼─────────────
 
public │ bloom_128_bits │ index │ krl   │ vehicle  │ 106 MB │
 
public │ bloom_32_bits   │ index │ krl   │ vehicle  │ 48 MB   │
 
public │ bloom_80_bits   │ index │ krl   │ vehicle  │ 77 MB   │
 
(3 rows)

After executing the same EXPLAIN ANALYZE from above (not including output here for brevity), Postgres funnily enough decided to use the less precise (32 bits) index here, although we have a better (more precise) one available. To test my theory of improvement, I dropped the 32-bit one and indeed – runtime was decreased 2x, 137ms vs 65ms! Less heap pages to visit and tuples to recheck. Again Postgres could be a bit cleverer here, probably it just uses the smallest available index covering the queried columns as with B-tree.

Summary

Our example use case was not too exhaustive but hopefully close enough to real life so that you got an idea when to consider Bloom and what to take into account and what are the pros and cons. A list of things to remember:

  • Perfect for “checkbox” type of applications – lots of columns with little varying data (and lots of data rows). One could draw parallels to Oracle bitmap index use cases.
  • Index is lossy, meaning it may give false positives and instead of real column values, in the index there are signatures linked to tables via CTID-s as usual.
  • Be ready for some trial and error with Bloom – finding out optimal columns to include and signature length. But when applied appropriately one can easily gain 10x benefit (aggregating space and speed).
  • Currently only equality operations and int4 and text (a.k.a. varchar as they’re the same) data types are supported.
  • For 5m rows with 10 columns the default signature length of 80 bits was sufficient (limited nr. of  distinct values) and performed better than individual B-tree indexes being at the same time a lot smaller!
  • There’s probably some room for improvement in planner cost estimates for Bloom, so currently there’s no point to have both B-tree and Bloom indexes as B-tree is preferred.
  • What about unique values? ERROR:  access method “bloom” does not support unique indexes…
  • What about NULL-s? NULL-s are not indexed so all queries like “WHERE col IS NULL” can’t benefit from Bloom indexes.
  • Bloom is WAL logged and crash-safe (unlike Hash indexes), so you can rely on it.
  • Changing individual bit lengths is probably not worth the effort. Only makes sense for special cases where one of the columns has a lot of distinct values and others very few. Then in theory increasing bits for the distinct column should give you less rows thrown away during rechecking.
  • When specifying index signature bit length (… WITH (length=X)), bits are actually rounded up to full words (16 bits). Thus “length=33” bits ends up as “length=48” bits.

Friday, June 11, 2021

10 Things I Hate About PostgreSQL by Rick Branson

 Over the last few years, the software development community’s love affair with the popular open-source relational database has reached a bit of a fever pitch. This Hacker News thread covering a piece titled “PostgreSQL is the worlds’ best database”, busting at the seams with fawning sycophants lavishing unconditional praise, is a perfect example of this phenomenon.

While much of this praise is certainly well-deserved, the lack of meaningful dissent left me a bit bothered. No software is perfect, so exactly what are PostgreSQL’s imperfections?

I’ve been hands-on with PostgreSQL in production since 2003 with deployments ranging from small (gigabytes) to modest to very large (~petabyte). My perspective is largely from building and running systems that are at least intended to be continuously available. Needless to say, I have gained first-hand experience with PostgreSQL’s particular idiosyncrasies through some painful production issues over the years.

#1: Disastrous XID Wraparound

Read more here. Suffice to say, this one can bite hard. There are many stories of multi-day outages caused by this issue. Go ahead, Google it and you’ll find numerous poor souls writing about the time they stepped on this landmine. Pretty much any non-trivial PostgreSQL install that isn’t staffed with a top expert will run into it eventually.

It’s likely that, at some point in the future, XIDs will transition to use 64-bit integers, but until then, we’re stuck with it. I guess at least we can be thankful that there is a process which prevents it from happening as a matter of course, unlike some airplane software.

#2: Failover Will Probably Lose Data

The run-of-the-mill streaming replication setup will almost certainly lose committed data if the active master suddenly fails. “Such is the price of asynchronous replication,” some might say, but it doesn’t have to be this way. PostgreSQL supports synchronous replication with quorum commit for fault-tolerant durability, but it has a much tighter performance envelope that complicates its application.

Waiting doesn’t utilize system resources, but transaction locks continue to be held until the transfer is confirmed. As a result, incautious use of synchronous replication will reduce performance for database applications because of increased response times and higher contention.

This bolt-on quorum replication is useful in a pinch, but I hesitate to recommend it for general-purpose use cases. It is similar to Kafka’s ISR replication with acks=all and a quorum min_isr, but with all the nuanced complexity of a transactional relational database running arbitrary queries. I’m not currently aware of a successful application of quorum commit for highly-available, high-durability replication at non-trivial scale. If you have, reach out!

In terms of relational databases, Galera Cluster’s group replication is also imperfect, but closer to the ideal. They even encourage geo-distributed replication, which would very likely be disastrous for a PostgreSQL replication setup using quorum commit.

#3: Inefficient Replication That Spreads Corruption

Streaming Replication is by far the most utilized replication mechanism in production deployments. It is a form of physical replication, meaning that it replicates changes in the on-disk binary data itself.

Every time an on-disk database page (8KB) needs to be modified by a write operation, even just a single byte, a copy of the entire page, edited with the requested changes, is written to the write-ahead log (WAL). Physical streaming replication leverages this existing WAL infrastructure as a log of changes it streams to replicas.

Update: Some folks have pointed out that PostgreSQL only needs to do this full-page write once per WAL checkpoint. This is true, but in most real-world systems most writes will end up on a unique page between checkpoints, following a power law distribution. More importantly though: when anticipating system behavior, the right approach is assuming the more expensive case, particularly if it depends on hard-to-predict and highly dynamic behavior of the application.

With physical replication, a large index build, for instance, creates a huge flood of WAL entries which can easily bottleneck the replication stream. The read-modify-replicate process at page-granularity can lead to hardware-induced data corruption on the master much more easily propagating to replicas, which I’ve personally witnessed several times in production.

This is in contrast to logical replication, which only replicates logical data changes. At least theoretically, a large index build would only result in a single command replicated across the network. While PostgreSQL has supported logical replication for quite some time, most deployments use physical streaming replication because it is more robust, more broadly supported, and much easier to use.

#4: MVCC Garbage Frequently Painful

Like most mainstream databases, PostgreSQL uses multi-version concurrency control (MVCC) to implement concurrent transactions. However, its particular implementation often introduces operational pain around garbage row versions and their cleanup (VACUUM). Generally speaking, UPDATE operations create new copies (or “row versions”) of any modified rows, leaving the old versions on disk until they can be cleaned up.

While this situation has steadily improved over the years, it’s a complex system that is a bit of a black box for anyone approaching the problem for the first time. For instance, knowing about Heap-Only Tuples (HOT) and when it kicks in can be make-or-break for heavy update-in-place workloads like maintaining a consistent counter column in a row. The default autovacuum setup does work most of the time, but when it doesn’t, good lord.

In contrast, MySQL and Oracle use redo and undo logs. They don’t need a similar background garbage collection process. The trade-off they make is mostly additional latency for transactional commit and rollback operations.

It could be that at some point in the distant future, zheap saves us all.

#5: Process-Per-Connection = Pain at Scale

PostgreSQL forks a process for every connection, where as most other databases use a more efficient connection concurrency model. This makes for a difficult tuning problem as there is a relatively low threshold at which adding more connections degrades performance (around ~2x cores) and eventually another higher threshold (hard to estimate, highly workload dependent) where performance will plummet.

The standard recipe of using a connection pooler certainly kicks the can down the road, but introduces significant additional architectural complexity. On a particularly large deployment, I eventually had to layer in a second pgbouncer tier. One tier ran on the application servers and another tier on the database servers. Altogether it aggregated connections for around 1 million client processes. Tuning it was 40% dark art, 40% brute force, and 10% pure luck.

Process scalability has been getting incrementally better every major release, but ultimately there is a somewhat hard limit to the performance of this architecture compared to something like thread-per-connection, which is used in MySQL.

For more technical depth, see https://brandur.org/postgres-connections.

#6: Primary Key Index is a Space Hog

Tables in PostgreSQL have an index for the primary key and separate row storage called the heap. Other databases integrate these together or support “index-organized tables”. In this arrangement, the primary key lookup process leads directly to the row data without a secondary fetch to get the full row and the requisite additional CPU and I/O utilization.

The CLUSTER command in PostgreSQL reorganizes a table according to an index to improve performance, but doesn’t really work for most real-world OLTP cases. It rewrites the entire table under an exclusive lock, blocking any reads or writes. PostgreSQL doesn’t maintain the clustered layout for new data, so this operation must be ran periodically. So it is really only useful if you can take your database offline for long periods of time on a regular basis.

But more critically, index-organized tables save space as the index doesn’t require a separate copy of the row data. For tables with small rows that are mostly covered by the primary key, such as join tables, this can easily cut the table’s storage footprint in half.

Consider the following table which stores social “likes” for arbitrary objects:

CREATE TABLE likes (
object_type INTEGER NOT NULL,
object_id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY,
user_id BIGINT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY(object_type, object_id, user_id)
);

PostgreSQL will maintain an index for the primary key which is separate from the base table storage. This index will contain a full copy of the object_type, object_id, and user_id columns for every row. 20 out of 28 bytes in each row (~70%) will be duplicated. If PostgreSQL supported index-organized tables, it wouldn’t consume all that additional space.

#7: Major Version Upgrades Can Require Downtime

Some major version upgrades require hours of downtime to convert the data for a large database. Using the typical streaming replication mechanism, it is not possible to do this gracefully by upgrading a replica and doing a failover. The on-disk binary format is incompatible across major versions, thus the wire protocol between master and replica is effectively also incompatible.

Hopefully logical replication will eventually completely replace streaming replication, which would enable an online, rolling upgrade strategy. When I worked on a large-scale horizontally-scaled deployment, we made a significant engineering investment in custom infrastructure to do these upgrades without downtime using an additional trigger-based replication system that was also used for shard migration.

#8: Somewhat Cumbersome Replication Setup

To be fair, MySQL’s out-of-the-box replication is much more cumbersome, but compared to some NoSQL stores like MongoDB and Redis or some cluster-oriented replication systems like MySQL Group Replication and Galera Cluster, from an ease-of-use and sharp-edge-avoidance perspective, setting up replication in PostgreSQL leaves a lot to be desired. While logical replication theoretically provides far more flexibility for third-party solutions to paper over these gaps, so far it’s there are some pretty big caveats for using it in place of streaming replication.

#9: Ridiculous No-Planner-Hints Dogma

Planner hints allow queries to direct the query planner to use strategies it wouldn’t otherwise use on its own. In what seems to be a form of the sufficiently smart compiler argument, the PostgreSQL development team has held the line for years in refusing to support query planner hints.

I do understand their reasoning, which largely is about preventing users from attacking problems using query hints that should be fixed by writing proper queries. However, this philosophy seems brutally paternalistic when you’re watching a production database spiral into a full meltdown under a sudden and unexpected query plan shift.

In many of these situations, a hint to the planner can mitigate the issue in minutes, buying the engineering team the hours or days they need to make a proper fix to the query. While there are some indirect workarounds that involve disabling certain query planner strategies, they are risky and definitely shouldn’t be employed under any kind of time pressure.

That ivory tower sure must be nice.

#10: No Block Compression

InnoDB’s Page Compression in MySQL commonly cuts storage footprint in half and is pretty much “free” from a performance perspective. PostgreSQL will automatically compress large values but this isn’t useful for the most common ways data is stored in relational databases. For most RDBMS use cases, a row is typically a few hundred bytes or less, which means compression could only really be effective when applied across multiple rows, or in blocks.

Block compression is indeed quite difficult to implement for the kind of data structures at the heart of PostgreSQL, but the “hole punch” strategy employed by MySQL’s InnoDB storage engine seems to work quite well in practice, despite some drawbacks.

2020–04–07 Update: Mark Callaghan, of “MySQL at Facebook” fame, questioned my statement here that hole-punching compression works “quite well in practice.” It turns out that the largest MySQL installation in the world never used hole-punching compression, as I previously thought. They did successfully use a slightly modified version of the older generation of InnoDB compression with success, however, before migrating to MyRocks a few years ago.

While the hole-punching compression does seem to work for some folks, there are some caveats make it less of a home run. If you’re running Percona’s version of MySQL, MyRocks is a better bet. If not, it seems that the classic InnoDB table compression is a safer bet for very read-heavy workloads on flash storage. Mark didn’t point to any specific instances of major production issues, but does point out that he “doubts filesystems have been designed for hole punch per page and I would be afraid of obscure failures.”

The only general-purpose block compression setup widely used in the PostgreSQL world leverages ZFS, which does seem to work quite well for people. ZFS is a production-grade reality in Linux these days, but definitely brings with it some administrative overhead that doesn’t exist for the more “out-of-the-box” filesystems like XFS or ext4.

All That Said…

You should probably still use PostgreSQL and not something else for storing data that you’d ideally like to, you know, keep around for some time. In general I’d recommend starting with PostgreSQL and then trying to figure out why it won’t work for your use case.

PostgreSQL is very mature, well-engineered, richly-featured, is generally free of sharp edges, and is quite performant for the vast majority of use cases. It also is unencumbered by a dominant corporate sponsor, includes fantastic documentation, and has a professional, inclusive community.

The good news is that the pain caused by many of the issues brought up in this post can be reduced or eliminated by using a managed database service like Heroku PostgreSQL, Compose PostgreSQL, Amazon RDS for PostgreSQL, or Google Cloud SQL for PostgreSQL. If you can use one of these services, for the love of all that is holy, please do!

I’m proud to say I’ve built software on top of PostgreSQL for almost two decades and remain a strong advocate, despite its flaws. Given the progress I’ve witnessed over the years by its incredible development team, I can say that most, if not all of these issues will be resolved in due time.

Monday, June 7, 2021

PostgreSQL Concurrency with MVCC

 One of the big selling points of Postgres is how it handles concurrency. The promise is simple: reads never block writes and vice versa. Postgres achieves this via a mechanism called Multi Version Concurrency Control. This technique is not unique to Postgres: there are several databases that implement some form of MVCC including Oracle, Berkeley DB, CouchDB and many more. Understanding how MVCC is implemented in Postgres is important when designing highly concurrent apps on PostgreSQL. It’s actually a very elegant and simple solution to a hard problem.

How MVCC works

Every transaction in postgres gets a transaction ID called XID. This includes single one statement transactions such as an insert, update or delete, as well as explicitly wrapping a group of statements together via BEGIN - COMMIT. When a transaction starts, Postgres increments an XID and assigns it to the current transaction. Postgres also stores transaction information on every row in the system, which is used to determine whether a row is visible to the transaction or not.

For example, when you insert a row, postgres will store the XID in the row and call it xmin. Every row that has been committed and has an xmin that is less than the current transaction’s XID is visible to the transaction. This means that you can start a transaction and insert a row, and until that transaction COMMITs that row will not be visible to other transactions. Once it commits and other transactions get created, they will be able to view the new row because they satisfy the xmin < XID condition – and the transaction that created the row has completed.

A similar mechanism occurs for DELETEs and UPDATEs, only in these cases Postgres stores an xmax value on each row in order to determine visibility. This diagram shows two concurrent transactions inserting and reading rows, and how MVCC comes into play in terms of transaction isolation.

For the following charts, assume the following DDL:

CREATE TABLE numbers (value int);

MVCC read/write isolation

While the xmin and xmax values are hidden from daily operations, you can actually just ask for them and Postgres will happily give them to you:

SELECT *, xmin, xmax FROM numbers;

You can also get the XID for the current transaction pretty easily:

SELECT txid_current();

Neat!

I know what you’re thinking though: what about a two transactions updating the same row at the same time? This is where transaction isolation levels come in. Postgres basically supports two models that allow you to control how this situation should be handled. The default, READ COMMITTED, reads the row after the inital transaction has completed and then executes the statement. It basically starts over if the row changed while it was waiting. For instance, if you issue an UPDATE with a WHERE clause, the WHERE clause will rerun after the initial transaction commits, and the UPDATE takes place if the WHERE clause is still satisfied. Here’s an example of two transactions modifying a row where the initial UPDATE causes the WHERE clause of the second transaction to return no rows. Therefore the second transaction does not update any rows at all:

READ COMMITTED transaction isolation

If you need finer control over this behavior, you can set the transaction isolation level to SERIALIZABLE. With this strategy the above scenario will just fail, because it says “If the row I’m modifying has been modified by another transaction, don’t even try,” and Postgres will respond with the error message ERROR: could not serialize access due to concurrent update. It’s up to your app to handle that error and try again, or to give up if that’s what makes sense.

SERIALIZABLE transaction isolation

Disadvantages of MVCC

Now that you know how MVCC and transaction isolation actually works, you’ve added another tool for solving the kinds of problems where a SERIALIZABLE isolation level comes in handy. While the advantages of MVCC are clear it also has some disadvantages.

Because different transactions will have visibility to a different set of rows, Postgres needs to maintain potentially obsolete records. This is why an UPDATE actually creates a new row and why DELETE doesn’t really remove the row: it merely marks it as deleted and sets the XID values appropriately. As transactions complete, there will be rows in the database that cannot possibly be visible to any future transactions. These are called dead rows. Another problem that comes from MVCC is that transaction IDs can only ever grow so much – they are 32 bits and can “only” support around 4 billion transactions. When the XID reaches its max, it will wraparound and start back at zero. Suddenly all rows appear to be in future transactions, and no new transactions would have visibility into those rows.

Both dead rows and the transaction XID wraparound problem are solved with VACUUM. This should be routine maintenance, but thankfully Postgres comes with an auto_vacuum daemon that will run at a configurable frequency. It’s important to keep an eye on this because different deployments will have different needs when it comes to vacuum frequency.