A backend design for marketplace auctions: concurrent bids with row locks, proxy bidding with maximum bids and increments, soft close against sniping, idempotent bid requests, and closing auctions on time.

An auction backend has one table that everybody writes to at the same moment: the auction's current price. Getting it right means serialising bids per auction, applying proxy bidding rules in one place, and making sure no bid lands after the close.
The rest, like outbid emails and checkout, can happen a few seconds later from events, as in the implementation below.
Two bids that both read a price of 100 and both write 110 leave one bidder thinking they lead when they do not. In Postgres, SELECT ... FOR UPDATE on the auction row makes the second transaction wait until the first commits, then read the new state, as the row-level locking docs describe. The lock is per auction, so bids on different items do not wait on each other, and the transaction stays short: lock, compute, write, commit.
Serializable isolation would also catch the conflict, but it aborts one of the transactions and leaves the retry to you, per the isolation docs. On a hot auction in its last minute, a lock queue is easier to reason about than a retry loop.
Each bidder submits a maximum, and the price moves only as far as needed: one increment above the second-highest maximum, capped at the leader's maximum. A new bid either raises the leader's own maximum, takes the lead if it beats the leader's maximum, or loses and pushes the price up to just above itself. With a 1.00 increment, a leader holding a 50.00 maximum and a new bid of 30.00, the price moves to 31.00 and the leader keeps the lead. A tie goes to the earlier bidder, since a new maximum has to be strictly higher to take over. Keep these rules in a pure function, so they can be tested without a database.
A soft close pushes ends_at out to two minutes from now whenever a bid arrives in the last two minutes. The bid transaction rejects anything after ends_at under the same lock, so the job that closes auctions can run up to a minute late without letting a late bid in. Retried requests carry an idempotency key, the same pattern Stripe's API uses, stored with a unique constraint, so a client that times out and retries gets the original result.
Encore is a backend framework with built-in infrastructure, so the auction database, the event topics and the closing job are declared in the TypeScript that uses them. Deploying provisions Postgres and Pub/Sub in your own AWS or GCP account, and the cron job runs on Encore's managed scheduler with no extra cloud resources.

