Transactions, ACID Compliance, and Data Normalization
local graph
Chapter 5 — Transactions, ACID Compliance, and Data Normalization
Section titled “Chapter 5 — Transactions, ACID Compliance, and Data Normalization”Transactions, ACID Compliance, and Data Normalization
Section titled “Transactions, ACID Compliance, and Data Normalization”This chapter explores PostgreSQL’s support for transactional, ACID-compliant applications that use a normalized data model. We will begin with a detailed look at ACID compliance and its importance, then examine one of its main components: transactional isolation and the different isolation levels supported in PostgreSQL. A separate section helps the developer understand the notion of implicit and explicit transactions, savepoints, rollbacks, and other transactional capabilities.
The chapter concludes with a discussion on data normalization, its importance for high-volume transactional applications, and how to model facts that change over time using slowly changing dimensions.
This chapter covers the following topics:
- Understanding ACID compliance and its role in reliable database transactions
- Working with transactions in PostgreSQL, including commits, rollbacks, and savepoints
- Managing concurrent transactions using PostgreSQL isolation levels
- Using locks and concurrency controls to prevent conflicting updates
- Designing normalized data models and handling evolving data with slowly changing dimensions
Technical requirements
Section titled “Technical requirements”All examples in the chapter are available in the GitHub repo under psql_scripts / sample_scripts / chapter_5.sql.
ACID compliance: What is it and why does it matter?
Section titled “ACID compliance: What is it and why does it matter?”When databases handle essential tasks, such as processing payments, tracking orders, or storing employee records, every transaction needs to be accurate, reliable, and safe. That’s where ACID compliance comes in.
Introduced in 1983 by Theo Härder and Andreas Reuter, ACID describes four key properties: a tomicity, c onsistency, i solation, and d urability. They ensure that database transactions are handled correctly, even when things go wrong. These rules have guided database systems for decades and remain just as important today.
The four key principles of ACID compliance are as follows:
- Atomicity: An atomic transaction cannot happen partially; either all parts of the transaction complete, or none of them
- Consistency: Transactions move databases from one consistent state, where all constraints are met, to another consistent state, where, again, all constraints are met
- Isolation: Events within a transaction are hidden from other concurrent transactions until the transaction has been committed
- Durability: Once a transaction has been completed and has committed its results, the system must guarantee that these results survive any subsequent malfunction
Together, these rules create the foundation for reliable databases, protecting data integrity and consistency, and ensuring smooth operations in systems we rely on every day.
Atomicity
Section titled “Atomicity”A transaction can consist of multiple statements. Atomicity means that either all statements are executed successfully or none are. The idea that a single transaction may include several statements is often a source of confusion, especially for beginners who think of a transaction as a single action.
To understand this better, let’s take a look at an example. First, we add a sales transaction line to an existing sales transaction and, in the same transaction, we decrement the available inventory to show that the inventory has been committed to a sales transaction. Both actions need to succeed together because they represent two sides of the same event: recording the sale and updating stock.
Let’s use a concrete example: The customer is purchasing a pair of Levi’s blue jeans, model 501, color blue, size 32/26, for Euro 29 (product_variant_id = 50). She already has an open sales transaction with an ID of east_7108:
BEGIN TRANSACTION;-- create the sales transaction line INSERT INTO sales_transaction_line (sales_transaction_id, product_variant_id, qty, price_at_sale) VALUES ('east_7108', 50, 1, 29);-- decrement the inventory UPDATE product_variant_inventory SET qty = qty -1 WHERE product_variant_id = 50;COMMIT TRANSACTION;By wrapping both statements into a transaction block using BEGIN TRANSACTION and COMMIT TRANSACTION, we make sure that either both actions succeed, or neither of them takes effect.
The word TRANSACTION is optional after BEGIN and COMMIT. We added it here for clarity.
Both actions need to succeed together because they represent two sides of the same event: recording the sale and updating stock.
Without the transaction block defined by BEGIN and COMMIT, both statements would be considered as individual transactions, which could lead to non-existent inventory being assigned to a sales order.
Consistency
Section titled “Consistency”Databases execute thousands of transactions per second, and must make sure that the database transitions from one consistent state to the next consistent state, where consistency is defined as meeting all the constraints specified in the database, such as minimum inventory levels, non-negative holdings in bank accounts, employee birthdays reflecting real dates, and so on.
An example will help us clarify the concept. When we inspect the product_variant_inventory table using the \d command in psql, we see that a constraint on the qty column makes sure that on-hand inventory is always greater than zero:
\d inventory.product_variant_inventory ; Table "inventory.product_variant_inventory" Column | Type | Collation | Nullable | Default--------------------+---------+-----------+----------+--------- product_variant_id | integer | | not null | qty | integer | | not null | 0
...Check constraints: "product_variant_inventory_qty_check" CHECK (qty >>= 0)...Any transaction, such as the one shown in the previous section, that would attempt to commit an order that causes the inventory level to drop below zero would fail, as it violates the check constraint, product_variant_inventory_qty_check.
This shows how important it is to define transactions properly, as atomicity and consistency are closely related concepts.
Isolation
Section titled “Isolation”The database doesn’t just execute thousands of transactions in sequence; many of them happen in parallel. Isolation of transactions means that the effects of a transaction only become visible once it has completed all of its work, achieved a new consistent state, and that state has been committed.
In our preceding example, this means that the new sales transaction line will only become visible outside of the transaction scope after the inventory has been assigned, and assuming that there is sufficient inventory, the transaction has been completed, and the results have been committed.
For example, if another concurrent transaction were to compute the customer’s invoice while our transaction is running, it would not see the transaction line, as the in-process transaction is isolated.
The SQL standard and PostgreSQL differentiate between multiple isolation levels, and the following section will dive deeper into the concept of transaction isolation in PostgreSQL.
Durability
Section titled “Durability”Databases must be highly reliable, meaning users can trust that the database maintains commitments, including completed transactions, even in the event of power failures, disk failures, or technical malfunctions.
In our example, this means that once we have accepted a sales order line and committed the inventory, then this stays true even if the database crashes and restarts.
The database achieves this by writing committed transactions to durable storage before communicating them to the user or the application.
Consistency is a necessary precondition to durability. Only consistent states will become part of the truth that the system guarantees against malfunctions, and that will be recovered after a crash or a restart. The topics of persistence and recovery are discussed in detail in the companion book PostgreSQL 16 Administration Cookbook by Ciolli et al.
Why ACID compliance matters for the business
Section titled “Why ACID compliance matters for the business”In simple terms, ACID compliance matters to the business because it is the foundation of trust, reliability, and accuracy in a company’s data systems. It ensures that financial transactions, customer orders, and critical business operations are processed correctly and safely, which directly protects revenue, reputation, and legal standing.
ACID-compliant systems ensure financial integrity, build and maintain customer trust, provide a reliable single source of truth, and mitigate legal risk and compliance issues.
Last, but not least, ACID-compliant databases accelerate system development and eliminate many sources of logic bugs. The fact that the database deals with atomicity, consistency, isolation, and durability removes a lot of effort that would otherwise have to be invested in the application code.
Working with transactions in PostgreSQL
Section titled “Working with transactions in PostgreSQL”Transactions are a single, logical unit of work performed on a database. They consist of a series of one or more database operations specified as SQL statements (such as SELECT, INSERT, UPDATE, or DELETE) that are treated as a single, all-or-nothing operation. For example, when Jane wires money to Jim, two operations need to happen: (1) Money leaves Jane’s account, and (2) the money shows up in Jim’s account. Both operations together define the transaction, and they both need to happen for the transaction to complete.
Transactions can be single-statement transactions, as in this example:
INSERT INTO brand (id, label, description) VALUES (10001, 'Wrangler Jeans', 'Good Mornings Make for Better Days');They can also be multi-statement transactions, such as the following:
BEGIN;INSERT INTO brand (id, label, description) VALUES (10001, 'Wrangler Jeans', 'Good Mornings Make for Better Days');
INSERT INTO product (id, category_id, brand_id, label, shortdescription) VALUES (10000, 1, 10001, 'Jeans by Wrangler', 'Best pants for a great day');
INSERT INTO product_variant (id, product_id, attributes, upc) VALUES (10001, 10000, '{"color": "blue", "size": "32/36", "fit": "Boot Leg"}', '1234567890');COMMIT;Single-statement transactions do not need the BEGIN / COMMIT wrapper. The preceding single-statement transaction is implicitly equivalent to the following:
BEGIN;
INSERT INTO brand (label, description) VALUES ('Wrangler Jeans', 'Good Mornings Make for Better Days');
COMMIT;Multi-statement transactions must be explicitly defined through BEGIN / COMMIT. Single statements, outside of a BEGIN / COMMIT block, are implicitly considered as transactions.
If multiple statements are not wrapped into a BEGIN / COMMIT block, then they are executed as individual transactions! Any rollback will only impact the most recent statement.
Transaction blocks
Section titled “Transaction blocks”Transaction blocks regroup multiple statements into a single transaction, as defined previously. Transaction blocks can also be nested (subtransactions), so that rollbacks can be limited to the most recent transaction context.
Transaction blocks can be started with BEGIN, START TRANSACTION, or BEGIN TRANSACTION, and end with COMMIT, COMMIT TRANSACTION, or ROLLBACK. As mentioned previously, single-statement transactions do not require the BEGIN / COMMIT statements.
Sometimes, applications (or users) want to execute individual statements and have their results immediately committed (a.k.a. an implicit transaction); other times, they want a whole block of statements executed together, and they will explicitly create a transaction block.
The key difference between running statements one by one (implicit transactions) and bundling them into a block (explicit transactions) lies in atomicity. With explicit blocks, either all statements succeed or none of them do. This ensures that the database cannot be left in an inconsistent state when errors occur.
Let’s understand this with an example. Suppose the inventory level for blue Wrangler jeans of size 32/36 (product variant ID 10001) is 1. Consider the following scenarios:
- Scenario 1 – Without a transaction block: We will run two statements, executed one after another, without a transaction block. They will both be considered as two separate implicit transactions:
Even though the inventory transaction failed, the sales transaction line was created. Obviously, this is not intended!INSERT INTO sales_transaction_line(sales_transaction_id, product_variant_id, qty, price_at_sale)VALUES ('east_5316', 10001, 5, 19.99);INSERT 0 1UPDATE product_variant_inventory SET qty = qty 5 WHERE product_variant_id = 10001;ERROR: new row for relation "product_variant_inventory" violates check constraint "product_variant_inventory_qty_check"DETAIL: Failing row contains (10001, -4).
- Scenario 2 – Using a transaction block: We will wrap the same statements inside a transaction block, making them one explicit multi-statement transaction:
BEGIN;INSERT INTO sales_transaction_line(sales_transaction_id, product_variant_id, qty, price_at_sale)VALUES ('east_5316', 10001, 5, 19.99);UPDATE product_variant_inventory SET qty = qty - 5 WHERE product_variant_id = 10001;END;ERROR: new row for relation "product_variant_inventory" violates check constraint "product_variant_inventory_qty_check"DETAIL: Failing row contains (10001, -4).
This time, the whole transaction fails, and no sales transaction line was created.
Rollback: Explicitly undoing the work inside a transaction
Section titled “Rollback: Explicitly undoing the work inside a transaction”While COMMIT makes all changes within the transaction (after BEGIN) durable by writing them to WAL, ROLLBACK reverses all changes. It restores the database to its state before the BEGIN statement. ROLLBACK commands can also be issued explicitly within a stored procedure.
Errors can also be handled inside stored procedures using the EXCEPTION statement, allowing for explicit calls to ROLLBACK:
CREATE OR REPLACE PROCEDURE add_to_sales_transaction (p_st_id TEXT,p_pv_id INTEGER,p_qty INTEGER,p_price NUMERIC)AS$$BEGIN INSERT INTO sales_transaction_line (sales_transaction_id, product_variant_id, qty, price_at_sale) VALUES (p_st_id, p_pv_id,p_qty, p_price); UPDATE product_variant_inventorySET qty = qty - p_qtyWHERE product_variant_id = p_pv_id;EXCEPTION WHEN check_violation THEN ROLLBACK; RAISE NOTICE 'Check constraint failure'; WHEN OTHERS THEN ROLLBACK; RAISE NOTICE 'Transaction failed for unknown reasons';END $$ LANGUAGE PLPGSQL;Savepoints and subtransactions
Section titled “Savepoints and subtransactions”Rollbacks undo all the work in the current transaction block. Savepoints can be defined within transactions to limit the effect of a ROLLBACK command. Only the statements executed before the savepoint will be rolled back when the ROLLBACK TO SAVEPOINT command is issued. In long (and very complex) transactions, savepoints can be used to define subtransactions. For example, an order with thousands of order lines might be able to commit 90% of the lines, including the corresponding inventory assignment, and document the other 10% that were rejected due to a lack of available inventory.
Subtransactions can also be initiated in exception handlers and can result in hierarchies of subtransactions. Chapter 6*,* Functions and Stored Procedures, will discuss savepoints, commits, and rollbacks in detail as part of the description of the PL/pgSQL procedural language.
Transactions, contained within an ACID-compliant database engine, are one of the fundamental building blocks in Postgres. We have seen how they can be defined implicitly and explicitly, and how they can either commit successfully or be rolled back. The following sections put the individual transactions into the context of concurrent transactions, describe how PostgreSQL handles concurrency, and take a closer look at the concept of isolation, the I in ACID.
A closer look at isolation levels and their importance
Section titled “A closer look at isolation levels and their importance”When databases execute many transactions, with each transaction potentially consisting of dozens, if not hundreds, of individual statements, in parallel, the database must ensure that intermediate states are not visible to the other transactions, that is, that the particular transactions are isolated from each other until they have completed their work.
It is crucial to ensure that other processes do not see incomplete database states that do not meet the consistency requirements or might even need to be reverted if a transaction fails and is rolled back.
We will see later that guaranteeing isolation comes with performance impacts and requires a certain degree of application awareness – thus, isolation does not come for free. To allow the developer to balance isolation and complexity, the SQL standard defines four isolation levels:
Read Uncommitted: Transactions can see uncommitted changes from other transactions, which can lead to dirty readsRead Committed: Transactions can only see committed changes, preventing dirty reads but allowing non-repeatable readsRepeatableRead: A transaction’s reads are consistent, preventing dirty and non-repeatable reads but allowing phantom readsSerializable: Transactions are fully isolated, executed in a serial order to prevent dirty, non-repeatable, and phantom reads
Read Uncommitted is part of the SQL standard but is not supported in PostgreSQL. The developer can request the Read Uncommitted isolation level, but PostgreSQL’s Read Uncommitted mode behaves like Read Committed.
Before diving deeper into the individual isolation levels, we will explain the key anomalies that characterize the levels and define when and why a developer will choose a specific isolation mode.
The three key anomalies are as follows:
- D irty r ead: A transaction sees the results of a partially executed transaction that may be rolled back later. In our previous example, a concurrent transaction could see the sales transaction line and act on it, even though it might still be rolled back due to insufficient inventory. This is possible at the
Read Uncommittedisolation level (not supported in PostgreSQL) and is avoided at theRead Committedlevel. - N on-repeatable r ead: The same transaction executes the same
SELECTstatement twice and sees different results, for example, because a concurrent transaction has committed inventory. This problem is solved by adopting theRepeatableReadlevel. - Phantom r ead: Similar to the non-repeatable read, but instead of being caused by changes in row values, it is caused by concurrent transactions adding or deleting rows. Non-repeatable reads are about modifying existing rows; phantom reads are about inserting or deleting rows, which changes the result set. The
Serializableisolation level addresses this problem.
Table 5.1 summarizes the three key anomalies, indicating at which isolation level they can occur and which level should be chosen to avoid them.
| Isolation l evel / Anomal y | Dirty r ead | Non- r epeatable r ead | Phantom r ead |
|---|---|---|---|
| Read Uncommitted | ❌ | ❌ | ❌ |
| Read Committed | ✅ | ❌ | ❌ |
| Repeatable Read | ✅ | ✅ | ❌ |
| Serialized | ✅ | ✅ | ✅ |
Table 5.1: The database isolation levels and the three key anomalies that they prevent
We will now examine the two most commonly used isolation levels in PostgreSQL: Read Committed and Repeatable Read.
Read Committed isolation level
Section titled “Read Committed isolation level”Read Committed is the default isolation level in PostgreSQL. At this level, every SQL statement in a transaction sees only data that other transactions have already committed. However, each statement gets its own fresh snapshot of the database. That means different statements within the same transaction might see different results if other transactions commit in between. This level prevents dirty reads (you never see another session’s uncommitted changes), but it does allow anomalies such as non-repeatable reads and lost updates. This means you cannot assume that repeating the same query within a transaction will always yield the same result.
Consider a simple business case: updating stock after adding an order line. The transaction executes three steps:
- Verify that sufficient inventory is available.
- Create the sales transaction line.
- Reduce the available inventory.
Here is the code:
DO $$ BEGIN IF (SELECT 1 FROM product_variant_inventory WHERE product_variant_id = 50 AND qty >> 1) THEN -- create the sales transaction line INSERT INTO sales_transaction_line (sales_transaction_id, product_variant_id, qty, price_at_sale) VALUES ('east_7108', 50, 1, 12); -- decrement the inventory UPDATE product_variant_inventory SET qty = qty -1 WHERE product_variant_id = 50; ELSE RAISE NOTICE 'No inventory available'; END IF;END $$;At Read Committed, the update in S tep 3 might still fail if another parallel transaction has decremented the same inventory between the first check and the inventory update.
Let’s look at the effects of Read Committed using a simple two-statement transaction:
BEGINSELECT qty FROM product_variant_inventory WHERE product_variant_id = 50;UPDATE product_variant_inventory SET qty = qty -1 WHERE product_variant_id = 50;COMMITWe’ll walk through two scenarios using these statements in different sessions.
In the first scenario, illustrated in Table 5.2, uncommitted changes from database session 1 are not visible outside of the transaction in database session 2: