Nov 19, 20267 min read

Promo Code Backend: Discount Rules, Redemption Limits and Abuse

How to build the backend behind ecommerce promo codes: unguessable codes, discount rules, redemption limits that hold under concurrent checkouts, per-customer limits, releases on cancellation, and brute-force protection.

Illustration for Promo Code Backend: Discount Rules, Redemption Limits and Abuse

A promo code looks like a string field on the cart, but the backend behind it decides whether a limited campaign stays limited. Races for the last use, repeat redemptions and code-guessing scripts all show up on day one of a popular sale.

This guide builds a promo code service in Go with Postgres, covering rules, atomic redemption, releases and abuse controls.

Promo code backend at a glance

JobApproachWhat breaks if you skip it
Code generationRandom codes from an unambiguous alphabetGuessable or mistyped codes
Discount rulesPercent or amount, minimum order, date windowDiscounts applied to the wrong orders
Global limitConditional UPDATE ... RETURNINGOversold limited campaigns
Per-customer limitUnique index on promotion and customerRepeat use of first-order codes
One promo per orderUnique index on orderStacked discounts
ReleaseDelete redemption, decrement counterCancelled orders burn uses
AbuseUniform errors, rate limits, event streamCode guessing and leaked codes

Why do promo code limits break under load?

The obvious implementation reads the promotion, checks redeemed_count < max_redemptions in code, then increments. Under concurrency, two checkouts both read 99 of 100, both pass the check and both write, and the campaign ends at 101. The same race applies to "once per customer" checks done with a SELECT before the insert.

The fix is to let the database decide, since a single UPDATE with the limit in its WHERE clause takes a row lock, and under Postgres's default read committed isolation the second transaction re-checks the condition after the first commits. Run against Postgres with a limit of 1, two concurrent sessions got UPDATE 1 and UPDATE 0, and the counter ended at 1. Per-customer limits become a unique index, which no race can get around.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the promo service declares its Postgres database and a Pub/Sub topic for redemption events, and checkout calls it as a typed service API.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

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

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir -p promos/migrations

Store rules and redemptions

The schema keeps rules on the promotion and puts the limits the database must enforce into constraints:

