The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Implement retry logic for Prisma operations in createLink function and add withPrismaRetry utility
Kiran K00804d72d224
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex 6ac368d7e6..fad95d5736 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -16,6 +16,7 @@ import { linkConstructorSimple } from "@dub/utils/src/functions/link-constructorimport { waitUntil } from "@vercel/functions";import { createId } from "../create-id";import { combineTagIds } from "../tags/combine-tag-ids";+import { withPrismaRetry } from "../utils/with-prisma-retry";import { scheduleABTestCompletion } from "./ab-test-scheduler";import { linkCache } from "./cache";import { encodeKeyIfCaseSensitive } from "./case-sensitivity";@@ -51,87 +52,89 @@ export async function createLink(link: ProcessedLinkProps) {key,});- const response = await prisma.link.create({- data: {- ...rest,- id: createId({ prefix: "link_" }),- key,- shortLink: linkConstructorSimple({ domain: link.domain, key }),- title: truncate(title, 120),- description: truncate(description, 240),- // if it's an uploaded image, make this null first because we'll update it later- image: proxy && image && isNotHostedImage(image) ? null : image,- utm_source,- utm_medium,- utm_campaign,- utm_term,- utm_content,- expiresAt: expiresAt ? new Date(expiresAt) : null,- geo: geo || Prisma.DbNull,-- testVariants: testVariants || Prisma.DbNull,- testCompletedAt: testCompletedAt ? new Date(testCompletedAt) : null,- testStartedAt: testStartedAt ? new Date(testStartedAt) : null,-- // Associate tags by tagNames- ...(tagNames?.length &&- link.projectId && {- tags: {- create: tagNames.map((tagName, idx) => ({- tag: {- connect: {- name_projectId: {- name: tagName,- projectId: link.projectId as string,+ const response = await withPrismaRetry(() =>+ prisma.link.create({+ data: {+ ...rest,+ id: createId({ prefix: "link_" }),+ key,+ shortLink: linkConstructorSimple({ domain: link.domain, key }),+ title: truncate(title, 120),+ description: truncate(description, 240),+ // if it's an uploaded image, make this null first because we'll update it later+ image: proxy && image && isNotHostedImage(image) ? null : image,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ expiresAt: expiresAt ? new Date(expiresAt) : null,+ geo: geo || Prisma.DbNull,++ testVariants: testVariants || Prisma.DbNull,+ testCompletedAt: testCompletedAt ? new Date(testCompletedAt) : null,+ testStartedAt: testStartedAt ? new Date(testStartedAt) : null,++ // Associate tags by tagNames+ ...(tagNames?.length &&+ link.projectId && {+ tags: {+ create: tagNames.map((tagName, idx) => ({+ tag: {+ connect: {+ name_projectId: {+ name: tagName,+ projectId: link.projectId as string,+ },},},- },- createdAt: new Date(new Date().getTime() + idx * 100), // increment by 100ms for correct order- })),- },- }),-- // Associate tags by IDs (takes priority over tagNames)- ...(combinedTagIds &&- combinedTagIds.length > 0 && {- tags: {- createMany: {- data: combinedTagIds.map((tagId, idx) => ({- tagId,createdAt: new Date(new Date().getTime() + idx * 100), // increment by 100ms for correct order})),},- },- }),-- // Webhooks- ...(webhookIds &&- webhookIds.length > 0 && {- webhooks: {- createMany: {- data: webhookIds.map((webhookId) => ({- webhookId,- })),+ }),++ // Associate tags by IDs (takes priority over tagNames)+ ...(combinedTagIds &&+ combinedTagIds.length > 0 && {+ tags: {+ createMany: {+ data: combinedTagIds.map((tagId, idx) => ({+ tagId,+ createdAt: new Date(new Date().getTime() + idx * 100), // increment by 100ms for correct order+ })),+ },+ },+ }),++ // Webhooks+ ...(webhookIds &&+ webhookIds.length > 0 && {+ webhooks: {+ createMany: {+ data: webhookIds.map((webhookId) => ({+ webhookId,+ })),+ },+ },+ }),++ // Shared dashboard+ ...(publicStats && {+ dashboard: {+ create: {+ id: createId({ prefix: "dash_" }),+ projectId: link.projectId,+ userId: link.userId,},},}),-- // Shared dashboard- ...(publicStats && {- dashboard: {- create: {- id: createId({ prefix: "dash_" }),- projectId: link.projectId,- userId: link.userId,- },- },- }),- },- include: {- ...includeTags,- webhooks: webhookIds ? true : false,- },- });+ },+ include: {+ ...includeTags,+ webhooks: webhookIds ? true : false,+ },+ }),+ );const uploadedImageUrl = `${R2_URL}/images/${response.id}`;diff --git a/apps/web/lib/api/utils/with-prisma-retry.ts b/apps/web/lib/api/utils/with-prisma-retry.tsnew file mode 100644index 0000000000..87d2138f56--- /dev/null+++ b/apps/web/lib/api/utils/with-prisma-retry.ts@@ -0,0 +1,52 @@+import { Prisma } from "@dub/prisma/client";++const DEFAULT_CONFIG = {+ maxRetries: 2,+ retryDelay: 1000, // 1 second+ exponentialBackoff: true,+};++// Helper function for retrying operations+export async function withPrismaRetry<T>(+ operation: () => Promise<T>,+ config = DEFAULT_CONFIG,+): Promise<T> {+ let lastError: Error;++ for (let attempt = 0; attempt < config.maxRetries; attempt++) {+ try {+ return await operation();+ } catch (error) {+ lastError = error as Error;++ // Don't retry on certain errors (e.g., validation errors, unique constraint violations)+ if (error instanceof Prisma.PrismaClientKnownRequestError) {+ // Don't retry unique constraint violations or validation errors+ if (error.code === "P2002" || error.code === "P2003") {+ throw error;+ }+ }++ // Don't retry on the last attempt+ if (attempt === config.maxRetries - 1) {+ console.error(`Failed after ${config.maxRetries} attempts:`, error);+ throw error;+ }++ // Calculate delay with exponential backoff+ const delay = config.exponentialBackoff+ ? config.retryDelay * Math.pow(2, attempt)+ : config.retryDelay;++ console.warn(+ `Failed (attempt ${attempt + 1}/${config.maxRetries}), retrying in ${delay}ms:`,+ error.message,+ );++ // Add delay before retrying+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }++ throw lastError!;+}