Optimistic locking for stock

You can use a version-checked update to detect competing stock changes and retry safely, which is the core of the stock reservation service.

Learning outcomes

  • You can explain how a version column and guarded update prevent two carts from selling the same units.
  • You can distinguish a version conflict from insufficient stock and understand why a fresh read is necessary.
  • You can explain how Redis holds prevent duplicate reservations without replacing database inventory checks.
  • You can reason about transaction boundaries for multi-line reservations and restocking.
  • You can interpret concurrent reservation tests and distinguish inventory errors from Go data races.

Your restaurant has 10 portions of a popular dish remaining. Hundreds of customers try to order it at the same time. If two requests both read that one portion remains, both might attempt to reserve it. Your stock reservation service must ensure that only one succeeds, even when requests execute concurrently across multiple backend instances.

The problem is similar to the seat-booking problem you have already encountered in C++. The difference is that the database now protects shared inventory, while Redis provides a temporary hold for each order.

The inventory invariant

Inventory is shared state. Every reservation must preserve this rule:

on_hand >= 0

A reservation for qty units can succeed only when the current stock contains at least that quantity.

For example, consider a restaurant with 10 portions of an item:

OperationAvailable stock
Initial stock10
Reserve 37
Reserve 43
Reserve 4Sold out

The last reservation must fail. Returning a successful response while reducing stock below zero would be an Overselling.

A stock table can represent the inventory like this:

sql
CREATE TABLE stock (
    item_id BIGINT NOT NULL PRIMARY KEY,
    on_hand INT NOT NULL,
    version BIGINT NOT NULL DEFAULT 0,
    CHECK (on_hand >= 0)
);

The on_hand column records the available units. The version column changes whenever a stock update succeeds.

The database must protect both values together. A Go mutex cannot provide that guarantee across multiple backend instances. Each instance has its own process memory, so an in-memory lock on one instance cannot coordinate with another.

The version column

Optimistic locking lets multiple transactions attempt an operation without acquiring an explicit row lock before every read.

Each transaction reads a row and remembers its version. When it updates the row, it checks whether that version is still current.

Suppose the database contains:

item_id = 42
on_hand = 1
version = 7

Two carts read this row. Both see one available unit and version 7. Both decide to reserve one unit.

Without concurrency protection, both could decrement the stock based on the same earlier observation.

The version column detects the conflict. The first transaction changes the row:

on_hand = 0
version = 8

The second transaction still expects version 7. Its update can no longer match the row.

This is an example of compare-and-set: change the value only when the state still matches what you previously observed.

The guarded update

A Guarded UPDATE places the conditions for a successful operation directly in the SQL UPDATE statement.

For inventory, the statement must check both the available quantity and the observed version:

sql
UPDATE stock
SET
    on_hand = on_hand - ?,
    version = version + 1
WHERE item_id = ?
  AND on_hand >= ?
  AND version = ?;

The parameters represent:

  1. The quantity to subtract.
  2. The item ID.
  3. The minimum available quantity required.
  4. The version observed during the earlier read.

The important detail is that the database evaluates these conditions as part of the update itself. Checking the values in Go and issuing an unconditional update would leave a gap in which another transaction could change the row.

Consider the two competing requests again.

The first request executes the update successfully:

on_hand = 0
version = 8

The second request executes its update with version = 7. The row no longer matches, so the database changes zero rows.

In Go's database/sql, you can inspect the result with RowsAffected():

go
result, err := tx.ExecContext(ctx, query, qty, itemID, qty, version)
if err != nil {
    return fmt.Errorf("decrement stock: %w", err)
}

affected, err := result.RowsAffected()
if err != nil {
    return fmt.Errorf("read affected rows: %w", err)
}

An affected-row count of one means the update succeeded. A count of zero means the update did not match the conditions. A database error means the operation itself failed.

A zero-row result does not automatically mean the item is sold out. The version might have changed while enough inventory remained.

The retry loop

A failed version comparison requires a fresh read.

Suppose a restaurant has five portions remaining. Two requests each want one portion. Both read version 12.

The first request succeeds and changes the row to:

on_hand = 4
version = 13

The second request's update affects zero rows because its observed version is stale. However, four portions remain. Reporting sold out would be incorrect.

The second request must read the current row again, observe version 13 and four available portions, and retry.

The decision process is:

  1. Read OnHand and Version.
  2. Check whether OnHand is less than the requested quantity.
  3. If stock is insufficient, return ErrSoldOut.
  4. Attempt the guarded decrement using the observed version.
  5. If the decrement succeeds, finish this line.
  6. If the version comparison fails, read again.

The following pseudocode shows the important distinction:

repeat:
    row = Get(itemID)

    if row.OnHand < qty:
        return ErrSoldOut

    updated = Decrement(itemID, qty, row.Version)

    if updated:
        return success

The loop does not assume that a conflicting update means the inventory is gone. It checks the current database state before deciding.

In your stock service, the Tx interface exposes this distinction directly:

go
Get(ctx, itemID) (Row, error)
Decrement(ctx, itemID, qty, version int) (bool, error)

A false result without an error represents an unsuccessful version comparison. Read again rather than treating it as ErrSoldOut.

A missing stock row or an unexpected database failure must also be handled separately from insufficient inventory. Use a Sentinel error such as ErrSoldOut for the expected sold-out condition. Callers can use errors.Is to identify that condition even when other errors have been wrapped with context.

Atomic cart reservations

A restaurant order usually contains multiple items.

For example, one cart might request:

ItemRequested quantity
Item 12
Item 24

Suppose item 1 has five portions available, but item 2 has only one.

If you reserve each line independently, the first reservation succeeds and the second fails. The customer now has an incomplete reservation, and two portions of item 1 remain unavailable to other customers.

You need a single Transaction for all lines in the cart.

A transaction gives the operation one final outcome:

  • Every stock update succeeds and the transaction commits.
  • At least one update fails and the transaction rolls back.

A simplified Go transaction looks like this:

go
tx, err := table.Begin(ctx)
if err != nil {
    return fmt.Errorf("begin reservation: %w", err)
}

for _, line := range lines {
    if err := reserveLine(ctx, tx, line); err != nil {
        _ = tx.Rollback()
        return err
    }
}

if err := tx.Commit(); err != nil {
    return fmt.Errorf("commit reservation: %w", err)
}

The important property is that all lines share the same transaction. If the second line fails, the first line's decrement must not remain committed.

The exercise represents the database boundary through two interfaces:

  • Table starts a transaction.
  • Tx reads rows, decrements stock, increments stock and commits or rolls back.

This design lets the service work with an in-memory fake during testing. You do not need a running MySQL server to exercise the transaction logic.

Remember that a database transaction cannot roll back operations performed in Redis. Those operations require their own cleanup.

Temporary Redis holds

The database protects inventory correctness. Redis can improve the customer experience by indicating that a particular order is temporarily holding an item.

A Stock Hold is a temporary reservation associated with an order and an item. For example:

resv:o-1:42

Here, o-1 is the order ID and 42 is the item ID.

Create the Redis key using SET with NX and EX:

SET resv:o-1:42 3 NX EX 300

The arguments have distinct responsibilities:

  • NX creates the key only when it does not already exist.
  • EX 300 expires the key after 300 seconds.
  • 3 represents the requested quantity in this example.

The five-minute expiration is a Redis TTL, or time-to-live. It prevents an abandoned hold from remaining indefinitely when a customer closes the application or loses connectivity.

If the key is created successfully, the order acquires the hold. If the key already exists, another attempt to reserve the same order and item is rejected.

The hold interface in the exercise represents this behaviour:

go
type Holds interface {
    Hold(ctx context.Context, key string, qty int, ttl time.Duration) (bool, error)
    Release(ctx context.Context, key string) error
}

The service passes the requested quantity and a TTL of exactly 5*time.Minute.

A hold key based on the order and item also supports repeated reservation attempts. This is related to the Idempotency key mechanism used by your order API, but the two mechanisms have different responsibilities.

The order API's idempotency key identifies a repeated order-creation request. The Redis hold identifies a temporary reservation for a particular order and item. Neither replaces the database's stock check.