-- promos/migrations/1_create_promos.up.sql CREATE TABLE promotions ( id BIGSERIAL PRIMARY KEY, code TEXT NOT NULL UNIQUE, -- stored upper-case percent_off INT CHECK (percent_off BETWEEN 1 AND 100), amount_off_cents BIGINT CHECK (amount_off_cents > 0), min_order_cents BIGINT NOT NULL DEFAULT 0, max_redemptions INT, -- NULL means unlimited redeemed_count INT NOT NULL DEFAULT 0, starts_at TIMESTAMPTZ NOT NULL, ends_at TIMESTAMPTZ NOT NULL, CHECK ((percent_off IS NULL) <> (amount_off_cents IS NULL)) ); CREATE TABLE redemptions ( id BIGSERIAL PRIMARY KEY, promotion_id BIGINT NOT NULL REFERENCES promotions(id), customer_id TEXT NOT NULL, order_id TEXT NOT NULL UNIQUE, -- one promo per order discount_cents BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -- Enforced by the database, not by a check-then-insert race in code. CREATE UNIQUE INDEX one_per_customer ON redemptions (promotion_id, customer_id);

The unique index makes every promotion here once per customer, so for campaigns where repeat use is allowed, use a partial index or a separate table for those promotions.

Redeem atomically and release on cancellation

// promos/promos.go package promos import ( "context" "errors" "strings" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("promos", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Redeemed struct { Code string `json:"code"` OrderID string `json:"order_id"` CustomerID string `json:"customer_id"` DiscountCents int64 `json:"discount_cents"` } // Analytics, fraud review and finance reporting subscribe to this. var PromoRedeemed = pubsub.NewTopic[*Redeemed]("promo-redeemed", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type RedeemParams struct { Code string `json:"code"` CustomerID string `json:"customer_id"` OrderID string `json:"order_id"` SubtotalCents int64 `json:"subtotal_cents"` } type RedeemResponse struct { DiscountCents int64 `json:"discount_cents"` } var errUnavailable = &errs.Error{Code: errs.FailedPrecondition, Message: "code is not valid for this order"} // Redeem is called by checkout when the order is placed. // //encore:api private method=POST path=/promos/redeem func Redeem(ctx context.Context, p *RedeemParams) (*RedeemResponse, error) { code := strings.ToUpper(strings.TrimSpace(p.Code)) tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() // Claim one use atomically. The WHERE clause holds every rule that can // change under concurrency, so two checkouts cannot both take the last use. var id int64 var percentOff, amountOff *int64 err = tx.QueryRow(ctx, ` UPDATE promotions SET redeemed_count = redeemed_count + 1 WHERE code = $1 AND now() BETWEEN starts_at AND ends_at AND min_order_cents <= $2 AND (max_redemptions IS NULL OR redeemed_count < max_redemptions) RETURNING id, percent_off, amount_off_cents`, code, p.SubtotalCents, ).Scan(&id, &percentOff, &amountOff) if errors.Is(err, sqldb.ErrNoRows) { return nil, errUnavailable // same answer for unknown, expired and used up } else if err != nil { return nil, err } discount := int64(0) if percentOff != nil { discount = p.SubtotalCents * *percentOff / 100 } else { discount = min(*amountOff, p.SubtotalCents) } _, err = tx.Exec(ctx, ` INSERT INTO redemptions (promotion_id, customer_id, order_id, discount_cents) VALUES ($1, $2, $3, $4)`, id, p.CustomerID, p.OrderID, discount) if sqldb.ErrCode(err) == sqlerr.UniqueViolation { return nil, errUnavailable // already used by this customer or order } else if err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } _, _ = PromoRedeemed.Publish(ctx, &Redeemed{Code: code, OrderID: p.OrderID, CustomerID: p.CustomerID, DiscountCents: discount}) return &RedeemResponse{DiscountCents: discount}, nil } // Release gives the use back when an order is cancelled or payment fails. // //encore:api private method=POST path=/promos/release/:orderID func Release(ctx context.Context, orderID string) error { _, err := db.Exec(ctx, ` WITH r AS (DELETE FROM redemptions WHERE order_id = $1 RETURNING promotion_id) UPDATE promotions SET redeemed_count = redeemed_count - 1 WHERE id IN (SELECT promotion_id FROM r)`, orderID) return err }

If the redemption insert hits the unique index, the deferred rollback also undoes the counter increment, so a rejected repeat use never consumes a slot. Release is idempotent: a second call for the same order deletes nothing and changes no counter. Both endpoints are private, so only checkout and other services in the app can call them.

encore run starts Postgres locally and applies the migration. Redemption events go to analytics and fraud review through subscriptions, and the outbox package makes the event part of the transaction where finance reporting cannot miss one. On deploy, Encore creates the database and topic in your own AWS or GCP account and provisions an IAM role for the service, or a service account on GCP.

When a marketing request adds a new rule, such as "first order only", a coding agent changes the WHERE clause and the migration in one diff and tests it against the local database, with no separate infrastructure change.

How do you generate codes and stop abuse?

Campaign codes like SPRING20 are meant to be shared, so their protection is the rules and limits above. Single-use codes for individual customers need randomness from crypto/rand and an alphabet without look-alike characters:

// No 0/O, 1/I/L: codes get read aloud and typed from screenshots. const alphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" // NewCode returns a random code such as "SPRING-7K4Q-MX2D". With 8 random // characters from 31 symbols there are about 8.5e11 combinations, so // guessing a valid code from a batch of 100,000 takes millions of attempts. func NewCode(prefix string) (string, error) { b := make([]byte, 8) for i := range b { n, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet)))) if err != nil { return "", err } b[i] = alphabet[n.Int64()] } return fmt.Sprintf("%s-%s-%s", prefix, b[:4], b[4:]), nil }

On the redemption side, return the same error for unknown, expired and used-up codes so a script learns nothing from the response, and rate-limit validation per customer and per IP, following OWASP's guidance on blocking brute-force attacks. Leaked public codes show up as a spike in redemptions from new accounts, which the redemption event stream makes easy to alert on. Tying high-value codes to a customer ID at issue time closes the leak entirely.

Promo codes in your own Postgres

The same design works without Encore: the schema, the conditional UPDATE and the unique indexes are plain Postgres. You then provision the database, run migrations in CI, wire a queue or event bus for redemption events, and manage credentials for each environment yourself. Keep the redemption logic in one service either way, so no other code path can increment the counter without the checks.

How to choose

Use Encore if you want the promo service, its database and its event stream declared together and running locally and in your own cloud account from the first commit. Build directly on Postgres and your existing queue if those are already in place and the team is comfortable owning migrations and infrastructure per environment.

Frequently asked questions

How do you stop a promo code from being used more times than its limit?

Claim a use with one conditional UPDATE that increments the counter only while it is below the limit, and check the affected row. Under concurrent checkouts Postgres serializes the updates on that row, so only as many succeed as there are uses left. Reading the count and then writing it in two steps lets two checkouts take the last use.

How do you enforce one use per customer?

Put a unique index on (promotion_id, customer_id) in the redemptions table and insert the redemption in the same transaction as the counter update. The database rejects the second redemption even when two requests arrive at the same moment, and the transaction rollback returns the counter.

How long should promo codes be?

Public campaign codes can be short and memorable, since they are meant to be shared. Single-use codes sent to individual customers should be random, with about 8 characters from an unambiguous alphabet, which gives hundreds of billions of combinations and makes guessing a valid one impractical when combined with rate limiting.

Should a promo code be redeemed at cart or at order time?

Validate it when it is applied to the cart so the customer sees the discount, but claim the use only when the order is placed. Release the use when the order is cancelled or the payment fails, so abandoned carts do not burn limited codes.

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