Sub topic 5
Unique links and attributing signups
A referral program only works if you can say which subscriber brought in which signup. Without that, you can't pay rewards fairly, you can't see which readers drive growth, and the k-factor from the previous chapter stays a guess. This chapter covers how to build referral links, carry the referral through a signup, and record it so it holds up under real-world mess.
Prerequisites and scope
This chapter assumes you can read short Python and SQL, and that you know how a double opt-in signup works: the reader submits an email address, receives a confirmation email, and is subscribed only after clicking the confirmation link. It also assumes you control, or can script against, your own subscriber database. Hosted newsletter platforms provide referral features that do this work for you. Understanding the mechanics still helps you judge what those tools do and where they fall short.
What attribution has to answer
Attribution means linking a new subscriber to the source that caused the signup. For a referral program, the source is another subscriber. Your system needs to answer four questions:
- Who shared the link? This is the referrer.
- Who signed up through it? This is the referred subscriber.
- When did each step happen: click, signup, confirmation?
- Does this signup count toward a reward?
Most of the engineering is in keeping the answer to question 1 intact between the first click and the confirmed signup. That can be days later, on a different device, after a confirmation email.
Generating unique referral codes
Each subscriber gets one code that identifies them in a link such as https://example.com/subscribe?ref=Qx3.... A good code has three properties:
- It is unique per subscriber.
- It is hard to guess, so nobody can enumerate codes and credit themselves or others.
- It contains no personal data. Links get pasted into public posts, and URLs end up in logs and in the
Refererheader sent to other sites.
Do not use the raw email address or a sequential id as the code. A sequential id lets anyone try ref=1, ref=2, and so on. An email address in a URL leaks personal data. A keyed hash (HMAC) of the subscriber id avoids both problems:
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)Ten characters of URL-safe base64 carry 60 bits, which is enough to make guessing impractical. An HMAC cannot be reversed, so you cannot recover the subscriber id from the code. You must store the mapping from code to subscriber in a table with a UNIQUE constraint. The constraint also catches the rare truncation collision. If an insert fails because the code exists, generate a new one, for example by hashing the id with a counter.
The secret must stay on the server. If you rotate it, previously issued codes still work as long as you keep the stored mapping. Only newly generated codes change.
Carrying the code through the signup
A reader clicks the link, but the referral is only worth something once they confirm. Between those two moments you have to remember the code. There are two common ways.
| Method | How it works | Weakness |
|---|---|---|
| Browser cookie or local storage | The landing page saves `ref` in the browser | Lost if the reader switches device or browser, or clears cookies |
| Pending-signup row | The signup form submits `ref` with the email, and the server stores it with the unconfirmed subscriber | Only captures the code if the reader submits the form on the same page load |
The pending-signup row is more reliable because it lives on your server. Combine both: the landing page reads ref from the URL, stores it in a cookie, and writes it into a hidden form field. Then the server saves it next to the email address the moment the form is submitted.
The confirmation email is where many programs break. The reader opens it, often in a different app or browser, and a cookie-only system sees no referral. If the code is already stored on the pending row, the confirmation click needs no memory of the original click.
Recording the referral
The data model needs two tables. The referrals table uses the referred subscriber's id as its primary key. That enforces one referrer per subscriber, so the first captured referrer wins. This is first-touch attribution.
The following program is self-contained and runs with the standard library. It creates the tables, records a referral, and shows that bad or repeated referrals are ignored.
import base64
import hashlib
import hmac
import sqlite3
from datetime import datetime, timezone
SECRET = b"keep-this-secret-server-side"
SCHEMA = """
CREATE TABLE subscribers (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
ref_code TEXT UNIQUE,
confirmed_at TEXT,
unsubscribed_at TEXT
);
CREATE TABLE referrals (
referred_id INTEGER PRIMARY KEY REFERENCES subscribers(id),
referrer_id INTEGER NOT NULL REFERENCES subscribers(id),
ref_code TEXT NOT NULL,
captured_at TEXT NOT NULL
);
"""
def referral_code(subscriber_id, secret):
digest = hmac.new(secret, str(subscriber_id).encode(), hashlib.sha256).digest()
return base64.urlsafe_b64encode(digest)[:10].decode()
def now():
return datetime.now(timezone.utc).isoformat()
def add_subscriber(db, email):
cur = db.execute("INSERT INTO subscribers (email) VALUES (?)", (email,))
sub_id = cur.lastrowid
db.execute(
"UPDATE subscribers SET ref_code = ? WHERE id = ?",
(referral_code(sub_id, SECRET), sub_id),
)
return sub_id
def record_referral(db, ref_code, referred_id):
"""Store the referral at signup time. Returns True if a row was added."""
row = db.execute(
"SELECT id FROM subscribers WHERE ref_code = ?", (ref_code,)
).fetchone()
if row is None:
return False # unknown code: ignore, never fail the signup
referrer_id = row[0]
if referrer_id == referred_id:
return False # self-referral
cur = db.execute(
"INSERT OR IGNORE INTO referrals "
"(referred_id, referrer_id, ref_code, captured_at) VALUES (?, ?, ?, ?)",
(referred_id, referrer_id, ref_code, now()),
)
return cur.rowcount == 1
def confirm(db, subscriber_id):
db.execute(
"UPDATE subscribers SET confirmed_at = ? WHERE id = ?",
(now(), subscriber_id),
)
db = sqlite3.connect(":memory:")
db.executescript(SCHEMA)
ana = add_subscriber(db, "[email protected]")
ben = add_subscriber(db, "[email protected]")
cy = add_subscriber(db, "[email protected]")
ana_code = db.execute("SELECT ref_code FROM subscribers WHERE id = ?", (ana,)).fetchone()[0]
print(record_referral(db, ana_code, ben)) # True
print(record_referral(db, ana_code, ana)) # False, self-referral
print(record_referral(db, "not-a-code", cy)) # False, unknown code
print(record_referral(db, ana_code, ben)) # False, already attributed
confirm(db, ben)Note the design choice: an invalid code never blocks a signup. A broken referral link should cost you one attribution, not one subscriber.
Counting only qualified referrals
Recording a referral at signup and rewarding it are separate steps. A referral that counts toward a milestone should require that the referred person confirmed their address and has not unsubscribed. The query below does this, and lists referrers who reached a five-referral milestone:
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;Because the filter runs when you query, a referral that later unsubscribes drops out of the count automatically. If you grant a reward when the threshold is reached, store the grant in its own table. Otherwise a reader who later falls below the threshold could be rewarded twice when they climb back over it.
You can also require a minimum age, for example that the referred subscriber stays subscribed for seven days, before the referral qualifies. Add a condition on confirmed_at against the current date. This delays rewards but removes many throwaway signups.
Attribution models and edge cases
First-touch attribution, where the first referrer captured wins, is the usual choice. It is easy to explain and cannot be overwritten by a later link. Last-touch lets the most recent link win, which invites referrers to push their link at someone who already clicked another. Pick one rule, document it in your program terms, and apply it everywhere.
| Situation | Recommended handling |
|---|---|
| Reader is already subscribed and clicks a referral link | Do not attribute. A referral must bring a new subscriber |
| Reader clicks two different referral links before signing up | First-touch: keep the first code captured |
| Reader opens the confirmation email on another device | Works if the code is stored on the pending row |
| Email security tools or privacy features prefetch links | Count confirmed signups, never clicks, as referrals |
| Someone shares a link on a public forum | Attribution still works. Abuse checks in a later chapter handle suspicious volume |
| Signup arrives with no code | Record the source as direct, organic, or the UTM source if present |
Referral clicks are also unreliable as a metric because automated systems fetch links. Use clicks only as a rough funnel signal. The confirmed signup is the event to trust.
For sources that are not referrals, such as a social post or a partner promotion, use the same pattern with UTM parameters (utm_source, utm_medium, utm_campaign). Store them on the subscriber row at signup. Then every subscriber has a source recorded, and you can compare referral subscribers to all others later when you judge subscriber quality by source.
Putting it together
A reliable attribution pipeline follows this order:
- Issue each subscriber an opaque, unique code and store the mapping.
- Capture the code from the link into the signup form and into a cookie.
- Save the code on the pending subscriber when the form is submitted.
- Create the referral row once, with first-touch rules and a self-referral check.
- Count a referral toward rewards only after the referred subscriber confirms and stays subscribed.
Exercise
A reader clicks Ana's referral link on their phone, submits their email, then opens the confirmation email on a laptop. A cookie-only system shows no referrer. What change makes the attribution survive, and why?
Show answer
Save the ref code on the server when the form is submitted, as part of the pending (unconfirmed) subscriber record. The confirmation click then needs no browser memory, because the code is already stored next to the email address, whichever device the reader uses to confirm.
Exercise
Why is the referrals table keyed on referredid instead of on the pair (referrerid, referred_id), and what rule does that choice enforce?
Show answer
Keying on referred_id allows at most one row per referred subscriber, so only one referrer can ever be credited for them. This enforces first-touch attribution. With INSERT OR IGNORE, a later referral for the same person is silently dropped. A key on the pair would permit several referrers to claim the same subscriber.
Exercise
Your five-referral milestone query counts Ben, who joined through Ana's link, confirmed, and then unsubscribed a week later. Does Ben count toward Ana's total, and which part of the query decides this?
Show answer
No. The condition s.unsubscribed_at IS NULL excludes Ben once he unsubscribes. His referral row still exists, but the query filters it out when it counts qualified referrals.