Nov 20, 20267 min read

Build an Ecommerce Checkout Backend: Carts, Stock Holds and Payments

Build the backend of an ecommerce checkout: turning a cart into an order with stock holds that expire, charging with idempotency keys, confirming payment from a webhook, and releasing abandoned holds on a schedule, in Go.

Illustration for Build an Ecommerce Checkout Backend: Carts, Stock Holds and Payments

Checkout is where an ecommerce backend stops being a catalog. It has to take a cart, make sure the goods exist, collect the money exactly once and leave a consistent order whichever step fails halfway.

The hard parts are about timing: two buyers for the last unit, a payment that times out and is retried, a customer who abandons the page with stock still reserved. This guide builds the checkout in Go on Postgres, covering holds, payment and confirmation.

What does a checkout backend do?

StepWhat happensWhere it lives
Create orderValidate the cart, price it on the server, create a pending orderPostgres transaction
Hold stockReserve units for a fixed timeSame transaction
Start paymentCreate a payment with an idempotency keyPayment provider
ConfirmWebhook marks the order paid and converts holds to salesWebhook handler
ReleaseExpired or failed holds return to stockScheduled job

Always price the cart on the server from your own product table. Totals sent by the browser are only a display value, never an input to the charge.

How do you hold stock without overselling?

Keep available on each product and an order_holds table with an expiry. In the checkout transaction, lock the product rows with SELECT ... FOR UPDATE in ID order, which prevents deadlocks between two carts that contain the same products in a different order. Check available >= quantity, decrement it, and insert the hold with expires_at = now() + interval '15 minutes'. A reservation that is part of the same transaction as the order cannot leak, since both commit or neither does. The trade-offs between lock styles are in optimistic vs pessimistic locking.

Choose the hold time from your payment flow: long enough to complete a 3-D Secure challenge, short enough that abandoned carts do not lock scarce stock.

How do you charge exactly once?

Networks fail after the provider has acted: create the payment with an idempotency key built from the order ID, which the provider uses to return the original result for a repeated request. Stripe's idempotency documentation describes the behavior, and most payment providers have an equivalent. Store the provider's payment ID on the order as soon as you have it.

Confirm from the webhook, not from the browser redirect, because customers close tabs. Verify the webhook signature, look up the order by payment ID, and mark it paid only if it is still pending. Providers retry webhooks, so the handler must be safe to run many times, as covered in Stripe webhooks in Go.

What happens to abandoned checkouts?

A scheduled job finds pending orders whose hold has expired, marks them expired and returns the units to available. Do both in one transaction and guard with the order status, so a payment that lands at the same moment as the release does not create a paid order with no stock. If a webhook arrives for an expired order, refund it or re-check stock, and tell the customer.

Building it with Encore

Encore

