Nov 17, 20268 min read

Marketplace Order Escrow Backend: Holds, Releases, Refunds and Disputes

Hold a marketplace payment when an order is accepted, release it after delivery is confirmed, refund it on a lost dispute, and keep those transitions in a ledger the two sides can audit.

Illustration for Marketplace Order Escrow Backend: Holds, Releases, Refunds and Disputes

A marketplace cannot pay the seller the moment the buyer checks out. The platform has to hold the funds until delivery is confirmed, or return them if a dispute goes the buyer's way, and every one of those transitions has to be something you can show both sides later.

The hard part is the races: a buyer confirms while a dispute is being opened, an auto-release job runs while a refund is in flight, and a payment provider webhook arrives twice. This guide designs an escrow backend around a hold row, a ledger, and conditional updates, then builds it in Go with Encore in your own AWS or GCP account.

Money transmission, licensing and fund safeguarding are the team's legal and compliance responsibility. Encore does not provide them.

Escrow at a glance

EventHold becomesLedger entrySide effect
Order acceptedheldholdCapture or authorize with the payment provider, idempotent key = hold id
Buyer confirms delivery, or auto-release fires with no disputereleasedreleaseTransfer to the seller
Dispute opened before releaseheld still, dispute_open on the orderdispute_openedPause auto-release
Dispute resolved for the buyerrefundedrefundRefund the buyer
Dispute resolved for the sellerreleasedreleaseTransfer to the seller

Holds, ledgers and races

Keep a holds row per order with a status of held, released or refunded, and an append-only ledger table for every transition. The payment provider is downstream of the ledger: write the row first, then call the provider with the hold id as the idempotency key. If the provider call fails, a retry of the same transition sees the existing row and tries the side effect again, or a job does.

Auto-release is a scheduled scan of holds whose auto_release_at has passed and whose order has no open dispute. The UPDATE ... WHERE status = 'held' is the lock: a dispute that commits first causes the job to skip the row.

How do you build this with Encore?

Encore

Encore is a backend framework with built-in infrastructure. You declare the database, the topic and the schedule in the same package as the handlers, and encore run starts local Postgres so you can exercise the flow before opening a pull request. On deploy to your own AWS or GCP account, Encore provisions those resources and Encore provisions an IAM role for the service, or a service account on GCP.

Encore cron jobs are platform managed and do not run locally or in preview environments. Call AutoReleaseHolds from the local development dashboard to test it.

Set up the app

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

Run in your terminal to get started locally.

