BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Intermediate · Lesson 5 of 12

Software Architecture

Commit a Transfer Atomically

A mistyped till code interrupts a transfer of AED 75. Post both ledger entries in PostgreSQL and check exactly what survives a rollback.

A transfer slip bridges two wooden trays holding brass tokens on a stationer’s desk.

The main till in a stationery shop holds AED 500 and the collection desk holds AED 100. The supervisor moves AED 75 from the main till to the desk. Halfway through recording the move, the desk code is mistyped. The first database insert succeeds and the second fails. At closing time, should the recorded balances be 425 and 100, or 500 and 100? And how would you tell whether the physical cash still needs attention?

The two questions have different evidence. The cashier can count the drawers to establish where the notes went. The software can guarantee that the ledger records either both sides of the transfer or neither. We will build that guarantee for a single PostgreSQL database, stop deliberately after the first write, cause a genuine second-write error, and finally post the correct transfer. Keep the reference T17 throughout. It lets us inspect the exact operation rather than guessing from a plausible balance.

اقرأ الدرس بالعربية

Decide what a completed transfer looks like

There are two entries on the transfer slip. The first reduces MAIN by 7,500 fils and the second increases DESK by the same amount. One hundred fils make a dirham. Keeping amounts as whole fils makes the arithmetic in this exercise exact. Nothing is sold, refunded or charged as a fee. The combined balance must therefore stay at 60,000 fils. Write down the expected final balances before touching the database: MAIN should hold 42,500 fils and DESK should hold 17,500.

Conserving the total is necessary but insufficient. Posting in the wrong direction would also preserve the total. Posting the whole transfer twice would leave the total unchanged as well. We need evidence for the identity of the request, the source, the destination and the signed amounts. In the example, a posting is one change to one till. A transfer is the pair of postings that shares a reference. A balance is the opening amount plus the changes recorded against that till. Those definitions give us three independent things to inspect.

Open a fresh PostgreSQL session with autocommit enabled for the setup statements. Keep it open throughout the exercise. These temporary objects are private to that session. Create them once, before running any of the experiments, so that rolling back an experimental write leaves the opening records available.

CREATE TEMP TABLE till (
  code text PRIMARY KEY,
  opening_fils integer NOT NULL
);
CREATE TEMP TABLE posting (
  ref text NOT NULL,
  leg text NOT NULL CHECK (leg IN ('out','in')),
  till_code text NOT NULL REFERENCES till(code),
  delta_fils integer NOT NULL,
  PRIMARY KEY (ref, leg),
  CHECK ((leg = 'out' AND delta_fils < 0) OR
         (leg = 'in'  AND delta_fils > 0))
);
INSERT INTO till VALUES ('MAIN',50000), ('DESK',10000);

CREATE TEMP VIEW balances AS
SELECT t.code, t.opening_fils + COALESCE(SUM(p.delta_fils),0) AS fils
FROM till AS t LEFT JOIN posting AS p ON t.code = p.till_code
GROUP BY t.code, t.opening_fils;

The primary key allows at most one outgoing and one incoming entry per reference. The foreign key catches a till code that does not exist. The sign check catches an incoming entry carrying a negative amount. None of these individual checks can force a caller to send the second entry. A careless caller could legally insert the outgoing row and commit it on its own. The transaction boundary belongs around the complete business operation. PostgreSQL's transaction tutorial explains how statements inside that boundary become one unit of work.

The view computes balances from the entries we actually kept. It starts from the till list so that an empty ledger still shows both opening amounts. Before the first experiment, run the balance query in the next block on its own. DESK comes first alphabetically at 10,000 and MAIN follows at 50,000. This ordering matters when checking your notes: the first number printed by the query is the destination balance, even though the first write we make will be against the source.

Stop after the first write

BEGIN;
INSERT INTO posting VALUES ('T17','out','MAIN',-7500);
SELECT code, fils FROM balances ORDER BY code;
ROLLBACK;
SELECT code, fils FROM balances ORDER BY code;
SELECT COUNT(*) FROM posting WHERE ref = 'T17';

Execute one statement at a time and pause after the first balance query. The session doing the work can see its own pending debit. It shows MAIN at 42,500 and DESK at 10,000. The combined amount looks short by precisely the sum on the slip. That observation is useful when debugging a transaction; it is also a reason never to send a success receipt from this point in the code. Seeing your own row proves the insert ran. It gives you no evidence that the transfer has finished.

Now execute the rollback and read the balances again. MAIN returns to 50,000 and DESK remains at 10,000. The count for T17 is zero. There is no positive entry cancelling a leftover negative one. The attempted debit itself is absent from the committed ledger. A reversal of an already completed transfer would instead be a new business event, normally linked to the original. For the database command that ends an unfinished transaction and discards its changes, see the ROLLBACK reference.

