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:
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) errorAcceptance criteria
- Reserving 3 units of item
1from an initial stock of 10 leavesOnHandat 7. The service retains a hold with keyresv:o-1:1, quantity 3 and a TTL of exactly 5 minutes. - Reserving 3 units when item
1has only 2 available returnsErrSoldOutand leaves its stock at 2. - When a cart requests 2 units of item
1and 4 units of item2, whose initial stocks are 5 and 1, the later line returnsErrSoldOut. The transaction restores both stocks to 5 and 1, and no holds remain. - Reserving 4 units of item
1for ordero-1twice returnsErrAlreadyReservedon the second call. Stock is decremented only once, leaving 6 units. - Reserving 3 units of item
1and 2 units of item2, 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 returnErrSoldOut, 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
1and2, 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:
cd backend
make test W=8B1The 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.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Inventory holds
2 items
- 8.1Optimistic locking for stocknot completed
- 8.2Stock reservation servicenot completed
Up next · Module 2 · 2 items · about 4 h 30 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- The stock service implements the supplied interfaces and constructor.
- Reservations acquire correctly keyed five-minute holds.
- Cart reservations commit or roll back as a single transaction.
- Restocking restores inventory before releasing holds.
- Concurrent reservations never oversell available stock.
- The W8B1 tests pass with the Go race detector.
Commands
cd backend && make test W=8B1Tests
TestW8B1_ReserveTakesStockAndKeepsAFiveMinuteHoldinbackend/internal/stock/stock_test.goTestW8B1_ReserveFailsWithErrSoldOutWhenStockIsShortinbackend/internal/stock/stock_test.goTestW8B1_AFailedLineRollsBackEarlierLinesAndReleasesEveryHoldinbackend/internal/stock/stock_test.goTestW8B1_ReservingTheSameOrderTwiceTakesStockOnceinbackend/internal/stock/stock_test.goTestW8B1_RestockPutsTheUnitsBackAndReleasesTheHoldsinbackend/internal/stock/stock_test.goTestW8B1_FiveHundredCartsRaceForTenUnitsAndExactlyTenWininbackend/internal/stock/stock_test.goTestW8B1_BiggerLinesRaceWithoutOversellinginbackend/internal/stock/stock_test.goTestW8B1_RacingCartsWithTwoLinesNeverLeakStockinbackend/internal/stock/stock_test.go