Sub topic 5
Unique links and attributing signups
This chapter assumes you know how a referral program works (the previous chapters cover that) and can read basic Python and SQL. It covers how to give each subscriber a link and how to credit the right referrer when someone signs up.
What attribution has to do
Attribution means recording which referrer caused which signup. A reward program is only fair if this record is correct. Three steps make it work:
- Give each subscriber a unique, hard-to-guess code.
- Remember the code from the first click until the new reader signs up.
- Credit the referrer only once the signup is confirmed.
Generating referral codes
Sequential ids like ref=42 are easy to guess, and people could enumerate other subscribers' links. An HMAC (a keyed hash) of the subscriber id gives a short code that outsiders cannot predict without your secret.
import base64
import hashlib
import hmac
def referral_code(subscriber_id: int, secret: bytes) -> str:
digest = hmac.new(secret, str(subscriber_id).encode(), hashlib.sha256).digest()
return base64.urlsafe_b64encode(digest)[:10].decode()
code = referral_code(42, b"keep-this-secret-server-side")
link = f"https://example.com/subscribe?ref={code}"
print(link)The hash cannot be reversed to find the subscriber id. You therefore need a table that maps each code back to a subscriber. Create the row when the subscriber joins, and put a unique constraint on the code column. With 10 characters of base64, a collision is unlikely but possible, so handle the constraint error by regenerating the code with a salt.
Carrying the code through the signup
The visitor often does not subscribe on the first click. Your landing page has to hold on to the code until they do. Common approaches:
- Store
refin a first-party cookie when the landing page loads. - Copy it into a hidden field on the signup form.
- Save it with the pending subscriber record, so it survives the confirmation email.
Decide a rule for conflicts. With first-touch attribution, the first referrer to bring the visitor gets credit. With last-touch, the most recent link wins. First-touch is simpler to explain and harder to game by overwriting codes. Whichever you pick, write it in your program rules.
Recording the referral
Write the referral row at confirmation, not at form submission. Unconfirmed addresses include typos, bots, and addresses someone else entered. Reject self-referrals by comparing the referrer's address with the new one. Also allow only one referral row per referred subscriber.
CREATE TABLE referrals (
referrer_id INTEGER NOT NULL,
referred_id INTEGER NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL
);The UNIQUE constraint on referred_id enforces one referrer per new subscriber. This is what makes first-touch attribution safe if the same address signs up twice.
Counting for rewards
When a referrer approaches a milestone, count only referrals that still count. This query keeps subscribers who confirmed and have not unsubscribed, and lists referrers who reached five.
SELECT r.referrer_id,
COUNT(*) AS confirmed_referrals
FROM referrals AS r
JOIN subscribers AS s ON s.id = r.referred_id
WHERE s.confirmed_at IS NOT NULL
AND s.unsubscribed_at IS NULL
GROUP BY r.referrer_id
HAVING COUNT(*) >= 5
ORDER BY confirmed_referrals DESC;Common errors
| Error | Effect | Fix |
|---|---|---|
| Counting at form submission | Rewards for fake or mistyped addresses | Insert the row at confirmation |
| Dropping the code on redirects | Real referrals go unattributed | Keep `ref` through every redirect and in a cookie |
| Guessable codes | Others can use or inspect links | Use an HMAC with a server-side secret |
| No uniqueness on `referred_id` | One signup credited twice | Add a unique constraint |
| Cookie blocked by the browser | Lost attribution | Also pass the code in a hidden form field |
Exercise
A visitor clicks Ana's referral link, leaves, and returns a week later through Ben's link, then subscribes and confirms. Under first-touch attribution, who gets credit? Which table constraint prevents both from being credited?
Show answer
Ana gets credit, because her link was the first touch. The UNIQUE constraint on referrals.referred_id allows only one referral row per new subscriber, so Ben's row cannot also be inserted.