YugabyteDB Transactions
Isolation levels, distributed transaction mechanics, and the retry behaviour applications must implement.
YugabyteDB supports distributed ACID transactions across tablets and regions, with isolation levels exposed through the PostgreSQL interface.
Isolation levels
SET DEFAULT_TRANSACTION_ISOLATION TO 'repeatable read';
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;How a distributed transaction works
- The transaction is assigned an identifier and a status record held in a transaction status tablet.
- Writes are recorded provisionally in the tablets they touch.
- At commit, the status record is updated — a single Raft write that atomically decides the outcome for every participant.
- Provisional records are resolved into regular records asynchronously.
The status record is what makes commit atomic across tablets without a blocking two-phase commit coordinator. See Distributed Transactions for why that matters.
Retries are mandatory
for attempt in range(1, 6):
try:
with conn.transaction():
do_work(conn)
break
except psycopg.errors.SerializationFailure:
if attempt == 5:
raise
time.sleep(0.05 * 2 ** attempt + random.uniform(0, 0.05))Reducing contention and latency
Avoid single-row hotspots. A shared counter serialises through one tablet leader.
Keep transactions single-tablet where possible. A transaction confined to one tablet avoids the distributed path entirely and is substantially faster. Design primary keys so related rows share a tablet.
Use follower reads for tolerant reads:
SET yb_read_from_followers = true;
SET yb_follower_read_staleness_ms = 30000;
SELECT * FROM catalog WHERE id = $1;Batch related statements. Round trips between the client and the query layer dominate short transactions; fewer statements means fewer of them.
Locking
SELECT ... FOR UPDATE and the other PostgreSQL locking clauses are supported and acquire
distributed locks. As elsewhere, taking the lock early is preferable to discovering a conflict at
commit after the work is done — but every lock held across a network round trip lengthens the
window in which others conflict with it.