fix: send invite emails before inserting DB records to avoid partial-state bugs - #303
Conversation
…state bugs Reversed the order of operations in POST /api/referrals: - Emails are now sent FIRST - DB records are only created for successfully delivered emails - Previously, DB records were created even if emails failed to send. - Also returns 502 if all emails fail instead of a misleading 200.
Greptile SummaryThis PR reverses the order of operations in
Confidence Score: 3/5The reordering fixes one class of inconsistency but opens a symmetric one: a DB write failure after successful email delivery leaves no trace of the send, so a user retry will dispatch duplicate invitation emails to the same recipients. The core logic change swaps which side of the transaction is durable when something goes wrong. The DB insert path (lines 183-190) is still fallible after emails have already left the door, and nothing in the handler catches or compensates for that case. src/app/api/referrals/route.ts - specifically the DB insert error branch (lines 183-190) and the rate-limit check interaction with partial delivery. Important Files Changed
Sequence DiagramsequenceDiagram
participant C as Client
participant API as POST /api/referrals
participant ES as Email Service
participant DB as Supabase DB
C->>API: "POST { emails: [...] }"
API->>API: Validate input, check rate limits
API->>DB: Query existing invites (dedup)
API->>DB: Query profile (referralCode)
Note over API,ES: NEW ORDER (this PR)
API->>ES: sendEmail() for each newValidEmail
ES-->>API: emailResults[]
alt All emails fail
API-->>C: 502 Failed to send invitation emails
else Some/all emails succeed
API->>DB: INSERT referralRows (only successful emails)
alt DB insert fails
Note over API,DB: Emails sent but no DB record, retry sends duplicates
API-->>C: 400 DB error
else DB insert succeeds
API-->>C: 200 message data email_delivery_failed
end
end
|
Summary
Reverses the order of operations in
POST /api/referralsto prevent partial-state bugs.Problem
Previously, referral records were inserted into the database first, then emails were sent asynchronously. If email delivery failed, the database would show invites that were never actually sent.
Fix
Affects the affiliate/invite friends flow.