The relationship between Redis and MySQL

Redis must not become the source of inventory truth.

Imagine two different orders attempting to reserve the same last portion. Their Redis keys differ because their order IDs differ. Both orders might acquire their own holds.

That does not mean both can reserve the portion. The guarded database update still allows only one successful decrement.

The reverse is also important. Redis might be temporarily unavailable. The exercise requires a hold operation that returns an error not to prevent the database reservation. The service continues with MySQL as the authority for stock correctness.

The reservation lifecycle therefore separates hold acquisition from stock modification.

For the current exercise, the sequence is:

  1. Attempt to acquire each line's Redis hold.
  2. Track each hold acquired successfully by the current call.
  3. Start the stock transaction.
  4. Process every line using the guarded decrement and retry logic.
  5. Commit after all lines succeed.
  6. Retain successful holds until they expire.

There are two important failure cases.

Duplicate hold: When Hold returns false, release every hold acquired by the current invocation and return ErrAlreadyReserved. Do not begin the stock transaction.

Stock or transaction failure: Roll back the database transaction and release every hold acquired by the current invocation.

Hold cleanup must be local to the reservation call. A failed request must not release a hold that another request successfully acquired.

The exercise also chooses to continue when Redis returns a hold-operation error. This is a deliberate fail-open policy for the temporary hold, not permission to bypass the guarded database update. A production system should make this availability trade-off explicit.

Restocking inventory

Inventory must also be restored when an order no longer needs its reserved units.

Suppose an order reserved three portions of item 1 and two portions of item 2. Restocking must put those exact quantities back.

The underlying SQL operation increments available stock and changes the version:

sql
UPDATE stock
SET
    on_hand = on_hand + ?,
    version = version + 1
WHERE item_id = ?;

Incrementing the version matters because another transaction might have previously read the row. Its old observation must not be treated as current after the stock changes.

Restocking also needs a transaction. If an order contains multiple lines, you do not want the first item's inventory restored while the second item's increment fails.

The order of operations matters:

  1. Begin a transaction.
  2. Increment every requested line.
  3. Commit the transaction.
  4. Release the corresponding Redis holds.

Never release the holds before the stock transaction commits. Otherwise, another request could see a released hold while the inventory increment has not actually succeeded.

The exercise exposes this operation through:

go
func (s *Service) Restock(
    ctx context.Context,
    orderID string,
    lines []Line,
) error

The same order ID and item IDs identify the holds to release after the successful commit.

In a complete order lifecycle, the order-state transition must also prevent the same cancellation or rejection from restoring inventory twice. That transition belongs to the order workflow. The stock service's responsibility here is to increment the supplied lines transactionally and release the corresponding holds afterward.

Concurrency testing

Sequential tests cannot establish that the reservation algorithm works under contention.

A sequential test might reserve ten portions successfully and then reject an eleventh request. It does not reproduce the situation in which hundreds of requests read the same version before any of them completes its update.

The W8B1 tests use hundreds of Go goroutines to exercise the service concurrently.

A sync.WaitGroup lets the test wait for all workers to finish. A start channel can release workers together to increase the overlap between requests.

A simplified test structure looks like this:

go
var wg sync.WaitGroup
start := make(chan struct{})

for i := 0; i < 500; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        <-start
        // Attempt a reservation.
    }()
}

close(start)
wg.Wait()

The actual tests also count outcomes using atomic counters. Multiple goroutines can update those counters simultaneously, so ordinary unsynchronized integer increments would introduce a Data race.

For example:

go
var wins atomic.Int64
var soldOut atomic.Int64

if err == nil {
    wins.Add(1)
} else if errors.Is(err, ErrSoldOut) {
    soldOut.Add(1)
}

Atomic operations protect the shared counters. The reservation service must independently protect its own shared data through its transaction and guarded-update logic.

The race detector

Go provides the Go race detector to find unsynchronized concurrent access to shared memory.

Run tests with:

bash
go test -race ./...

The race detector instruments the Go program and reports data races it encounters during execution.

