Made with Palestinian hands Support EmuPath ☕

No results found.

Try another search or remove some filters.

WORKED LEARNING GUIDE

Reason About a Database Transaction

Use a fictional inventory reservation to distinguish atomic updates, business constraints and external side effects.

Before you start: Read basic SQL and application workflows

The scenario

A training shop has three units of a fictional item. Reserving two units should reduce available stock to one and create one reservation. A crash after the stock update but before the reservation leaves inconsistent records if the two changes are committed independently. Use disposable sample data only.

1. Describe the invariant

Write the business rule before choosing SQL: a completed reservation must have the matching stock change, and available stock must not become negative. List the starting rows and the expected ending rows. This turns “the request succeeded” into concrete checks. In the example, three minus two equals one; a later request for two more units must not silently produce negative stock.

2. Group related changes

A transaction can group the database updates into an all-or-nothing unit. In a disposable PostgreSQL exercise, compare a successful commit with a deliberate rollback after the first change. Inspect the final rows rather than assuming that a printed message proves the result. Exact error handling depends on the database driver and application framework, so document how the application recognizes and rolls back a failed operation.

3. Consider concurrent requests

Two sessions can both observe a value before either finishes updating it. Merely wrapping statements in a transaction does not establish that every business rule is protected under every isolation level. Review the database’s constraints, locking and isolation behavior, and test the competing-request case. Record an acceptable result: one request may succeed while the other is rejected or retried according to the application contract.

4. Keep external effects separate

An ordinary database rollback does not recall an email already sent by another service. Draw a boundary around the database and mark messages or payment requests outside it. For this exercise, use a fake message recorder and check whether a failed reservation would incorrectly announce success. A production design needs a deliberate delivery and retry strategy; do not assume that a database transaction makes an entire distributed workflow atomic.

A reservation rolls back after an email was sent. What should you assume?

Try two more cases

Stock is 3 and a valid reservation consumes 2. What should the committed available stock be?

Two requests read the same stock value concurrently. What needs review?

Practice with EmuPath

Check the primary reference

Examples are educational scenarios. Verify the current documentation and your own environment before changing a real system.

Explore another lesson