Email Sequences System
Reportr’s email sequences system manages automated email campaigns for user onboarding, trial reminders, and engagement. It ensures users receive timely, relevant communications without duplicates.Architecture Overview
Core Module
Location:src/lib/email-sequences.ts
Purpose: Manages triggered email campaigns with deduplication and time-based delivery
Key Components:
- Email log tracking (prevents duplicates)
- Time window matching (finds eligible users)
- User eligibility queries (identifies recipients)
Database Schema
EmailLog Model:@@unique([userId, emailType])- Prevents duplicate emails- Race condition safe with database constraints
Core Functions
hasEmailBeenSent()
Checks if a specific email has already been sent to a user.
Location: src/lib/email-sequences.ts:7
logEmailSent()
Records that an email was sent, preventing future duplicates.
Location: src/lib/email-sequences.ts:23
- Multiple processes can call this simultaneously
- Database unique constraint ensures only one record created
- Silently succeeds if email already logged
getUserEmailHistory()
Retrieves all emails sent to a specific user.
Location: src/lib/email-sequences.ts:52
isDateInWindow()
Checks if a date falls within today’s processing window.
Location: src/lib/email-sequences.ts:62
targetDate- Reference date (e.g., user signup date)daysOffset- Days to add to target date (e.g., 3 for “3 days after signup”)windowHours- Processing window duration (default 24 hours)
findUsersForTimeBasedEmail()
Finds all users eligible for a specific time-based email.
Location: src/lib/email-sequences.ts:89
Email Types
Type Definitions
Location:src/lib/email-types.ts
Email Sequences
Onboarding Sequence
Goal: Help new users get started and understand featuresTrial Management Sequence
Goal: Encourage trial users to upgrade before expirationUsage Alert Sequence
Goal: Notify users when approaching or reaching limitsCron Job Implementation
Daily Email Processing
Location:src/app/api/cron/send-emails/route.ts (planned)
Vercel Cron Configuration
File:vercel.json
Email Service Integration
Send Email Function
Location:src/lib/email-service.ts
Testing
Unit Tests
Best Practices
Deduplication
-
Always check before sending
-
Log immediately after sending
-
Handle race conditions gracefully
- Database constraint prevents duplicates
- Ignore P2002 errors (already logged)
Timing
- Use UTC for all date calculations
- Run cron jobs during low-traffic hours
- Add jitter to avoid thundering herd
Monitoring
- Track email delivery rates
- Monitor bounce rates
- Log all send failures
- Alert on high failure rates