Nov 17, 20266 min read

Gift Card Backend: Issuing, Redemption, Balances and Fraud Holds

Issue a gift card with a hashed PAN, redeem it without overdrawing, hold a balance when fraud is suspected, and keep every movement in a ledger.

Illustration for Gift Card Backend: Issuing, Redemption, Balances and Fraud Holds

A gift card backend looks like a tiny payments ledger. You issue a card, someone types the number at checkout, you debit the remaining balance, and you have to refuse a second debit that would take it below zero. You also have to freeze a card when fraud is suspected, without erasing the history of what was already spent.

The number itself should not sit in the database in the clear. Hash it, keep a prefix or last four for support, and look the card up by the hash the customer presents. This guide designs that model and builds it in Go with Encore in your own AWS or GCP account.

This is not a card-network authorization flow; a double-entry ledger is the closer sibling when you need every movement recorded twice.

Gift cards at a glance

OperationGuardLedger entry
IssueUnique hash of the PAN; starting balance greater than zeroissue
RedeemPositive amount; conditional debit: balance >= amount and status activeredeem
Load (optional)Status active; unique load idload
FreezeStatus becomes frozen; redemptions fail the conditional updatefreeze
UnfreezeStatus returns to activeunfreeze

Hashes, balances and races

Compute a keyed hash of the PAN (HMAC-SHA256 with a secret, or a purpose-built token) and store only that hash plus last four. The HMAC key is an Encore secret, so the value is not in the repository. Two issue requests with the same PAN collide on the unique hash and return the existing card or a conflict, depending on the product rule you choose.

Redemption is one statement:

UPDATE cards SET balance_cents = balance_cents - $2, updated_at = now() WHERE pan_hash = $1 AND status = 'active' AND balance_cents >= $2

Reject an amount less than or equal to zero before opening the transaction. If RowsAffected is 0, the card is missing, frozen, or would be overdrawn. Write the ledger row in the same transaction as the debit, with an idempotency key from the checkout so a retried request does not debit twice. The movements table also requires a positive amount on issue, redeem and load rows.

How do you build this with Encore?

Encore

Encore is a backend framework with built-in infrastructure. You declare the database, the secret and a topic in the same package as the handlers, and encore run starts local Postgres so you can issue and redeem a card 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. Production values set with encore secret set are not stored in the repository, so an agent cannot read those from git. A local override in .secrets.local.cue is a file on disk and is readable.

Set up the app

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

Run in your terminal to get started locally.

