Sub topic 2
How a Referral Program Works
This chapter assumes you know how an email service provider (ESP) stores subscribers and sends confirmation emails. It also assumes you can read short Python and SQL. It covers the mechanics of a referral program: the parts, the life of one referral, and the data you need to run it. Reward design, k-factor math, link construction, abuse controls and legal rules each get their own chapter, so this one only points to them.
What a referral program is
A referral program asks existing subscribers to bring in new ones, usually by sharing a personal link. When a person subscribes through that link and meets a defined condition, the referrer earns credit toward a reward.
The program is the first working piece of a growth loop. Each new subscriber becomes a possible source of more subscribers. A one-off promotion, such as a paid ad, stops producing subscribers when you stop paying. A referral program keeps producing them as long as readers value the newsletter and the sharing step is easy.
A working program does four things:
- It gives every subscriber a way to identify themselves as a referrer.
- It records which referrer a new signup came from.
- It decides when a referral counts.
- It delivers the reward when counted referrals reach a threshold.
The moving parts
| Part | Job | Typical implementation |
|---|---|---|
| Referral code | Identifies the referrer in a link | Short random string stored on the subscriber record |
| Landing page | Receives the click and shows the signup form | Page that reads `?ref=` and keeps the value through signup |
| Signup handler | Creates the subscriber and links them to the referrer | Server code or ESP automation |
| Confirmation step | Proves the new address is real and wanted | Double opt-in email |
| Referral ledger | Stores each referrer-to-referred pair and its status | A `referrals` table |
| Reward engine | Checks thresholds and triggers rewards | Scheduled job or event handler |
| Referrer dashboard | Shows progress | Page or email block with counts and next milestone |
You can buy these parts as a hosted referral platform or build them. In both cases the data model stays the same, so it is worth understanding even if you never write it.
The life of one referral
A referral passes through several systems. Each handoff is a place where the referrer can be lost, so follow it end to end.
Two details matter here. The referral is recorded at signup, before the friend confirms. Credit is only granted at confirmation. Recording early means you never lose the attribution if the friend confirms an hour later on a different device. Granting late means unconfirmed or mistyped addresses never earn rewards.
Referral states
Treat each referral as a record that moves through states, not as a yes-or-no flag.
Keeping a status column lets you answer questions that a plain counter cannot. How many referrals are waiting on confirmation? How many expired? Which qualified referrals were revoked, and why? You will use those answers in the abuse and quality chapters.
A minimal working core
The following script implements the ledger with SQLite. It creates subscribers with random referral codes, records pending referrals at signup, qualifies them on confirmation, and counts only qualified referrals whose subscribers are still subscribed.
import secrets
import sqlite3
from datetime import datetime, timezone
SCHEMA = """
CREATE TABLE subscribers (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
referral_code TEXT UNIQUE,
source TEXT NOT NULL,
created_at TEXT NOT NULL,
confirmed_at TEXT,
unsubscribed_at TEXT
);
CREATE TABLE referrals (
id INTEGER PRIMARY KEY,
referrer_id INTEGER NOT NULL REFERENCES subscribers(id),
referred_id INTEGER NOT NULL UNIQUE REFERENCES subscribers(id),
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL,
qualified_at TEXT
);
"""
def now():
return datetime.now(timezone.utc).isoformat()
def signup(conn, email, ref_code=None):
"""Create a subscriber. Record a pending referral if the code is valid."""
existing = conn.execute(
"SELECT id FROM subscribers WHERE email = ?", (email,)
).fetchone()
if existing:
# Existing subscribers cannot be referred a second time.
return existing[0]
referrer = None
if ref_code:
row = conn.execute(
"SELECT id FROM subscribers WHERE referral_code = ?", (ref_code,)
).fetchone()
referrer = row[0] if row else None
source = "referral" if referrer else "direct"
cur = conn.execute(
"INSERT INTO subscribers (email, referral_code, source, created_at) "
"VALUES (?, ?, ?, ?)",
(email, secrets.token_urlsafe(6), source, now()),
)
new_id = cur.lastrowid
if referrer:
conn.execute(
"INSERT INTO referrals (referrer_id, referred_id, created_at) "
"VALUES (?, ?, ?)",
(referrer, new_id, now()),
)
return new_id
def confirm(conn, subscriber_id):
"""Confirm the address and qualify any pending referral for it."""
conn.execute(
"UPDATE subscribers SET confirmed_at = ? WHERE id = ?",
(now(), subscriber_id),
)
conn.execute(
"UPDATE referrals SET status = 'qualified', qualified_at = ? "
"WHERE referred_id = ? AND status = 'pending'",
(now(), subscriber_id),
)
def qualified_count(conn, referrer_id):
return conn.execute(
"SELECT COUNT(*) FROM referrals AS r "
"JOIN subscribers AS s ON s.id = r.referred_id "
"WHERE r.referrer_id = ? AND r.status = 'qualified' "
"AND s.unsubscribed_at IS NULL",
(referrer_id,),
).fetchone()[0]
conn = sqlite3.connect(":memory:")
conn.executescript(SCHEMA)
alice = signup(conn, "[email protected]")
confirm(conn, alice)
alice_code = conn.execute(
"SELECT referral_code FROM subscribers WHERE id = ?", (alice,)
).fetchone()[0]
bob = signup(conn, "[email protected]", alice_code)
carol = signup(conn, "[email protected]", alice_code)
confirm(conn, bob) # Carol never confirms.
pending = conn.execute(
"SELECT COUNT(*) FROM referrals WHERE status = 'pending'"
).fetchone()[0]
print("qualified:", qualified_count(conn, alice)) # qualified: 1
print("pending:", pending) # pending: 1The script prints qualified: 1 and pending: 1. Three design choices in it are worth copying:
referred_idisUNIQUE, so one person can be credited to only one referrer.- The
sourcefield is set at signup. Later chapters use it to compare subscriber quality by acquisition channel. - The referral code is random and not derived from the subscriber id. If codes were sequential, anyone could guess another subscriber's code.
Decisions to make before launch
Most referral programs fail on definitions, not on code. Settle these in writing before you build.
What counts as a referral
Pick the qualifying event and keep it fixed. Common choices are, from weakest to strongest:
- The friend submits an email address.
- The friend confirms the address through double opt-in.
- The friend confirms and opens at least one issue.
- The friend confirms and stays subscribed for a set period, such as 14 days.
The first option is easy to inflate with fake addresses. The last is the most reliable, but it delays the referrer's reward. Confirmation is the usual minimum because it is cheap to check and screens out typos and made-up emails. Stricter rules suit programs with larger rewards.
When the reward is granted
Reward on qualification or on a milestone? Granting a small reward per referral gives fast feedback. Granting only at milestones, for example at 3, 10 and 25 qualified referrals, rewards sustained effort. The next chapter covers that choice. For now, make sure your ledger supports both by counting qualified rows rather than storing a running total.
Who can refer
Allowing only confirmed subscribers to refer keeps unconfirmed accounts from earning rewards. Decide whether unsubscribed people keep their code and whether their past referrals still count.
Who can be referred
Decide what happens when someone who is already subscribed clicks a referral link. The sample code ignores the link and credits no one. That is the simplest rule, but write it down so support staff can explain it to a referrer who asks why a friend did not count.
Common errors
- Losing the code between click and signup. The
?ref=value exists only on the landing page URL. If the visitor navigates to another page before signing up, the code is gone. Store it in a first-party cookie or pass it through every step of the form. - Crediting at signup instead of confirmation. This rewards fake and mistyped addresses and pushes your bounce rate up.
- Counting with a stored integer. A
referral_countcolumn drifts when a referral is revoked or a subscriber unsubscribes. Derive counts from the ledger, asqualified_countdoes. - No uniqueness on the referred person. Without a constraint, a race between two requests can create two referrals for one person.
- Not recording non-referral signups. If direct signups have no
source, you cannot compare referred subscribers with the rest later. - Hiding the dashboard. Referrers who cannot see their progress stop sharing. Show the current count and distance to the next milestone.
Edge cases to handle
| Situation | Suggested handling |
|---|---|
| Friend signs up twice with different referrers | Keep the first referral, enforced by the unique `referred_id` |
| Friend clicks a link, but signs up days later directly | Decide on an attribution window. Many programs use 30 days |
| Referrer unsubscribes after referring | Keep qualified referrals, but decide whether the reward is still owed |
| Friend unsubscribes right after confirming | Count only referrals still subscribed, or require a retention period |
| Same person uses their own second email | Cannot be prevented by the ledger alone, see the abuse chapter |
| Referral code in an old email is rotated | Keep old codes resolving to the same subscriber |
Measuring whether it works
Once the ledger runs, you can read basic health figures straight from it:
- Participation rate: referrers who shared at least once, divided by active subscribers.
- Signup-to-qualified rate: qualified referrals divided by all referral records. A low value points to confirmation problems.
- Share of new subscribers from referrals: referral-sourced signups divided by all signups in a period.
These feed the k-factor and quality chapters. Capture the raw data now, because you cannot rebuild a missing history later.
Exercise
A friend clicks Alice's referral link, but leaves the page and signs up two days later by typing the newsletter URL directly. The code was never stored. What happens in the sample code, and what is a fix?
Show answer
The sample code receives no ref_code, so it sets source to direct and creates no referral record. Alice gets no credit. The fix is to save the ref value in a first-party cookie (or local storage) when the landing page loads, then send it with the signup request, with an expiry matching your attribution window, such as 30 days.
Exercise
Why does the ledger store each referral as a row with a status, rather than adding 1 to a referral_count column on the referrer when the friend signs up?
Show answer
A row with a status lets you count only qualified referrals, see which are pending or expired, and revoke one later without the total drifting. A stored counter cannot tell you which referral produced a change. It also goes wrong when a signup is retried or a subscriber unsubscribes, and it would credit unconfirmed addresses if it is updated at signup.
Exercise
Write the SQL condition that would limit qualified_count to referrals that were qualified at least 14 days ago, so a retention period applies.
Show answer
Add AND r.qualified_at <= datetime('now', '-14 days') to the WHERE clause. SQLite's datetime returns a space-separated format, so store qualified_at in the same format, or compare with julianday() on both sides, because the sample code stores ISO strings with a T and a timezone suffix.