Product · Backend · PostgreSQL · Architecture
Digitising the Loyalty Stamp Card
Replacing the café punch card with software sounds like a weekend project. It isn't. The full engineering story: the three numbers that decide whether it survives a busy counter, the transaction ordering and indexes that answer them, customer identity without passwords, and the decision I reversed in writing.
Every café has one: a paper card, ten little boxes, a rubber stamp behind the counter. Buy ten coffees, get one free. It is one of the oldest loyalty programmes there is, and it works well enough that almost nobody questions it.
It also fails in ways everyone has seen. Cards get lost in washing machines. Customers carry five half-filled cards from five cafés. A friendly barista stamps twice. A stamp can be copied with a pen. And the café owner, the person paying for the free coffees, has no idea how many rewards are outstanding, who their regulars are, or whether the programme is working at all.
Digital Stamp Card is my attempt to replace that card with software. A customer earns a stamp for each qualifying visit and unlocks a reward at a fixed threshold. Staff stamp from a phone at the counter. The owner sets the rules and sees the whole programme on a dashboard. I built it alone, from the product decisions and the architecture through to deployment, starting at the end of August 2026.
It sounds like a weekend project: a card, a counter, a reward. This post is about why it isn't, and about the decisions that turned out to matter, including one I had to reverse.
What the system is really optimising for
Before writing any code I did the napkin maths, because the first instinct on a product like this is to worry about scale, and scale is the wrong thing to worry about here.
| Stage | Outlets | Stamps a day | Writes a second at the lunch peak |
|---|---|---|---|
| One café | 1 | about 100 | about 0.05 |
| Fifty cafés | 60 | about 5,000 | about 1 |
| Five hundred cafés | 600 | about 50,000 | about 10 |
Ten writes a second is a rounding error for Postgres. Scale was never going to be the problem, so I made a rule that it would not drive a single decision. Three other things can kill this product, and every decision after that was scored against them, in this order:
- Latency at the counter. If a stamp takes eight seconds while a queue builds behind the customer, the café stops using it. The budget is a p95 under 800 ms from scan to confirmation.
- Abuse. Staff stamping their friends, receipts reused, one bill stamped five times. The audit trail is not a feature of the product. It is the product.
- Cost. A small café will pay a few hundred rupees a month at most. Infrastructure has to round to zero per business.
Writing those three down first was the most useful hour of the project. Every argument afterwards, about a table, an index or a feature, was settled by asking which of the three it helped and what it cost the others.
The shape of it
There are three surfaces: the staff app on a counter phone, the customer's card (and a Google Wallet pass), and the owner's dashboard. They are all one Next.js web app on Vercel. Behind them is a single NestJS API on Render, the only thing that writes to the database, and Postgres on Neon. Wallet updates are sent by a worker that drains an outbox table.
It is TypeScript end to end in a pnpm and Turborepo monorepo: the web app, the API and a shared package of contracts that both sides import. Validation schemas, rejection reasons and programme rules are defined once, in that package, so the API and the screen that explains a rejection can never disagree about what a rejection is.
Nothing in the stack is exotic, deliberately. Every piece is boring and replaceable, so the interesting decisions live in the design rather than in the build setup.
The free tier sleeps, and loyalty traffic is the worst case
Requirement three meant free tiers to start. That combination has a problem that lands directly on requirement one.
Free web services on Render sleep after about fifteen minutes without traffic, and Neon's free compute also scales to zero when idle. A café stamps all through lunch, goes quiet, and then someone scans at four in the afternoon. That request pays for a cold container and a cold database, with a customer standing at the counter.
A loyalty app is exactly the bursty, mostly idle traffic shape that free-tier sleep punishes hardest. It isn't a scale problem; it's a "nobody has scanned for twenty minutes" problem, and it happens every day. So I wrote down an upgrade path before it was needed, with one rule that makes "build it cheap now, upgrade later" safe rather than naive: everything that changes on the way to production must be configuration, and everything that is architecture must be right the first time.
| Concern | Testing now | Production later | Cost of the switch |
|---|---|---|---|
| API host | free, sleeps | always-on instance | a plan change |
| Database | Neon free | Neon paid | a connection string |
| Outbox worker | inside the API | its own service | one environment flag |
| Error tracking | console logs | an error tracker | add a key |
| Tenant isolation | scoped data layer | row-level security if asked | one migration |
Not one row of that is a rewrite. That table is the test of whether the plan holds up.
There is also a list of free-tier behaviour that will confuse you at two in the morning, written down so it doesn't. The best one: a sleeping API also stops the in-process outbox worker, so wallet updates sit pending until the next request wakes the service. That is not a bug, and knowing it in advance saves an evening.
One origin, or sign-in breaks on every iPhone
This is the decision most likely to cost a wasted week if it is found late.
If the web app is on one domain and the API on another, every API call is cross-site, and the session cookie has to be a third-party cookie. Safari blocks third-party cookies outright, and Safari is the only real browser engine on iOS. At a café counter, half the staff phones are iPhones. That isn't an edge case; it is the default case.
There were three ways out:
- Proxy everything through Next.js. One origin and no cookie problem, but an extra hop and a function invocation on every API call, which eats the latency budget.
- Bearer tokens in JavaScript. No cookies at all, but a token any injected script can read, and a home-screen app that gets killed in the background has to sign in again on every resume. Bad at a counter.
- The same registrable domain. The web app and the API on two subdomains of one domain, so the cookie is first-party for both.
I chose the third. It costs a domain name and removes the whole class of problem.
Every row belongs to a business
The product is multi-tenant from the first migration: one database, one schema, and a
business_id on every row that belongs to a café. No schema per tenant and no database per
tenant; at this scale that is pure operational cost.
The risk with a shared schema is one forgotten WHERE business_id = ? that leaks one
café's customers to another. Two defences hold it:
- One tenant-scoped data layer. Every query for tenant data goes through repositories that take a tenant context as their first argument and add the predicate themselves. Forgetting the scope is a type error, not a code review comment.
- Every index leads with
business_id. Scoping is cheap, so there is never a performance excuse to skip it.
Postgres row-level security is the belt-and-braces answer, and I deliberately deferred it: it complicates migrations and connection pooling, and the surface at this stage is small enough to hold in your head. Deferring it isn't forgetting it. It has a written trigger: the first customer with a contractual data-isolation requirement.
The same reasoning answers "can we give a café its own installation?" No, and nobody needs one. Onboarding a café is inserting a business row, not deploying a copy of the app. Per-tenant deploys would mean per-tenant migrations, secrets and wallet certificates, an enormous amount of work that buys nothing.
The stamp count is derived, never stored
The obvious data model has a stamps column on the card that goes up by one and resets to
zero after a reward. That puts a mutable number at the centre of a system whose whole value
is that it can be trusted.
Instead, stamps are append-only events, redemptions are append-only records, and the count is computed:
current_stamps(card) =
count(accepted stamp events for the card)
- sum(stamps consumed by its redemptions)
reward_available = current_stamps >= stamps_required
The detail that makes this stable is that each redemption records the threshold as it was at the moment of redemption, along with a snapshot of the reward's description. If an owner later changes the programme from ten stamps to eight, history doesn't quietly rewrite itself and nobody's past reward becomes retroactively invalid. Nothing resets, nothing mutates, and "how did this card get to seven?" always has an answer.
It costs two indexed aggregates per card view, which at this scale is well under a millisecond. If one card ever has tens of thousands of events, a maintained balance can sit in front of it, but only as a cache, never as the source of truth. That threshold is written down too.
The stamp transaction
This is the critical path; everything else is scaffolding around it. Staff find the card, type the invoice number and confirm.
In SQL, the shape is this:
BEGIN;
-- Two staff stamping the same card at once must not both see the same state.
SELECT ... FROM card WHERE id = $1 FOR UPDATE;
-- Settle the invoice BEFORE checking any rule.
SELECT ... FROM stamp_event
WHERE business_id = $2 AND invoice_number = $3 AND status = 'accepted';
-- same card -> a retry: return the existing stamp
-- different card -> INVOICE_ALREADY_USED
-- Then the rules, cheapest first: card status, programme active,
-- cooldown at this outlet, daily cap (in the outlet's time zone), minimum spend.
INSERT INTO stamp_event (...) VALUES (..., 'accepted')
ON CONFLICT (business_id, invoice_number) WHERE status = 'accepted'
DO NOTHING;
INSERT INTO outbox (kind, payload) VALUES ('wallet.push', ...);
COMMIT;The ordering is the part that isn't obvious, and it matters. Café wifi is bad. A staff member stamps, the connection drops after the server has committed, and they tap again. If the rules ran first, that retry would be measured against the state its own first attempt created, and the app would answer "cooldown active, eligible in four hours" for a stamp that actually succeeded. Settling the invoice first means a retry is recognised as a retry and simply returns the stamp that already exists. Staff never see a frightening error for something that worked. Settle identity before eligibility.
The invoice is checked twice: once up front, and once more by the ON CONFLICT clause,
which catches a concurrent request that won the insert in between. Both resolve the same
way, by asking whose card holds the invoice. The nice property is that the anti-abuse rule
and the idempotency key are the same index. One bill can't be stamped twice, and a
retried request can't double-stamp, for the price of one constraint.
One small thing makes a large difference at the counter: reading a card runs the same rule checks as a preflight. The staff screen can say "cooldown, eligible in 3 h 20 m" before anyone types an invoice number, instead of after.
Rejections are data, not errors
The first time an owner says "your app is broken, it won't stamp", the answer is in the rejected attempts. The first time you wonder whether the cooldown is set too aggressively, the answer is in the rejected attempts. So every rejection is stored, in the same table as the accepted stamps, with a typed reason the staff screen can explain:
- invoice already used, with when it was first used;
- cooldown active, with when the card is next eligible;
- daily cap reached;
- below the minimum spend, with the amount required;
- card or programme not active.
Storing rejections in the same table would break the invoice constraint, since a rejected attempt would "use" an invoice number. The fix is a partial unique index:
CREATE UNIQUE INDEX stamp_event_invoice_uniq
ON stamp_event (business_id, invoice_number)
WHERE status = 'accepted';Rejected rows don't consume the invoice, so a legitimate retry after a rejection still works, and the audit trail is complete. The cost is that every count has to filter on accepted events, so that filter lives once, in the repository layer, rather than at every call site.
Two reasons are deliberately quiet. "Wrong business" is never sent: card lookups are already scoped to the business, so a card from another café is simply not found, and the response must not confirm that somebody else's card exists. And "card not found" is returned but not recorded, because a rejection row needs a card to point at. Writing those two exceptions down is what keeps them from looking like bugs a year later.
Money and time
Two small rules that are expensive to retrofit:
- Money is
NUMERIC, never a float. Pick decimal or minor units and never mix them. - Every timestamp is stored in UTC, and the outlet's own time zone drives "per day" rules. "Two stamps a day" at a café open until one in the morning is a business-day question, not a UTC-midnight question. Getting this wrong later means recomputing every report.
An outbox instead of a queue
Updating a customer's wallet pass must never sit inside the stamp request; it is slow and it can fail. The usual answer is a job queue on Redis, but that is a second datastore, a second failure mode and a second bill, to move a few thousand jobs a day.
Instead there is a Postgres outbox table. The outbox row is written in the same
transaction as the stamp, so it can't be lost if the process dies between commit and
enqueue. A worker claims pending rows with FOR UPDATE SKIP LOCKED, retries with
exponential backoff, and moves rows that exhaust their attempts to a failed state the
dashboard can show. SKIP LOCKED means a second worker can be added later without changing
anything, and the same pattern carries any later side effect: one mechanism, not three.
The wallet side was its own small education. Google Wallet has a purpose-built loyalty object with a native points field, signed with a service account, and it works: the pass saves to a phone, and the count changes in the customer's pocket after a stamp without anyone touching it. (The issuer account is still in Google's demo mode until it is reviewed, so for now passes only save for test accounts.) Apple Wallet has no loyalty type, so a pass has to be built and drawn by hand, and it must be signed with a certificate from a paid developer account. I deliberately didn't build it yet. Code that produces a pass every device refuses to open is code that cannot run, and writing it before the account exists proves nothing.
Offline is explicitly not supported
The tempting fix for bad café wifi is to queue stamps on the phone and sync later. I decided not to, and wrote down why so the idea wouldn't keep coming back.
Every meaningful check is on the server and depends on state the phone can't see: the invoice may already be used, the cooldown may not have passed, the daily cap may be reached. Accepting a stamp offline means telling a customer they got a stamp and silently taking it back later, which is worse than the failure it was trying to avoid.
So stamping needs a connection and says so, clearly and fast. The app shell is cached, so it opens instantly from the home screen even on poor signal. A request times out after five seconds with an unambiguous "no connection, can't stamp" message, never an endless spinner. And a retry reuses the same invoice number, so it lands on the idempotent path above.
For a real outage, the design has a fallback: staff note invoice numbers on paper and the owner enters them afterwards, each flagged as a manual entry in the audit trail. I want to be precise about its status, because the project's own records are: the schema reserves the "manual" source, but the catch-up endpoint is specified and not built. Today the fallback is paper and patience. Saying that plainly is better than a design document that promises something the code doesn't do.
Sessions you can actually revoke
Staff shouldn't have to sign in every shift, so their sessions last thirty days, sliding. That is exactly why revoking a device had to be in the first version: a staff phone left in an auto-rickshaw is a device that can issue stamps for a month.
Sessions are database rows, not just self-contained tokens. The access token is short, fifteen minutes, and carries nothing but the user and the session. On each request the API checks the token's signature and that the session row is still live. That check is memoised for thirty seconds, because a database round trip on every request would spend the entire latency budget. So "sign out this device" takes effect within thirty seconds rather than instantly, and immediately on the instance that performed it.
Thirty seconds of exposure on a lost phone is a fair trade for not querying the database on every request; the fifteen minutes a pure token would give is not. And because business, outlet and role are read from the session row rather than baked into the token, moving a staff member to another outlet takes effect on the same thirty-second horizon instead of at their next sign-in.
A customer is a person, once
The first version had no customer accounts at all: the card itself was the identity. That works right up to the first person holding cards from two cafés, with two bookmarks and no way to see both.
The second version adds one layer: a person exists once, globally, and has a customer record per business, each with its card. Some decisions in that layer were subtle enough to write down carefully.
A business sees its own customers, and nothing else. A café can read the person behind its own customer record. It cannot see that the same person drinks at the café down the road: no endpoint joins from one business to another's memberships.
Customer sessions are a separate mechanism, not a flag. Staff sessions carry a business and every tenant query requires one. A customer session must do the opposite, read across businesses, and carry no business at all. Threading an optional business through the staff guard would add a branch to every scoped query where the scope is missing, which is the exact property the data layer exists to prevent. So customers get their own table, cookie, guard and context, and the two kinds of token are typed so each guard rejects the other's.
There is no password. Signing in and signing up are the same act: enter an email, receive a six-digit code, and the account exists once the code is verified. Six digits is only a million possibilities, and the code is not what makes it safe; three limits around it are, and removing any one breaks it:
- it expires in ten minutes;
- five wrong attempts kill it;
- an address can only be sent five codes an hour, so an attacker can't mint new codes faster than the attempt cap burns them.
The code is stored as a hash of the destination and the code together, because a bare hash of a six-digit number is a lookup table with a million rows. Only one code is live per address: asking for a new one invalidates the last. And codes are sent directly rather than through the outbox, because a sign-in code is worthless if it arrives late, and queuing it would park the plain code in a table.
The same answer for everyone. Starting a sign-in returns the same response whether or not the address has an account, and every dead-code case shares one message. Otherwise the endpoint tells anyone who asks whether a given person uses the product.
That principle caught a real bug in review. The phone number was unique across all users, which made the profile update quietly answer "is this number on the platform?", and let someone reserve a number they didn't own, locking out its real owner the day phone verification arrived. The fix was the same shape as the invoice constraint: a partial unique index that only applies to verified numbers. An identifier is not an identity until it is verified.
The decision I reversed
The first version printed a QR code on a physical card, encoding one URL with a long random token. Anyone holding the card could view it; a signed-in staff phone could stamp it. It made the counter flow frictionless: hand over a card, stamp it, let the customer claim it later or never. It was proven on real infrastructure: a printed card was stamped from an Android phone at a counter, and the customer saw the stamp arrive.
Along the way I also had to settle why the customer couldn't simply tap their phone on the staff phone. On the web, that half of NFC doesn't exist: a browser can read and write NFC tags, but it cannot make a phone pretend to be a card, and it cannot put a phone into reader mode for another phone. Wallet tap needs certified payment terminals. So the direction had to be: the customer presents, the staff device reads.
Then customer accounts arrived, with a name, an email and a phone number. At that point the card URL stopped being a harmless view of a coffee count and became a bearer view of a person's identity. A photographed QR code is no threat to a stamp count; it is a different matter when the same link shows someone's email address.
Keeping the token would have meant two authorisation models forever, one where a link is proof and one where a session is, and remembering at every new endpoint which one applied. So it went: QR, NFC, print batches and the claim flow all left with the token they encoded. Now a card exists only because a customer does, every route to it runs through a session, and the card's id grants nothing.
The cost is real, and I wrote it down plainly: anonymous plastic cards are gone, and adding a customer is slower at the counter than handing over a card. If physical cards come back, they must come back as a credential that can be revoked, such as a rotating code, never as the old static token.
A design system without a UI dependency
The counter phone loads the app over café wifi, so the web app has no component library. The buttons, cards, tables, badges and the chart are hand-written, with about twenty inline icons. A component library and its helpers buy very little when the hard parts it solves, dialogs and comboboxes, are things this product doesn't have.
One set of colour tokens is retuned in place for each surface: the customer's card is warm and branded, because it sits next to a printed card; the consoles are neutral, because they are tools and colour on them should carry meaning. And two corner radii, not four: 14 px on a panel, 8 px on anything you press. For a while the buttons were pills, and next to squarer cards the screens looked assembled from two different kits. A shared corner is most of what makes a set of components look like one system.
Verify by looking at the artefact
The lesson I value most from this project came from the wallet pass. For three rounds, the stamp grid on the pass was invisible, while every instrument reported success: a valid image, the correct dimensions, the field present in the signed payload, and Google replying that the pass was updated. It was white ink on a white card. One look at the actual pixels found it.
So the project has a rule: status codes are not evidence. Render the image and open it, run the query and read the values, fetch the URL and inspect the bytes. When the output is wrong and every check passes, the checks are measuring the wrong thing. The work log keeps two columns for that reason, built and proven, and only moves something to the second after someone has seen it work.
Revisit triggers
Every decision that trades something away has a written condition for reopening it, so "later" has a definition:
| Decision | Revisit when |
|---|---|
| Derived stamp count | one card passes about 10,000 events, or the card page p95 passes 100 ms |
| Postgres outbox | jobs pass about 10 a second, or real scheduling is needed |
| Scoped data layer | the first customer requires contractual data isolation |
| Free database tier | storage passes 70% of the cap, or about 50 active cafés |
| No offline writes | a café with genuinely bad connectivity refuses to adopt |
| One region | meaningful traffic outside India |
Where it stands
I'll be exact, because the difference matters. Version 1 is deployed, and its whole loop was proven on real infrastructure: a card left the drawer, was stamped at a counter from an Android phone, and the customer saw it. Deployed is not the same as live, though: there are no paying customers yet. Version 2, which rebuilds identity around the reversed decision, is green on 123 automated tests, a typecheck and a build against a database branch. It isn't deployed yet, and when the product is finalised it ships on a fresh database.
What it taught me
The interesting work in this product was never the card on the screen. It was deciding what to optimise for before writing code, and letting those three numbers settle the arguments: the order of checks inside one transaction, an index that does two jobs, a feature deliberately left out, an identity model that answers everyone the same way, and a decision reversed in writing when the product outgrew it.
Small products are a good place to practise that discipline, because every trade-off is visible at once. And the habit that came out of it, separating "built" from "proven" and checking the artefact rather than the status code, is the one I now bring to everything else I build.