Encore is a backend framework with built-in infrastructure. The checkout service declares its Postgres database and a cron job for releasing holds in Go, and Encore provisions them on AWS or GCP in your own account on deploy. The payment provider key is an Encore secret.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- checkout/migrations/1_create_tables.up.sql CREATE TABLE products ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL, price_cents BIGINT NOT NULL CHECK (price_cents >= 0), available INT NOT NULL CHECK (available >= 0) ); CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'paid', 'expired')), total_cents BIGINT NOT NULL, payment_id TEXT, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE order_lines ( order_id BIGINT NOT NULL REFERENCES orders(id), product_id BIGINT NOT NULL REFERENCES products(id), quantity INT NOT NULL CHECK (quantity > 0), PRIMARY KEY (order_id, product_id) );
// checkout/checkout.go package checkout import ( "context" "errors" "sort" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("checkout", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Line struct { ProductID int64 `json:"product_id"` Quantity int `json:"quantity"` } type CheckoutParams struct { Lines []Line `json:"lines"` } type CheckoutResponse struct { OrderID int64 `json:"order_id"` TotalCents int64 `json:"total_cents"` } //encore:api public method=POST path=/checkout func Checkout(ctx context.Context, p *CheckoutParams) (*CheckoutResponse, error) { if len(p.Lines) == 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "empty cart"} } // Lock rows in ID order so two carts never wait on each other in a cycle. lines := append([]Line(nil), p.Lines...) sort.Slice(lines, func(i, j int) bool { return lines[i].ProductID < lines[j].ProductID }) tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() var total int64 for _, l := range lines { var price int64 var available int err := tx.QueryRow(ctx, `SELECT price_cents, available FROM products WHERE id = $1 FOR UPDATE`, l.ProductID). Scan(&price, &available) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "unknown product"} } else if err != nil { return nil, err } if l.Quantity <= 0 || available < l.Quantity { return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "not enough stock"} } if _, err := tx.Exec(ctx, `UPDATE products SET available = available - $2 WHERE id = $1`, l.ProductID, l.Quantity); err != nil { return nil, err } total += price * int64(l.Quantity) } var orderID int64 if err := tx.QueryRow(ctx, `INSERT INTO orders (total_cents, expires_at) VALUES ($1, now() + interval '15 minutes') RETURNING id`, total).Scan(&orderID); err != nil { return nil, err } for _, l := range lines { if _, err := tx.Exec(ctx, `INSERT INTO order_lines (order_id, product_id, quantity) VALUES ($1, $2, $3)`, orderID, l.ProductID, l.Quantity); err != nil { return nil, err } } if err := tx.Commit(); err != nil { return nil, err } // Next: create the payment with the idempotency key "order-<orderID>". return &CheckoutResponse{OrderID: orderID, TotalCents: total}, nil } // MarkPaid is called from the verified payment webhook. func MarkPaid(ctx context.Context, orderID int64, paymentID string) error { _, err := db.Exec(ctx, `UPDATE orders SET status = 'paid', payment_id = $2 WHERE id = $1 AND status = 'pending'`, orderID, paymentID) return err } //encore:api private func ReleaseExpired(ctx context.Context) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() // Expire pending orders past their hold, and return their units, in one statement. _, err = tx.Exec(ctx, ` WITH expired AS ( UPDATE orders SET status = 'expired' WHERE status = 'pending' AND expires_at < now() RETURNING id ) UPDATE products p SET available = p.available + l.quantity FROM order_lines l JOIN expired e ON e.id = l.order_id WHERE p.id = l.product_id`) if err != nil { return err } return tx.Commit() } var _ = cron.NewJob("release-expired-holds", cron.JobConfig{ Title: "Release expired stock holds", Every: 5 * cron.Minute, Endpoint: ReleaseExpired, })

The hold is the decrement itself: available drops inside the same transaction that creates the order, and the release job adds it back only for orders that are still pending when it runs, so a paid order is never touched. If two units of one product appear in the cart as separate lines, merge them first. Encore cron jobs are managed by the platform and run in cloud environments, not under encore run or in preview environments, so call ReleaseExpired from the local development dashboard when testing. Each checkout appears as a trace with its queries, which makes lock waits visible.

A coding agent can add a coupon table, its price rule and the migration in one change, run concurrent checkouts against the local database, and ship it with whatever new infrastructure it needs.

Best fit: Ecommerce teams building a custom checkout in Go who want holds, orders and the release job in one service on their own AWS or GCP account.

Frequently asked questions

How do you prevent overselling during checkout?

Inside the checkout transaction, lock the product rows with SELECT FOR UPDATE in a consistent order, check available stock and decrement it while creating a hold for the order. Concurrent checkouts for the same product wait for the lock and see the reduced stock, so the last unit goes to exactly one buyer.

What is a stock hold in checkout?

A hold reserves units for an order for a limited time, such as 15 minutes, while the customer pays. If payment succeeds the hold becomes a sale, and if the time passes or payment fails a scheduled job releases the units back to available stock.

How do you avoid charging a customer twice at checkout?

Create the payment with an idempotency key derived from the order ID, so a retried request after a timeout returns the same payment instead of creating a second one. Confirm the order from the payment provider's webhook, and make the webhook handler idempotent too.

Can I build a checkout backend with Encore?

Yes. A Go service declares the Postgres database and a cron job for releasing expired holds, and Encore provisions them in your own AWS or GCP account on deploy. Postgres runs locally under encore run, while cron jobs run in cloud environments, so call the release endpoint by hand when testing locally.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders