How to build coupon codes that cannot be over-redeemed: a data model with limits and expiry, a redemption that locks the coupon row, safe retries per order, releasing a coupon when an order is cancelled, and a TypeScript version on Postgres.

A coupon looks like a string and a percentage until the first promotion goes out. Then the backend has to enforce a maximum number of uses, one use per customer, a time window and a minimum order value, even when two checkouts claim the last use in the same millisecond.
Coupons that can be redeemed past their limit tend to be found by customers before they are found by engineers, and the discount cannot be taken back after the order ships. This guide builds the redemption path so the limits hold under concurrency, and it can be retried and reversed.
Payment providers model the same fields, for example the Stripe coupon object carries max_redemptions, redeem_by and times_redeemed, and a store needs those plus a per-customer limit and a minimum order value. The rules fall into three groups.
Everything that depends on a count has to be checked and updated under the same lock, since a check followed by an update from two separate requests lets both through.
A coupons row holds the rules and a redeemed_count, and a redemptions row records each use with the order it belongs to. The percent and fixed amount are mutually exclusive, which a check constraint enforces so a bad import cannot create a coupon that is both.
The migration in the sample further down creates both tables, with a partial index on (code, customer_id) that covers the per-customer count, which only needs redemptions that have not been released.
Open a transaction and read the coupon with SELECT ... FOR UPDATE. Per the PostgreSQL locking documentation, a row-level lock blocks other transactions that try to lock or update the same row until the first one commits, so concurrent redemptions of one coupon run one after the other. With the lock held, the count and per-customer checks are accurate, and the insert and the counter update commit together.
The UNIQUE constraint on order_id handles retries, and an INSERT ... ON CONFLICT as described in the INSERT documentation is the alternative when you prefer to let the database detect the duplicate. Checking for an existing redemption first, as the code below does, returns the same discount on a retry without consuming a second use.
The cost of the lock is that redemptions of a single coupon are serialized, which is fine for a store whose busiest coupon sees a few redemptions a second and wrong for one that sees thousands, where sharded counters or a reservation queue are the next step. Under the default read committed isolation described in the transaction isolation docs, the lock is also what makes the count read trustworthy, since a plain read would see only committed rows.
Encore is a backend framework with built-in infrastructure, so the coupon service is an api endpoint and a SQLDatabase declared in the same service. Per the AWS infrastructure docs, the deploy provisions Postgres on RDS in your own account with the migrations applied, and encore run starts Postgres locally for the same code.