Consider where a checkout application borrows its database connection. The begin, both inserts and the final commit or rollback must use the same connection. Sending the second insert through another connection taken from a pool breaks that boundary. So does leaving autocommit on and issuing the two inserts as separate standalone statements without beginning a transaction. In the latter case the first write has already finished its own transaction by the time the desk lookup fails. An error handler cannot undo that earlier commit simply by rolling back the second statement.

Make the second entry fail

BEGIN;
INSERT INTO posting VALUES ('T17','out','MAIN',-7500);
INSERT INTO posting VALUES ('T17','in','DSEK',7500);

The destination is deliberately misspelled DSEK. Submit the statements separately so you can observe the foreign-key failure from the last one. A mistyped code resembles a realistic integration error and gives this test a precise failure point. Up to that point the outgoing entry had succeeded in the open transaction. PostgreSQL now considers the transaction failed. In an interactive client, issue the next rollback separately if the client stopped running the script at the first error.

ROLLBACK;
SELECT code, fils FROM balances ORDER BY code;
SELECT COUNT(*) FROM posting WHERE ref = 'T17';

The desired result is the same pair of opening balances and no rows for T17. Do not classify the test as passed merely because an error appeared. A service that writes each side independently will also report a foreign-key error on DSEK. It will fail the balance and row-count checks because the debit survives. Those checks separate the property we want from a superficial demonstration that a foreign key exists. They also make good acceptance criteria for a change to the code that manages database connections.

Commit the correct pair

BEGIN;
INSERT INTO posting VALUES ('T17','out','MAIN',-7500);
INSERT INTO posting VALUES ('T17','in','DESK',7500);
COMMIT;

SELECT ref, leg, till_code, delta_fils
FROM posting WHERE ref = 'T17' ORDER BY delta_fils;
SELECT code, fils FROM balances ORDER BY code;

Only one character sequence changed in the input: the destination now names an existing till. Check the two detail rows before checking the totals. You should find T17 with an outgoing 7,500 fils from MAIN and an incoming 7,500 fils to DESK. Then read the balances in their printed order: DESK 17,500 and MAIN 42,500. Together they still account for the original AED 600. A reader querying the committed ledger can now see the transfer as a whole. The COMMIT reference describes when the transaction's changes take effect.

Why did we bother with two inserts when one statement could insert two rows? A single multi-row insert also gives statement-level atomicity here. The split exposes the point between the writes so that you can test it, and it matches applications that have to perform several related statements. If the application also persists a transfer header or updates a balance cache used for authorization, include those dependent database writes in the same transaction. Keep the boundary short. Waiting for a cashier to review a dialog while a transaction is open makes other workers wait unnecessarily if they need the same locked records.

Check the ledger from the reader's side

SELECT ref, COUNT(*) AS legs, SUM(delta_fils) AS net_fils
FROM posting GROUP BY ref
HAVING COUNT(*) <> 2 OR SUM(delta_fils) <> 0;

On the completed example this audit returns no rows. It lists references with the wrong number of entries or an unequal sum of debits and credits. It would catch a lone debit and it would catch a pair of minus 7,500 and plus 750. It cannot catch a missing transfer that has no rows at all. Nor can it detect a balanced pair posted to the wrong two tills. For those cases reconcile the entries to the original slip. A useful test has both a ledger-wide consistency check and an assertion about the particular request you submitted.

On shared tables, a separate ordinary reader under PostgreSQL's default Read Committed isolation does not see another transaction's pending debit. A single balance query reads a consistent snapshot. Two separate queries, one for each till, can straddle the commit and mix an old balance with a new one. Fetch both balances in one query when explaining a transfer to a cashier. Because our tables are temporary, opening a second session here would create a separate exercise environment. The visibility rule applies to concurrent sessions reading the same shared tables. See the transaction isolation documentation.

One failure occurs after the database has done its job: the network drops while the client waits for confirmation of commit. A timeout alone cannot tell the cashier whether T17 succeeded. Look up the original reference and compare both stored entries with the intended tills and amounts. If an outcome is still in flight, reconcile it before reporting failure. Reusing the same reference lets the unique key arbitrate a replay. Inventing a new one can produce two complete, balanced transfers for a single envelope of cash. Atomicity alone cannot identify them as duplicates.

Exercise: return part of the float

Start from the successfully committed T17. The desk returns AED 20 to MAIN under reference T18. Predict the balances. Use the same two-entry pattern, but first roll back immediately after the outgoing write. Read the balances and count the rows for T18. Then run the entire T18 transfer and commit it once. Run the audit again.

Answer. After rollback, T18 has zero entries and T17 still has two. DESK remains at AED 175 and MAIN at AED 425. After commit, T18 has a debit of 2,000 fils at DESK and a credit of 2,000 at MAIN. DESK ends at AED 155 and MAIN at AED 445. The combined balance is AED 600 in both checks, and the audit returns no exceptions. A reader should be able to account for the difference between the two observations by pointing to precisely two committed rows.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Answer Questions with SELECT

Two AED 40 receipts look alike. Should both count? Reconcile a day of shop sales in PostgreSQL, from the first filter to a channel report you can check by hand.

Read article ↗