Stock reservation service

You build a stock reservation service that reserves cart lines and restores them on restock. Version-checked decrements prevent concurrent carts from overselling inventory.

Ticket

Build the stock reservation service in backend/internal/stock. It reserves inventory for every line in a cart, rejects duplicate reservations, and restores units when an order is restocked.

Two carts can otherwise buy the last plate. Redis holds help identify duplicate reservations, but the database must prevent an Overselling independently. Use Optimistic locking and a Guarded UPDATE to protect stock.

The tests use fakes for the following exported contract:

go
package stock

import (
    "context"
    "time"
)

type Row struct {
    OnHand  int
    Version int
}

type Line struct {
    ItemID int64
    Qty    int
}

var ErrSoldOut error
var ErrAlreadyReserved error

type Tx interface {
    Get(ctx context.Context, itemID int64) (Row, error)
    Decrement(ctx context.Context, itemID int64, qty, version int) (bool, error)
    Increment(ctx context.Context, itemID int64, qty int) error
    Commit() error
    Rollback() error
}

type Table interface {
    Begin(ctx context.Context) (Tx, error)
}

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

type Service struct {
    table Table
    holds Holds
}

func NewService(table Table, holds Holds) *Service
func (s *Service) Reserve(ctx context.Context, orderID string, lines []Line) error
func (s *Service) Restock(ctx context.Context, orderID string, lines []Line) error

Acceptance criteria

  • Reserving 3 units of item 1 from an initial stock of 10 leaves OnHand at 7. The service retains a hold with key resv:o-1:1, quantity 3 and a TTL of exactly 5 minutes.
  • Reserving 3 units when item 1 has only 2 available returns ErrSoldOut and leaves its stock at 2.
  • When a cart requests 2 units of item 1 and 4 units of item 2, whose initial stocks are 5 and 1, the later line returns ErrSoldOut. The transaction restores both stocks to 5 and 1, and no holds remain.
  • Reserving 4 units of item 1 for order o-1 twice returns ErrAlreadyReserved on the second call. Stock is decremented only once, leaving 6 units.
  • Reserving 3 units of item 1 and 2 units of item 2, then restocking the same order, restores both stocks to 10 and releases all holds. The same order can reserve those lines again.
  • When 500 Goroutines calls compete for 10 units of item 1, exactly 10 reservations succeed, 490 return ErrSoldOut, and no other errors occur. Final stock is 0, and stock never becomes negative.
  • When 200 concurrent calls each request 3 units against 10 available, exactly 3 reservations succeed. Final stock is 1 and never becomes negative.
  • When 100 concurrent carts each request one unit of items 1 and 2, starting with 20 and 5 units respectively, exactly 5 carts succeed. Final stocks are 15 and 0, with exactly 10 holds remaining.

Constraints

  • Do not modify the provided tests.

Design direction

Keep the reservation rules in internal/stock. Let Table and Tx represent the database transaction boundary, and let Holds isolate the service from the Redis implementation. The supplied fakes should be enough to exercise the service without live infrastructure.

Treat Redis as a duplicate-reservation guard, not the source of inventory truth. A SET NX-style operation can acquire a Stock Hold with a Redis TTL, but the database must still decide whether stock can be decremented.

Use one transaction for all lines in a cart. A failure on a later line must not leave earlier lines committed. Keep track of the holds acquired by the current call so cleanup does not release another reservation's hold.

For a guarded decrement, read the row's OnHand and Version, check availability, then attempt the update with that version. A failed version comparison means another transaction changed the row. Read again and retry rather than treating the conflict as sold out.

For restocking, commit the inventory increments before releasing reservation holds. This avoids making a reservation available again before its units have actually been restored.

How to check your work

Run the stock tests from the backend directory:

bash
cd backend
make test W=8B1

The command runs the W8B1 tests with the Go race detector enabled, including concurrent reservations across hundreds of Goroutines calls. Read the first failing assertion to see which stock value, hold, or concurrency outcome differs from the expected result.

Finished Exercise 8.2?

Inventory holds

2 items

  • 8.1Optimistic locking for stocknot completed
  • 8.2Stock reservation servicenot completed

Payment workflow

Up next · Module 2 · 2 items · about 4 h 30 min

Start module 2

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. The stock service implements the supplied interfaces and constructor.
  2. Reservations acquire correctly keyed five-minute holds.
  3. Cart reservations commit or roll back as a single transaction.
  4. Restocking restores inventory before releasing holds.
  5. Concurrent reservations never oversell available stock.
  6. The W8B1 tests pass with the Go race detector.

Commands

terminal
cd backend && make test W=8B1

Tests

  • TestW8B1_ReserveTakesStockAndKeepsAFiveMinuteHold in backend/internal/stock/stock_test.go
  • TestW8B1_ReserveFailsWithErrSoldOutWhenStockIsShort in backend/internal/stock/stock_test.go
  • TestW8B1_AFailedLineRollsBackEarlierLinesAndReleasesEveryHold in backend/internal/stock/stock_test.go
  • TestW8B1_ReservingTheSameOrderTwiceTakesStockOnce in backend/internal/stock/stock_test.go
  • TestW8B1_RestockPutsTheUnitsBackAndReleasesTheHolds in backend/internal/stock/stock_test.go
  • TestW8B1_FiveHundredCartsRaceForTenUnitsAndExactlyTenWin in backend/internal/stock/stock_test.go
  • TestW8B1_BiggerLinesRaceWithoutOverselling in backend/internal/stock/stock_test.go
  • TestW8B1_RacingCartsWithTwoLinesNeverLeakStock in backend/internal/stock/stock_test.go