LOYALTY WALLET / ENGINEERING CASE STUDY
Loyalty Wallet: three engineering decisions
A stamp is worth part of a free haircut, so the counter has to be right even when the Wi-Fi is bad, the wallet APIs are down, or someone taps twice. These are three decisions about keeping it right, the evidence I have, and the gap I haven't closed.
- Next.js 15 (App Router)
- TypeScript
- Supabase Postgres (EU)
- Vercel cron
- passkit-generator (Apple)
- Google Wallet API
- plain CSS
The stamp path
Tap or hover a box to see what it does.
DECISION 01
The rules live in Postgres, and nothing outside the server can call them
The problem
Stamps are worth money (a free haircut). Counter maths in app code can be bypassed or raced.
What I chose
All stamping and redemption go through SECURITY DEFINER SQL functions (add_stamp, redeem_reward, staff_login, get_card_state). They handle locking, cooldown, threshold, expiry and audit logging in one transaction. EXECUTE is revoked from PUBLIC, anon and authenticated and granted only to service_role, with search_path pinned.
Alternatives and why not
- Counting in the Next.js route: two requests can read the same count and both write +1.
- Row-level security alone: it controls who can touch a row, not the rule that stamps need a 240-minute gap.
Evidence
| Function | anon | authenticated | service_role |
|---|---|---|---|
| add_stamp | ✗ | ✗ | ✓ |
| redeem_reward | ✗ | ✗ | ✓ |
| staff_login | ✗ | ✗ | ✓ |
| get_card_state | ✗ | ✗ | ✓ |
| void_stamp | ✗ | ✗ | ✓ |
$ curl -X POST $SUPABASE_URL/rest/v1/rpc/staff_login -H "apikey: <anon key>" ...
HTTP/1.1 401 {"code":"42501","message":"permission denied for function staff_login"}add_stamp — simplified sketch
sanitised excerptcreate function add_stamp(p_pass_token text, p_idempotency_key uuid)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
begin
-- lock the card row, check cooldown + threshold + expiry,
-- insert stamp_events, audit_logs and pass_sync_jobs
-- all inside this one transaction
end;
$$;
revoke execute on function add_stamp(text, uuid) from public, anon, authenticated;
grant execute on function add_stamp(text, uuid) to service_role;Simplified sketch written for this page to show the shape of the logic. It is not copied from the repository.
Trade-off
Business logic in SQL is harder to unit-test and refactor than TypeScript.
DECISION 02
Wallet passes are projections, synced through an outbox
The problem
Apple's and Google's APIs can be slow or down, but a stamp must never be lost or block the staff member at the counter.
What I chose
Every stamp or redeem writes a pass_sync_jobs row in the same transaction. A cron route claims jobs atomically (pending → processing with claimed_at), reclaims stale jobs after 10 minutes and gives up after 5 attempts. Apple updates are an empty APNs push, after which the device refetches the pass. Google updates are a PUT on the LoyaltyObject. Wallet buttons hide unless that wallet is configured, and the web card always works.
Alternatives and why not
- Calling Apple and Google inside the stamp request: the staff member waits on someone else's API, and a failure loses the update.
- A separate queue service: more moving parts for a few shops. Postgres already gives me the transaction.
Evidence
Not yet verified on real devices. Real-device wallet testing is next (Google first, then iPhone).
claim sync jobs — simplified sketch
sanitised excerptupdate pass_sync_jobs
set status = 'processing', claimed_at = now(), attempts = attempts + 1
where id in (
select id from pass_sync_jobs
where (status = 'pending'
or (status = 'processing' and claimed_at < now() - interval '10 minutes'))
and attempts < 5
for update skip locked
limit 20
)
returning *;Simplified sketch written for this page to show the shape of the logic. It is not copied from the repository.
Trade-off
Up to about a minute of delay before the pass reflects a stamp.
DECISION 03
A double tap never means a double stamp
The problem
Flaky shop Wi-Fi plus an impatient thumb leads to retries.
What I chose
The client sends a fresh idempotency key per tap, and the function dedupes replays. stamp_events is append-only (void, never delete). Composite foreign keys make a cross-shop stamp impossible at the schema level. The QR carries only an opaque pass token, never a customer ID.
Alternatives and why not
- Disabling the button after a tap: helps the UI, but a network retry still sends the request twice.
- Deleting wrong stamps: it erases the history the owner needs for fraud checks.
Evidence
Verified locally only.
stamp_events — simplified sketch
sanitised excerptcreate table stamp_events (
id uuid primary key default gen_random_uuid(),
shop_id uuid not null,
card_id uuid not null,
idempotency_key uuid not null unique,
voided_at timestamptz,
foreign key (card_id, shop_id) references cards (id, shop_id)
);Simplified sketch written for this page to show the shape of the logic. It is not copied from the repository.
Trade-off
Voids need an explicit admin path instead of a simple delete.
KNOWN GAP / NOT YET CLOSED
A redemption visit can still earn a stamp
The rule says it shouldn't, but add_stamp and redeem_reward are independent calls, and the 240-minute cooldown has long expired by the time the customer returns. Today this relies on staff discipline. Options I'm weighing: a DB-level interlock or a staff-UX guardrail.
Status: Not decided yet.
How I verified it, including where an AI agent was wrong
Caught ✓
- Placeholder staff PINs still in a seed migration.
- A README that never ran the hardening migration.
Got wrong ✗
- An AI agent auditing my handoff doc against the code treated "can't verify from the repo" as "verified".
- In one case it redacted .env values and then claimed they were set.
Agents are fast reviewers and confident guessers. I give them explicit verification boundaries.
Tested locally
- 5 stamps → reward + reset
- Idempotent replay deduped
- Cooldown blocks
- Double redeem blocked
- Revoked pass blocked
- Cross-shop insert rejected by FK
- Audit and sync-job counts exact
- Anon RPC call rejected on the live database