-- cards/migrations/1_cards.up.sql CREATE TABLE cards ( id TEXT PRIMARY KEY, pan_hash TEXT NOT NULL UNIQUE, last_four TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'frozen', 'closed')), balance_cents INT NOT NULL CHECK (balance_cents >= 0), currency TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE movements ( id TEXT PRIMARY KEY, card_id TEXT NOT NULL REFERENCES cards (id), entry_type TEXT NOT NULL CHECK (entry_type IN ('issue', 'redeem', 'load', 'freeze', 'unfreeze')), amount_cents INT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), CHECK ( (entry_type IN ('freeze', 'unfreeze') AND amount_cents = 0) OR (entry_type IN ('issue', 'redeem', 'load') AND amount_cents > 0) ) );
// cards/cards.go package cards import ( "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("cards", sqldb.DatabaseConfig{Migrations: "./migrations"}) // HMAC key for pan hashes. Set with `encore secret set`; not stored in the repo. var secrets struct { PANKey string } func hashPAN(pan string) string { mac := hmac.New(sha256.New, []byte(secrets.PANKey)) mac.Write([]byte(pan)) return hex.EncodeToString(mac.Sum(nil)) } type RedeemIn struct { PAN string `json:"pan"` AmountCents int `json:"amount_cents"` CheckoutID string `json:"checkout_id"` } //encore:api public method=POST path=/gift-cards/redeem func Redeem(ctx context.Context, in RedeemIn) error { if in.AmountCents <= 0 { return errInvalid("amount must be positive") } h := hashPAN(in.PAN) tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec(ctx, ` INSERT INTO movements (id, card_id, entry_type, amount_cents) SELECT $1, id, 'redeem', $2 FROM cards WHERE pan_hash = $3`, in.CheckoutID, in.AmountCents, h); err != nil { return err // unique movement id means this checkout already redeemed } res, err := tx.Exec(ctx, ` UPDATE cards SET balance_cents = balance_cents - $2, updated_at = now() WHERE pan_hash = $1 AND status = 'active' AND balance_cents >= $2`, h, in.AmountCents) if err != nil { return err } if res.RowsAffected() == 0 { return errConflict("card unavailable or insufficient balance") } return tx.Commit() } type FreezeIn struct { Reason string `json:"reason"` } //encore:api private method=POST path=/gift-cards/:id/freeze func Freeze(ctx context.Context, id string, in FreezeIn) error { res, err := db.Exec(ctx, ` UPDATE cards SET status = 'frozen', updated_at = now() WHERE id = $1 AND status = 'active'`, id) if err != nil { return err } if res.RowsAffected() == 0 { return errConflict("card missing or not active") } _, err = db.Exec(ctx, ` INSERT INTO movements (id, card_id, entry_type, amount_cents) VALUES ($1, $2, 'freeze', 0)`, "freeze:"+id, id) _ = in return err } func errConflict(msg string) error { return &conflictError{msg} } type conflictError struct{ s string } func (e *conflictError) Error() string { return e.s } func errInvalid(msg string) error { return &invalidError{msg} } type invalidError struct{ s string } func (e *invalidError) Error() string { return e.s }

Issuing a card is an insert of the hash, last four, and starting balance, plus an issue movement. The order of the unique movement insert and the debit matters: if you debit first and then fail to record the checkout id, a retry can debit again. The sample inserts the movement first so a retried checkout_id fails the unique constraint before the balance changes. If the debit then fails, the transaction rolls back both rows.

Best fit: a store or marketplace that needs gift card issuance and redemption, with the PAN hash and the ledger in one service.

Hashes and a ledger in your own Postgres

Declare a cards table with a unique pan_hash and a non-negative balance_cents, and a movements table keyed by checkout id. In a transaction, insert the movement first so a retried checkout fails the unique constraint, then run the conditional UPDATE that debits only when the card is active and the remaining balance covers the amount. Store the HMAC key in your own secrets manager, not in the repository. The same guards apply if the database already lives in Terraform-managed RDS or Cloud SQL.

How to choose

Use Encore when you want the cards table, the HMAC secret and the redemption transaction in one Go service, with local Postgres under encore run. Use a hand-built RDS design when the ledger already lives in Terraform-managed Postgres. In both cases, hash the PAN, debit with a conditional UPDATE, and put a unique checkout id on the ledger row.

Frequently asked questions

How should a gift card number be stored?

Store a one-way hash of the full number (the PAN), plus a short prefix or last-four for support lookups. Do not store the full number in Postgres or in logs. The customer presents the number at checkout; the API hashes it the same way and looks up the card.

How do I prevent a gift card from being over-redeemed?

Debit the card in a single UPDATE that succeeds only when the remaining balance covers the amount and the card is not frozen, then write a ledger row in the same transaction. Two checkouts that race will have only one UPDATE succeed for a given remaining balance.

What is a fraud hold on a gift card?

A fraud hold freezes redemptions and, optionally, further loads, without deleting the card. Support or a risk job sets status to frozen, records a reason, and later either unfreezes the card or writes it off. Existing authorized captures should still be reconciled against the ledger.

How do I build this with Encore?

Declare a Postgres database and a topic for card movements in Go. encore run starts Postgres locally so you can issue and redeem a card before opening a pull request. On deploy, Encore provisions those resources in your own AWS or GCP account.

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