It does not prove that your database algorithm prevents overselling. That requires explicit assertions about reservation outcomes and final stock values.

The W8B1 grading tests use in-memory fakes for the Table, Tx and Holds interfaces. They do not require live Redis or MySQL services.

The concurrent scenarios check three important cases.

Five hundred carts competing for ten units

Five hundred concurrent reservations each request one unit from an initial stock of 10.

The required result is:

OutcomeExpected
Successful reservations10
ErrSoldOut responses490
Other errors0
Final stock0

The tests also check that stock never becomes negative.

Larger reservation quantities

Two hundred concurrent requests each ask for three units from an initial stock of 10.

Exactly three requests can succeed. They reserve nine units, leaving exactly one available.

A request must not decrement stock by three when only one remains.

Carts containing two items

One hundred concurrent carts each request one unit of item 1 and one unit of item 2.

The initial stock is:

ItemInitial stock
Item 120
Item 25

Exactly five carts can succeed because item 2 has only five units. Each successful cart also consumes one unit of item 1.

The final state must be:

ResultExpected
Successful carts5
Item 1 stock15
Item 2 stock0
Remaining holds10

The hold count matters. Each successful cart retains two holds, one for each line.

These tests cover more than a single-item race. They verify that a cart cannot leak stock from one item when another item becomes unavailable.

Common failure modes

Several mistakes can make a reservation implementation appear correct in a sequential test but fail under concurrency.

Treating every failed decrement as sold out

A failed version comparison does not prove insufficient inventory. Returning ErrSoldOut immediately can reject a request even when enough stock remains. Read the latest row before deciding.

Updating stock without checking the version

Checking OnHand in Go and then issuing an unconditional decrement leaves a race between the read and update. The database must check both the quantity and version.

Committing each cart line separately

A cart is one reservation. If a later line fails, earlier changes must roll back. Otherwise, inventory remains partially reserved.

Releasing another call's hold

Cleanup must release only keys successfully acquired by the current invocation. Releasing a key merely because a request encountered it can interfere with another reservation.

Releasing holds before restocking commits

The stock increment might fail or the transaction might roll back. Releasing the hold first would make the temporary reservation disappear before the inventory is restored.

Ignoring Go memory races

A database can correctly protect inventory while your Go code still contains a data race in its own shared state. The race detector and explicit inventory assertions check different properties.

Choosing a concurrency strategy

Optimistic locking works well when competing updates are relatively uncommon.

A transaction reads a row and attempts a version-checked update. Most requests can succeed without repeatedly retrying. However, a popular dish with only a few portions left can produce frequent conflicts.

Under heavy contention, many requests might repeatedly read the same version, lose the update race and try again. This increases database work.

You have another option: SELECT FOR UPDATE.

With SELECT ... FOR UPDATE, the transaction locks the selected row before reading it. Other transactions trying to acquire the same row lock must wait until the current transaction commits or rolls back.

The trade-off is straightforward:

StrategySuitable situation
Optimistic lockingConflicts are relatively uncommon
SELECT ... FOR UPDATEA few hot rows receive heavy concurrent traffic

Neither strategy removes the need for the inventory invariant. Both must ensure that a reservation cannot reduce stock below zero.

Choose based on the workload rather than applying one strategy everywhere.

Applying the model to stock reservations

The Stock reservation service exercise puts these ideas together through the Reserve and Restock methods.

Your implementation works with the supplied Table, Tx and Holds interfaces. It must distinguish duplicate holds from sold-out inventory, preserve atomicity across cart lines, and retry version conflicts without allowing stock to become negative.

The important boundary is between temporary reservation state in Redis and actual inventory in the database. Redis helps manage the customer's hold, but the guarded database decrement decides whether the requested units can be reserved.

The concurrency tests then check whether that distinction holds when hundreds of goroutines compete for the same inventory.

Check your understanding

Question 1 of 4

Two carts read item 42 with on_hand = 3 and version = 9. The first cart reserves two units and successfully updates the row. The second cart also wants two units. What should its next operation be after its guarded decrement affects zero rows?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from.

Finished Lesson 8.1?