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.

Improve lead and sale event tracking with Redis caching

Kiran Ke9865a404d79
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index f372eed794..2b73e74612 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -66,6 +66,7 @@ export const POST = withWorkspace(
message: `Customer with externalId ${customerExternalId} and event name ${eventName} has already been recorded.`,
});
}
+
// Find click event
const clickEvent = await getClickEvent({ clickId });
@@ -134,12 +135,17 @@ export const POST = withWorkspace(
// Execute customer creation synchronously
customer = await upsertCustomer();
- // Use recordLeadSync which waits for the operation to complete
- await recordLeadSync(createLeadEventPayload(customer.id));
+ const leadEventPayload = createLeadEventPayload(customer.id);
+
+ await Promise.all([
+ // Use recordLeadSync which waits for the operation to complete
+ recordLeadSync(leadEventPayload),
- // Add a small delay to ensure the operation is fully processed
- // This helps mitigate any potential race conditions
- await new Promise((resolve) => setTimeout(resolve, 500)); // 500ms buffer
+ // Cache the latest lead event for 5 minutes because the ingested event is not available immediately on Tinybird
+ redis.set(`latestLeadEvent:${customer.id}`, leadEventPayload, {
+ ex: 60 * 5,
+ }),
+ ]);
}
waitUntil(
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index dd4ff64cab..93b5041411 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -9,6 +9,7 @@ import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhookOnEdge } from "@/lib/webhook/publish-edge";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
import {
trackSaleRequestSchema,
trackSaleResponseSchema,
@@ -18,8 +19,11 @@ import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { differenceInMonths } from "date-fns";
import { NextResponse } from "next/server";
+import { z } from "zod";
import { determinePartnerReward } from "../determine-partner-reward-edge";
+type LeadEvent = z.infer<typeof leadEventSchemaTB>;
+
// POST /api/track/sale – Track a sale conversion event
export const POST = withWorkspace(
async ({ req, workspace }) => {
@@ -84,16 +88,29 @@ export const POST = withWorkspace(
eventName: leadEventName,
});
+ let leadEventData: LeadEvent | null = null;
+
if (!leadEvent || leadEvent.data.length === 0) {
- throw new DubApiError({
- code: "not_found",
- message: `Lead event not found for externalId: ${customerExternalId}`,
- });
+ // Check cache to see if the lead event exists
+ const cachedLeadEvent = await redis.get<LeadEvent>(
+ `latestLeadEvent:${customer.id}`,
+ );
+
+ if (!cachedLeadEvent) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Lead event not found for externalId: ${customerExternalId}`,
+ });
+ }
+
+ leadEventData = cachedLeadEvent;
+ } else {
+ leadEventData = leadEvent.data[0];
}
const clickData = clickEventSchemaTB
.omit({ timestamp: true })
- .parse(leadEvent.data[0]);
+ .parse(leadEventData);
// if currency is not USD, convert it to USD based on the current FX rate
// TODO: allow custom "defaultCurrency" on workspace table in the future