Run in your terminal to get started locally.
The proxy bidding rules as a pure function:
// auctions/rules.ts
export interface AuctionState {
priceCents: number;
leaderId: string | null;
leaderMaxCents: number;
incrementCents: number;
}
export type BidResult =
| { ok: true; state: AuctionState; outbidId: string | null }
| { ok: false; reason: string };
export function applyBid(s: AuctionState, bidderId: string, maxCents: number): BidResult {
if (s.leaderId === null) {
if (maxCents < s.priceCents) return { ok: false, reason: "below starting price" };
return { ok: true, state: { ...s, leaderId: bidderId, leaderMaxCents: maxCents }, outbidId: null };
}
if (bidderId === s.leaderId) {
// Raising your own maximum does not move the price.
if (maxCents <= s.leaderMaxCents) return { ok: false, reason: "not above your maximum" };
return { ok: true, state: { ...s, leaderMaxCents: maxCents }, outbidId: null };
}
if (maxCents < s.priceCents + s.incrementCents) return { ok: false, reason: "below minimum bid" };
if (maxCents > s.leaderMaxCents) {
const price = Math.min(maxCents, s.leaderMaxCents + s.incrementCents);
return {
ok: true,
state: { ...s, priceCents: price, leaderId: bidderId, leaderMaxCents: maxCents },
outbidId: s.leaderId,
};
}
// The leader's maximum covers this bid; the price rises to just above it.
const price = Math.min(s.leaderMaxCents, maxCents + s.incrementCents);
return { ok: true, state: { ...s, priceCents: price }, outbidId: bidderId };
}
The bid endpoint, the outbid and closed events, and the job that closes auctions:
// auctions/auctions.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
import { applyBid } from "./rules";
const db = new SQLDatabase("auctions", { migrations: "./migrations" });
export const outbid = new Topic<{ auctionId: string; bidderId: string; priceCents: number }>(
"auction-outbid",
{ deliveryGuarantee: "at-least-once" },
);
export const closed = new Topic<{ auctionId: string; winnerId: string | null; priceCents: number }>(
"auction-closed",
{ deliveryGuarantee: "at-least-once" },
);
interface BidRequest {
auctionId: string;
bidderId: string; // from your auth handler in a real app
maxCents: number;
idempotencyKey: string;
}
interface BidResponse {
leading: boolean;
priceCents: number;
endsAt: string;
}
const SOFT_CLOSE_MS = 2 * 60 * 1000;
export const bid = api(
{ expose: true, method: "POST", path: "/auctions/:auctionId/bids" },
async (req: BidRequest): Promise<BidResponse> => {
const tx = await db.begin();
try {
// Bids on this auction wait here until the previous one commits.
const a = await tx.queryRow<{
price_cents: number; leader_id: string | null; leader_max_cents: number;
increment_cents: number; ends_at: Date; status: string;
}>`SELECT price_cents, leader_id, leader_max_cents, increment_cents, ends_at, status
FROM auctions WHERE id = ${req.auctionId} FOR UPDATE`;
if (!a) throw APIError.notFound("auction not found");
// Checked under the lock, so two copies of one retry cannot both bid.
const prior = await tx.queryRow<{ response: BidResponse }>`
SELECT response FROM bids WHERE idempotency_key = ${req.idempotencyKey}`;
if (prior) {
await tx.rollback();
return prior.response;
}
const now = new Date();
if (a.status !== "open" || now >= a.ends_at) throw APIError.failedPrecondition("auction has ended");
const result = applyBid(
{ priceCents: a.price_cents, leaderId: a.leader_id, leaderMaxCents: a.leader_max_cents, incrementCents: a.increment_cents },
req.bidderId,
req.maxCents,
);
if (!result.ok) throw APIError.invalidArgument(result.reason);
// Soft close: a bid in the last two minutes keeps the auction open two more.
const endsAt =
a.ends_at.getTime() - now.getTime() < SOFT_CLOSE_MS ? new Date(now.getTime() + SOFT_CLOSE_MS) : a.ends_at;
const s = result.state;
await tx.exec`
UPDATE auctions SET price_cents = ${s.priceCents}, leader_id = ${s.leaderId},
leader_max_cents = ${s.leaderMaxCents}, ends_at = ${endsAt}
WHERE id = ${req.auctionId}`;
const response: BidResponse = {
leading: s.leaderId === req.bidderId,
priceCents: s.priceCents,
endsAt: endsAt.toISOString(),
};
await tx.exec`
INSERT INTO bids (idempotency_key, auction_id, bidder_id, max_cents, response)
VALUES (${req.idempotencyKey}, ${req.auctionId}, ${req.bidderId}, ${req.maxCents}, ${JSON.stringify(response)}::jsonb)`;
await tx.commit();
if (result.outbidId && result.outbidId !== req.bidderId) {
await outbid.publish({ auctionId: req.auctionId, bidderId: result.outbidId, priceCents: s.priceCents });
}
return response;
} catch (err) {
await tx.rollback().catch(() => {});
throw err;
}
},
);
export const closeEnded = api(
{ expose: false, method: "POST", path: "/auctions/close-ended" },
async (): Promise<{ closed: number }> => {
let n = 0;
for await (const row of db.query<{ id: string; leader_id: string | null; price_cents: number }>`
UPDATE auctions SET status = 'closed'
WHERE status = 'open' AND ends_at <= now()
RETURNING id, leader_id, price_cents`) {
await closed.publish({ auctionId: row.id, winnerId: row.leader_id, priceCents: row.price_cents });
n++;
}
return { closed: n };
},
);
new CronJob("close-ended-auctions", {
title: "Close auctions past their end time",
every: "1m",
endpoint: closeEnded,
});
-- auctions/migrations/1_init.up.sql
CREATE TABLE auctions (
id TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
price_cents INTEGER NOT NULL,
increment_cents INTEGER NOT NULL,
leader_id TEXT,
leader_max_cents INTEGER NOT NULL DEFAULT 0,
ends_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX auctions_open_ends_idx ON auctions (ends_at) WHERE status = 'open';
CREATE TABLE bids (
idempotency_key TEXT PRIMARY KEY,
auction_id TEXT NOT NULL REFERENCES auctions (id),
bidder_id TEXT NOT NULL,
max_cents INTEGER NOT NULL,
response JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
A notifications service subscribes to auction-outbid and a payments service to auction-closed, each as a Pub/Sub subscription in its own service, so a slow email provider never holds the auction lock. Locally, encore run starts Postgres and the topics, and closeEnded can be called by hand, since cron schedules only run in deployed environments. The databases docs cover the transaction API used here, and in a real app bidderId comes from the auth handler instead of the request body.
When a coding agent adds a rule, such as a reserve price, it changes applyBid, adds a test and a migration in the same service and runs them locally, and the deploy applies the migration in your account without a separate infrastructure change.
Best fit: Marketplace teams building auctions who want the database, events and closing schedule in their own cloud account, with the bidding rules in one tested function.
Lock the auction row with SELECT FOR UPDATE inside the bid transaction, so the second bid waits until the first commits and is then checked against the new price. Without the lock, both read the same price and both can win.
The bidder submits a maximum, and the system bids on their behalf only as much as needed to lead, one increment above the next highest maximum. The current price only reaches the leader's maximum if someone else bids that high.
With a soft close: a bid in the last few minutes pushes the end time out by a fixed window, so other bidders always get a chance to respond. Proxy bidding also reduces sniping, since a last-second bid has to beat the leader's hidden maximum.
The bid transaction rejects any bid after ends_at, so the close itself can run a little late without letting late bids in. A job that runs every minute marks ended auctions closed and publishes an event for payment and notifications.
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.