Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Fix Resend batch Idempotency key (#3043)

Kiran Ka14e27f28067
diff --git a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
index 08c76c72d7..afacbf54c7 100644
--- a/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
+++ b/apps/web/app/(ee)/api/cron/bounties/notify-partners/route.ts
@@ -132,10 +132,10 @@ export async function POST(req: Request) {
},
}),
tags: [{ name: "type", value: "notification-email" }],
- headers: {
- "Idempotency-Key": `${bountyId}-page-${page}`,
- },
})),
+ {
+ idempotencyKey: `bounty-notify/${bountyId}-page-${page}`,
+ },
);
if (data) {
diff --git a/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts b/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts
index 27b7df96a1..c7fe0e8b7b 100644
--- a/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts
+++ b/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts
@@ -222,28 +222,33 @@ export async function POST(req: Request) {
// Make sure the cache is cleared
await redis.del(`${CACHE_KEY_PREFIX}:${userId}`);
- await sendBatchEmail([
- {
- variant: "notifications",
- to: sourceEmail,
- subject: "Your Dub partner accounts are now merged",
- react: PartnerAccountMerged({
- email: sourceEmail,
- sourceEmail,
- targetEmail,
- }),
- },
+ await sendBatchEmail(
+ [
+ {
+ variant: "notifications",
+ to: sourceEmail,
+ subject: "Your Dub partner accounts are now merged",
+ react: PartnerAccountMerged({
+ email: sourceEmail,
+ sourceEmail,
+ targetEmail,
+ }),
+ },
+ {
+ variant: "notifications",
+ to: targetEmail,
+ subject: "Your Dub partner accounts are now merged",
+ react: PartnerAccountMerged({
+ email: targetEmail,
+ sourceEmail,
+ targetEmail,
+ }),
+ },
+ ],
{
- variant: "notifications",
- to: targetEmail,
- subject: "Your Dub partner accounts are now merged",
- react: PartnerAccountMerged({
- email: targetEmail,
- sourceEmail,
- targetEmail,
- }),
+ idempotencyKey: `merge-partner-accounts/${userId}`,
},
- ]);
+ );
return new Response(
`Partner account ${sourceEmail} merged into ${targetEmail}.`,
diff --git a/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts b/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
index fcc67b9723..c93d54734f 100644
--- a/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
+++ b/apps/web/app/(ee)/api/cron/partner-program-summary/route.ts
@@ -337,6 +337,9 @@ async function handler(req: Request) {
}),
variant: "notifications",
})),
+ {
+ idempotencyKey: `partner-summary/${program.id}/${format(currentMonth, "yyyy-MM")}`,
+ },
);
}
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
index a102037c5e..e0c9abb303 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts
@@ -305,7 +305,7 @@ export async function processPayouts({
},
})),
{
- deduplicationId: invoice.id,
+ idempotencyKey: `payout-confirmed/${invoice.id}`,
},
);
}
diff --git a/apps/web/app/(ee)/api/cron/send-batch-email/route.ts b/apps/web/app/(ee)/api/cron/send-batch-email/route.ts
index b89174a283..a619e8035e 100644
--- a/apps/web/app/(ee)/api/cron/send-batch-email/route.ts
+++ b/apps/web/app/(ee)/api/cron/send-batch-email/route.ts
@@ -46,6 +46,8 @@ export async function POST(req: Request) {
const payload = batchEmailPayloadSchema.parse(JSON.parse(rawBody));
+ const idempotencyKey = req.headers.get("Idempotency-Key") || undefined;
+
console.log(`Processing batch of ${payload.length} email(s)`);
// Process all emails in parallel and build Resend payload
@@ -140,7 +142,9 @@ export async function POST(req: Request) {
console.log(`Sending ${emailsToSend.length} email(s) via Resend.`);
- const { data, error } = await sendBatchEmail(emailsToSend);
+ const { data, error } = await sendBatchEmail(emailsToSend, {
+ idempotencyKey,
+ });
if (error) {
console.error("Resend API error:", error);
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index 1016e93443..18f68bfff0 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -243,10 +243,10 @@ export const { POST } = serve<Payload>(
showModifiersTooltip: false,
}),
}),
- headers: {
- "Idempotency-Key": `application-approved-${programEnrollment.id}`,
- },
})),
+ {
+ idempotencyKey: `application-approved/${programEnrollment.id}`,
+ },
);
if (data) {
diff --git a/apps/web/lib/email/queue-batch-email.ts b/apps/web/lib/email/queue-batch-email.ts
index bbf0b3c1fc..9c407c322a 100644
--- a/apps/web/lib/email/queue-batch-email.ts
+++ b/apps/web/lib/email/queue-batch-email.ts
@@ -18,7 +18,7 @@ const queue = qstash.queue({
export async function queueBatchEmail<TTemplate extends (props: any) => any>(
emails: QueueBatchProps<TTemplate>[],
options?: {
- deduplicationId?: string;
+ idempotencyKey?: string; // Used for both QStash deduplication AND Resend idempotency
},
): Promise<string[]> {
if (emails.length === 0) {
@@ -39,19 +39,35 @@ export async function queueBatchEmail<TTemplate extends (props: any) => any>(
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
+ // Generate batch-specific idempotency key
+ const idempotencyKey = options?.idempotencyKey
+ ? batches.length > 1
+ ? `${options.idempotencyKey}-batch-${i}`
+ : options.idempotencyKey
+ : undefined;
+
const response = await queue.enqueueJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/send-batch-email`,
method: "POST",
body: batch,
- ...(options?.deduplicationId && {
- deduplicationId: `${options.deduplicationId}-batch-${i}`,
+ ...(idempotencyKey && {
+ deduplicationId: idempotencyKey, // QStash deduplication
+ }),
+ ...(idempotencyKey && {
+ headers: {
+ "Idempotency-Key": idempotencyKey, // Resend idempotency
+ },
}),
});
messageIds.push(response.messageId);
console.log(
- `Enqueued batch ${i + 1}/${batches.length} with ${batch.length} email(s): ${response.messageId}`,
+ `Enqueued batch ${i + 1}/${batches.length} with ${batch.length} email(s):`,
+ {
+ messageId: response.messageId,
+ ...(idempotencyKey && { idempotencyKey }),
+ },
);
}
diff --git a/packages/email/src/index.ts b/packages/email/src/index.ts
index 70329577d0..33f7c73e83 100644
--- a/packages/email/src/index.ts
+++ b/packages/email/src/index.ts
@@ -28,9 +28,12 @@ export const sendEmail = async (opts: ResendEmailOptions) => {
);
};
-export const sendBatchEmail = async (payload: ResendBulkEmailOptions) => {
+export const sendBatchEmail = async (
+ payload: ResendBulkEmailOptions,
+ options?: { idempotencyKey?: string },
+) => {
if (resend) {
- return await sendBatchEmailViaResend(payload);
+ return await sendBatchEmailViaResend(payload, options);
}
// Fallback to SMTP if Resend is not configured
diff --git a/packages/email/src/send-via-resend.ts b/packages/email/src/send-via-resend.ts
index 4c87033944..ecb2f4f04c 100644
--- a/packages/email/src/send-via-resend.ts
+++ b/packages/email/src/send-via-resend.ts
@@ -54,7 +54,10 @@ export const sendEmailViaResend = async (opts: ResendEmailOptions) => {
return await resend.emails.send(resendEmailForOptions(opts));
};
-export const sendBatchEmailViaResend = async (opts: ResendBulkEmailOptions) => {
+export const sendBatchEmailViaResend = async (
+ opts: ResendBulkEmailOptions,
+ options?: { idempotencyKey?: string },
+) => {
if (!resend) {
console.info(
"RESEND_API_KEY is not set in the .env. Skipping sending email.",
@@ -75,5 +78,10 @@ export const sendBatchEmailViaResend = async (opts: ResendBulkEmailOptions) => {
const payload = opts.map(resendEmailForOptions);
- return await resend.batch.send(payload);
+ const idempotencyKey = options?.idempotencyKey || undefined;
+
+ return await resend.batch.send(
+ payload,
+ idempotencyKey ? { idempotencyKey } : undefined,
+ );
};