September 3, 2024 4 min read A to Z Series: S Home

Serialized Transactions: One Clear Order

Serialized transactions make concurrent transactions behave as though the database ran them one at a time in a clear order.

I think about serialized transactions whenever concurrency can create an impossible business outcome. Speed is useful, but I recommend protecting invariants when the final result must look like one valid order.

The result matters more than the internal schedule

When I talk about "The result matters more than the internal schedule", I am really asking what Serialized Transactions does when a message is late, duplicated, or missing.

The database may do clever locking or validation internally. From the application point of view, the outcome should look as if one transaction happened first and the other happened second.

Ledger example

I use "Ledger example" to keep Serialized Transactions grounded in a real system, because abstract patterns are too easy to agree with and too hard to operate.

Two customers try to reserve the last seat. Serialized transactions let one reservation commit and force the other to retry or fail. The last seat is not sold twice.

Serialized write code

When I show "Serialized write code", I want the code in Serialized Transactions to reveal the production decision, not just the syntax.

Serializable isolation keeps the last seat from being sold twice:

BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

UPDATE seats
SET held_by = 'customer-42'
WHERE seat_id = '12A' AND held_by IS NULL;

COMMIT;

The serializable transaction makes the seat hold behave as if one buyer acted at a time. If two buyers race, the database must reject one conflicting write.

Sequence diagram: last seat reservation

last seat reservation Both requests are concurrent, but the committed result has one clear order. sd last seat reservation Customer A Customer A Booking DB Booking DB Customer B Customer B Start transaction toreserve seat 12A. Start another transactionfor seat 12A. Commit the first validreservation. Reject or retry becausethe seat is now taken.

Both requests are concurrent, but the committed result has one clear order.

The serialization choice

Related transaction topics

Written by Arunkumar Ganesan.

What I learnt is that serialization is expensive only until the alternative creates a balance, booking, or inventory state nobody can explain.

#DistributedSystems #Transactions #Databases #Architecture