-- escrow/migrations/1_escrow.up.sql CREATE TABLE orders ( id TEXT PRIMARY KEY, buyer_id TEXT NOT NULL, seller_id TEXT NOT NULL, amount_cents INT NOT NULL CHECK (amount_cents > 0), currency TEXT NOT NULL, dispute_open BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE holds ( id TEXT PRIMARY KEY, order_id TEXT NOT NULL UNIQUE REFERENCES orders (id), status TEXT NOT NULL CHECK (status IN ('held', 'released', 'refunded')), auto_release_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE ledger ( id BIGSERIAL PRIMARY KEY, hold_id TEXT NOT NULL REFERENCES holds (id), entry_type TEXT NOT NULL CHECK (entry_type IN ('hold', 'release', 'refund', 'dispute_opened')), amount_cents INT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- Transition events to publish, written in the same transaction as the status change. CREATE TABLE transition_outbox ( seq BIGSERIAL PRIMARY KEY, hold_id TEXT NOT NULL, type TEXT NOT NULL, UNIQUE (hold_id, type) );
// escrow/escrow.go package escrow import ( "context" "errors" "time" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("escrow", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Transition struct { HoldID string `json:"hold_id"` Type string `json:"type"` } var Transitions = pubsub.NewTopic[*Transition]("escrow-transitions", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type AcceptIn struct { OrderID, BuyerID, SellerID, Currency string AmountCents int } //encore:api public method=POST path=/orders/:id/accept func Accept(ctx context.Context, id string, in AcceptIn) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec(ctx, ` INSERT INTO orders (id, buyer_id, seller_id, amount_cents, currency) VALUES ($1, $2, $3, $4, $5)`, id, in.BuyerID, in.SellerID, in.AmountCents, in.Currency); err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO holds (id, order_id, status, auto_release_at) VALUES ($1, $2, 'held', now() + interval '14 days')`, "h_"+id, id); err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO ledger (hold_id, entry_type, amount_cents) VALUES ($1, 'hold', $2)`, "h_"+id, in.AmountCents); err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO transition_outbox (hold_id, type) VALUES ($1, 'hold')`, "h_"+id); err != nil { return err } if err := tx.Commit(); err != nil { return err } return flushTransitions(ctx, "h_"+id) } //encore:api public method=POST path=/orders/:id/confirm-delivery func ConfirmDelivery(ctx context.Context, id string) error { return release(ctx, id) } func release(ctx context.Context, orderID string) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var holdID string err = tx.QueryRow(ctx, ` UPDATE holds SET status = 'released', updated_at = now() WHERE order_id = $1 AND status = 'held' AND NOT EXISTS (SELECT 1 FROM orders WHERE id = $1 AND dispute_open) RETURNING id`, orderID).Scan(&holdID) if errors.Is(err, sqldb.ErrNoRows) { // Already released or not releasable; still retry a leftover outbox row. _ = tx.Rollback() var existing string qerr := db.QueryRow(ctx, `SELECT id FROM holds WHERE order_id = $1`, orderID).Scan(&existing) if qerr != nil { return errConflict("hold is not releasable") } if ferr := flushTransitions(ctx, existing); ferr != nil { return ferr } return errConflict("hold is not releasable") } else if err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO ledger (hold_id, entry_type, amount_cents) SELECT $1, 'release', amount_cents FROM orders WHERE id = $2`, holdID, orderID); err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO transition_outbox (hold_id, type) VALUES ($1, 'release') ON CONFLICT (hold_id, type) DO NOTHING`, holdID); err != nil { return err } if err := tx.Commit(); err != nil { return err } return flushTransitions(ctx, holdID) } // Publish any committed transitions that have not yet been sent. A failed // publish leaves the row in place so the next confirm or auto-release retries it. func flushTransitions(ctx context.Context, holdID string) error { rows, err := db.Query(ctx, ` SELECT seq, hold_id, type FROM transition_outbox WHERE hold_id = $1 ORDER BY seq`, holdID) if err != nil { return err } defer rows.Close() var pending []struct{ seq int64; id, typ string } for rows.Next() { var row struct{ seq int64; id, typ string } if err := rows.Scan(&row.seq, &row.id, &row.typ); err != nil { return err } pending = append(pending, row) } if err := rows.Err(); err != nil { return err } // Publish in sequence order so a release cannot overtake a pending hold. for _, row := range pending { if _, err := Transitions.Publish(ctx, &Transition{HoldID: row.id, Type: row.typ}); err != nil { return err } if _, err := db.Exec(ctx, `DELETE FROM transition_outbox WHERE seq = $1`, row.seq); err != nil { return err } } return nil } var _ = cron.NewJob("auto-release", cron.JobConfig{ Title: "Auto-release held escrow with no open dispute", Every: 1 * cron.Hour, Endpoint: AutoReleaseHolds, }) //encore:api private func AutoReleaseHolds(ctx context.Context) error { rows, err := db.Query(ctx, ` SELECT order_id FROM holds WHERE status = 'held' AND auto_release_at <= now()`) if err != nil { return err } var due []string for rows.Next() { var orderID string if err := rows.Scan(&orderID); err != nil { rows.Close() return err } due = append(due, orderID) } err = rows.Err() rows.Close() if err != nil { return err } for _, orderID := range due { if err := release(ctx, orderID); err != nil { // A conflict means a dispute or a confirm won the race; that is fine. continue } } // Retry leftover outbox rows in sequence, including a release that committed before a failed publish. pending, err := db.Query(ctx, ` SELECT hold_id FROM transition_outbox GROUP BY hold_id ORDER BY MIN(seq)`) if err != nil { return err } var holds []string for pending.Next() { var holdID string if err := pending.Scan(&holdID); err != nil { pending.Close() return err } holds = append(holds, holdID) } err = pending.Err() pending.Close() if err != nil { return err } for _, holdID := range holds { if err := flushTransitions(ctx, holdID); err != nil { return err } } return nil } func errConflict(msg string) error { return &conflictError{msg} } type conflictError struct{ s string } func (e *conflictError) Error() string { return e.s }

The hold transition and the ledger insert run in one transaction, and a transition_outbox row is written in that same transaction so a failed publish is retried on the next confirm or auto-release. A subscriber on escrow-transitions should call the payment provider with the hold id as the idempotency key, and should treat a second delivery as already done. Opening a dispute is a conditional update that sets dispute_open only while the hold is still held.

Best fit: a marketplace that needs escrow transitions in one database, with the payment provider as a subscriber.

Holds and a ledger in your own Postgres

Create the hold row in the same transaction as the accepted order, and record a ledger entry for the hold. Release, refund and dispute paths must all use a conditional UPDATE such as WHERE status = 'held', so only one of them can win. Drive auto-release from a scheduled job that selects held rows past their deadline, or from EventBridge Scheduler if that job already lives in AWS. The payment provider should be a subscriber of a transition event, not a second writer of hold status.

How to choose

Build this with Encore when you want the hold, the ledger, the topic and the auto-release job declared in one Go service, tested against local Postgres, and provisioned in your own cloud. Build it by hand on RDS, SQS and EventBridge Scheduler when those resources already exist in Terraform and the API is a plain binary. In both cases the conditional UPDATE on holds.status is the part that prevents a refund and a release from both succeeding.

Frequently asked questions

How should a marketplace hold funds in escrow?

Create a hold row in the same transaction as the accepted order, keyed by order id, and record a ledger entry for the hold. Do not mark the order paid to the seller until a release event arrives. The payment provider capture or transfer is a side effect after the ledger write, with an idempotency key so a retry cannot capture twice.

When should escrow be released to the seller?

Release when the buyer confirms delivery, or when a configured auto-release time passes without an open dispute. The release updates the hold in a conditional UPDATE that only succeeds in the held state, writes a ledger entry, and then pays the seller.

How do I keep a refund from racing a release?

Both paths must use a conditional update on the hold status, such as WHERE status = 'held'. The first transaction to commit wins; the second sees zero rows and returns a conflict. Open a dispute before the auto-release time if the buyer needs a review window.

How do I build this with Encore?

Declare a Postgres database, a topic for escrow transitions and a cron job for auto-release in Go. encore run starts Postgres locally so you can accept, confirm and dispute an order before opening a pull request. On deploy, Encore provisions those resources in your own AWS or GCP account. Encore cron jobs are platform managed and do not run locally or in preview environments, so call the auto-release endpoint yourself to test it.

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