How to Build a Referral Tracking System from Scratch
Referral tracking is essential for any growth-focused business. It lets you attribute new customers to specific referrers, reward them, and optimize your marketing spend. Building one from scratch gives you full control and avoids vendor lock-in.
Start by defining your referral logic: a unique code or link per user, tracking clicks, sign-ups, and conversions. Then design the database schema and implement the tracking logic on your backend.
1. Design the Referral Data Model
Store referral relationships in a single table:
- referrer_id – the user who referred
- referral_code – unique alphanumeric (e.g., UUID or user-id + random)
- clicked_by – optional, stores visitor IDs until they sign up
- status – pending, converted, rewarded
- created_at – timestamp
Keep the schema simple. Index the referral_code for fast lookups.
2. Generate Unique Referral Links
When a user signs up, create a referral code and append it to your base URL (e.g., example.com?ref=ABC123). Use a hash function or a short UUID generator to avoid collisions.
3. Implement Click Tracking
On your landing pages, read the ref parameter. Store it in a cookie or localStorage for 30 days (cookie-based attribution). Use a server-side endpoint (e.g., /track-click) to log each click with referrer_id, visitor IP, and user-agent. This prevents fraud.
4. Tie Conversions to Referrals
When a visitor signs up, check the cookie/localStorage for the referral code. Update the referral record’s status to “converted” and, if applicable, trigger a reward (discount, credit, etc.). Add an API endpoint to verify and mark the referral as fulfilled.
5. Build a Dashboard for Referrers
Create a simple page where users see their unique link, number of clicks, conversions, and pending rewards. Use a REST endpoint that queries the referral table grouped by referrer_id. Keep it real-time with a short cache.
Test your system with manual links and invalid codes. Once stable, you can scale with A/B testing and more complex reward tiers.