The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Share race-safe create-or-get for concurrent customer inserts.
Kiran K8f74fb2415a5
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.tsindex 92c16dfd35..8a4d6e9e9e 100644--- a/apps/web/lib/api/conversions/track-lead.ts+++ b/apps/web/lib/api/conversions/track-lead.ts@@ -1,4 +1,5 @@import { createId } from "@/lib/api/create-id";+import { createOrGetCustomer } from "@/lib/api/customers/create-or-get-customer";import { DubApiError } from "@/lib/api/errors";import { includeTags } from "@/lib/api/links/include-tags";import { generateRandomName } from "@/lib/names";@@ -165,10 +166,8 @@ export const trackLead = async ({: basePayload;};- // if the customer doesn't exist in our MySQL DB yet, upsert it- // (here we're doing upsert and not create in case of race conditions)if (!customer) {- customer = await prisma.customer.upsert({+ const { customer: createdOrFoundCustomer } = await createOrGetCustomer({where: {projectId_externalId: {projectId: workspace.id,@@ -190,8 +189,9 @@ export const trackLead = async ({country: clickData.country,clickedAt: new Date(clickData.timestamp + "Z"),},- update: {},});++ customer = createdOrFoundCustomer;}// if wait mode, record the lead event synchronouslydiff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex 3fe25ac040..a8396adec1 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -1,5 +1,6 @@import { convertCurrency } from "@/lib/analytics/convert-currency";import { isFirstConversion } from "@/lib/analytics/is-first-conversion";+import { createOrGetCustomer } from "@/lib/api/customers/create-or-get-customer";import { DubApiError } from "@/lib/api/errors";import { includeTags } from "@/lib/api/links/include-tags";import { generateRandomName } from "@/lib/names";@@ -31,7 +32,7 @@ import {trackSaleResponseSchema,} from "@/lib/zod/schemas/sales";import { nanoid, R2_URL } from "@dub/utils";-import { Customer, Prisma } from "@prisma/client";+import { Customer } from "@prisma/client";import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { createId } from "../create-id";@@ -183,9 +184,15 @@ export const trackSale = async ({? `${R2_URL}/customers/${finalCustomerId}/avatar_${nanoid(7)}`: customerAvatar;- try {- newCustomer = await prisma.customer.create({- data: {+ const { customer: createdOrFoundCustomer, created } =+ await createOrGetCustomer({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId: customerExternalId,+ },+ },+ create: {id: finalCustomerId,name: finalCustomerName,email: customerEmail,@@ -199,22 +206,11 @@ export const trackSale = async ({clickedAt: new Date(clickData.timestamp + "Z"),},});- } catch (error) {- if (- error instanceof Prisma.PrismaClientKnownRequestError &&- error.code === "P2002"- ) {- existingCustomer = await prisma.customer.findUniqueOrThrow({- where: {- projectId_externalId: {- projectId: workspace.id,- externalId: customerExternalId,- },- },- });- } else {- throw error;- }++ if (created) {+ newCustomer = createdOrFoundCustomer;+ } else {+ existingCustomer = createdOrFoundCustomer;}// Persist customer avatar to R2 if it's not already storeddiff --git a/apps/web/lib/api/customers/create-or-get-customer.ts b/apps/web/lib/api/customers/create-or-get-customer.tsnew file mode 100644index 0000000000..60ee7be124--- /dev/null+++ b/apps/web/lib/api/customers/create-or-get-customer.ts@@ -0,0 +1,46 @@+import { prisma } from "@/lib/prisma";+import { Prisma } from "@prisma/client";++/**+ * Race-safe customer create-or-get.+ *+ * Prisma's `customer.upsert()` can still throw P2002 under MySQL concurrency+ * (two requests miss the row, both attempt insert). This helper create-firsts+ * and on unique-constraint conflict falls back to find using `where`,+ * so concurrent track-lead / track-sale / etc. share one path instead of+ * failing the request.+ */+export async function createOrGetCustomer({+ where,+ create,+}: {+ where: Prisma.CustomerWhereUniqueInput;+ create: Prisma.CustomerUncheckedCreateInput;+}) {+ try {+ const customer = await prisma.customer.create({+ data: create,+ });++ return {+ customer,+ created: true,+ };+ } catch (error) {+ if (+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2002"+ ) {+ const customer = await prisma.customer.findUniqueOrThrow({+ where,+ });++ return {+ customer,+ created: false,+ };+ }++ throw error;+ }+}