Run in your terminal to get started locally.
The redemption and release endpoints, with the lock and the order-level idempotency described above:
// coupons/coupons.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
const db = new SQLDatabase("coupons", { migrations: "./migrations" });
interface RedeemRequest {
code: string;
orderId: string;
customerId: string;
orderTotalCents: number;
}
interface Redemption {
code: string;
orderId: string;
discountCents: number;
}
export const redeem = api(
{ expose: false, method: "POST", path: "/coupons/redeem" },
async (req: RedeemRequest): Promise<Redemption> => {
const code = req.code.trim().toUpperCase();
const tx = await db.begin();
try {
// A retried checkout gets the same discount and uses nothing extra.
const existing = await tx.queryRow<{ code: string; discount_cents: number; released_at: Date | null }>`
SELECT code, discount_cents, released_at FROM redemptions WHERE order_id = ${req.orderId}`;
if (existing) {
if (existing.released_at) throw APIError.failedPrecondition("redemption was released; use a new order ID");
await tx.commit();
return { code: existing.code, orderId: req.orderId, discountCents: existing.discount_cents };
}
// The row lock makes concurrent redemptions of one coupon run in turn.
const c = await tx.queryRow<{
percent_off: number | null;
amount_off_cents: number | null;
min_order_cents: number;
max_redemptions: number | null;
redeemed_count: number;
per_customer_limit: number;
starts_at: Date;
expires_at: Date | null;
now: Date;
}>`SELECT *, now() AS now FROM coupons WHERE code = ${code} FOR UPDATE`;
if (!c) throw APIError.notFound("unknown coupon");
if (c.now < c.starts_at || (c.expires_at && c.now > c.expires_at)) {
throw APIError.failedPrecondition("coupon is not valid right now");
}
if (req.orderTotalCents < c.min_order_cents) {
throw APIError.failedPrecondition("order total is below the coupon minimum");
}
if (c.max_redemptions !== null && c.redeemed_count >= c.max_redemptions) {
throw APIError.resourceExhausted("coupon has been fully redeemed");
}
const used = await tx.queryRow<{ n: number }>`
SELECT count(*)::int AS n FROM redemptions
WHERE code = ${code} AND customer_id = ${req.customerId} AND released_at IS NULL`;
if ((used?.n ?? 0) >= c.per_customer_limit) {
throw APIError.resourceExhausted("customer has already used this coupon");
}
const discount =
c.percent_off !== null
? Math.floor((req.orderTotalCents * c.percent_off) / 100)
: Math.min(c.amount_off_cents!, req.orderTotalCents);
await tx.exec`
INSERT INTO redemptions (code, order_id, customer_id, discount_cents)
VALUES (${code}, ${req.orderId}, ${req.customerId}, ${discount})`;
await tx.exec`UPDATE coupons SET redeemed_count = redeemed_count + 1 WHERE code = ${code}`;
await tx.commit();
return { code, orderId: req.orderId, discountCents: discount };
} catch (err) {
await tx.rollback();
throw err;
}
},
);
// Called when an order is cancelled or payment fails: the use goes back to the coupon.
export const release = api(
{ expose: false, method: "POST", path: "/coupons/release" },
async ({ orderId }: { orderId: string }): Promise<{ released: boolean }> => {
const tx = await db.begin();
try {
const r = await tx.queryRow<{ code: string }>`
UPDATE redemptions SET released_at = now()
WHERE order_id = ${orderId} AND released_at IS NULL RETURNING code`;
if (r) await tx.exec`UPDATE coupons SET redeemed_count = redeemed_count - 1 WHERE code = ${r.code}`;
await tx.commit();
return { released: r !== null };
} catch (err) {
await tx.rollback();
throw err;
}
},
);
-- coupons/migrations/1_init.up.sql
CREATE TABLE coupons (
code TEXT PRIMARY KEY,
percent_off INTEGER CHECK (percent_off BETWEEN 1 AND 100),
amount_off_cents INTEGER CHECK (amount_off_cents > 0),
min_order_cents INTEGER NOT NULL DEFAULT 0,
max_redemptions INTEGER,
redeemed_count INTEGER NOT NULL DEFAULT 0,
per_customer_limit INTEGER NOT NULL DEFAULT 1,
starts_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ,
CHECK ((percent_off IS NULL) <> (amount_off_cents IS NULL))
);
CREATE TABLE redemptions (
id BIGSERIAL PRIMARY KEY,
code TEXT NOT NULL REFERENCES coupons (code),
order_id TEXT NOT NULL UNIQUE,
customer_id TEXT NOT NULL,
discount_cents INTEGER NOT NULL,
redeemed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
released_at TIMESTAMPTZ
);
CREATE INDEX redemptions_customer_idx ON redemptions (code, customer_id) WHERE released_at IS NULL;
Both endpoints use expose: false, so only the checkout service in the same app can call them, as a typed call from ~encore/clients, per the API calls docs. The database and its migrations deploy with the code, and the migration file above is the whole schema.
To deploy, connect your AWS or GCP account as described in Connect your cloud account and push with git push encore.
A coding agent asked to add a new coupon rule, such as free shipping, changes the schema and the redemption check in one pull request and runs it against a local Postgres, with no database to create first.
Best fit: Online stores that need coupon limits to hold under concurrent checkouts and want the service and its Postgres database deployed to their own cloud account from one repository.
Run two redemptions of the last remaining use at the same time and confirm that one succeeds and one gets the fully-redeemed error. Replay the same order ID and confirm the count does not move, then release the order and confirm the use returns to the coupon.
Lock the coupon row inside the redemption transaction with SELECT ... FOR UPDATE, check the count and the per-customer limit, then insert the redemption and increment the counter before committing. Two requests for the last use cannot both pass, because the second waits for the first transaction to finish.
Store the order ID on the redemption with a unique constraint, and return the existing redemption when the same order arrives again. A checkout request that is retried after a timeout then gets the same discount and does not consume a second use.
Mark the redemption as released and decrement the coupon's counter in one transaction, so the use goes back to the customer and the limit. Keep the released row, since the history is needed for support and fraud checks.
With Encore you declare a SQLDatabase in the service with its migrations, and the deploy provisions Postgres in your own AWS or GCP account, with encore run starting Postgres locally. The redemption endpoint and the schema live in the same repository.
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.