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.

Offload workspace links usage to `workspaceLinksUsageStream` (#3820)

Steven Tey881b8683e733
diff --git a/apps/web/app/(ee)/api/cron/streams/update-workspace-clicks/route.ts b/apps/web/app/(ee)/api/cron/streams/update-workspace-clicks/route.ts
index f043109c86..cb5b5b8a8e 100644
--- a/apps/web/app/(ee)/api/cron/streams/update-workspace-clicks/route.ts
+++ b/apps/web/app/(ee)/api/cron/streams/update-workspace-clicks/route.ts
@@ -2,9 +2,9 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
import { conn } from "@/lib/planetscale";
import {
- ClickEvent,
RedisStreamEntry,
- workspaceUsageStream,
+ WorkspaceClicksUsageEvent,
+ workspaceClicksUsageStream,
} from "@/lib/upstash/redis-streams";
import { NextResponse } from "next/server";
@@ -21,7 +21,7 @@ type WorkspaceAggregateUsage = {
};
const aggregateWorkspaceUsage = (
- entries: RedisStreamEntry<ClickEvent>[],
+ entries: RedisStreamEntry<WorkspaceClicksUsageEvent>[],
): { updates: WorkspaceAggregateUsage[]; lastProcessedId: string | null } => {
// Aggregate usage by workspaceId
const aggregatedUsage = new Map<string, WorkspaceAggregateUsage>();
@@ -68,7 +68,7 @@ const aggregateWorkspaceUsage = (
};
const processWorkspaceUpdateStreamBatch = () =>
- workspaceUsageStream.processBatch<ClickEvent>(
+ workspaceClicksUsageStream.processBatch<WorkspaceClicksUsageEvent>(
async (entries) => {
if (!entries || Object.keys(entries).length === 0) {
return {
@@ -197,7 +197,7 @@ export async function GET(req: Request) {
}
// Get stream info for monitoring
- const streamInfo = await workspaceUsageStream.getStreamInfo();
+ const streamInfo = await workspaceClicksUsageStream.getStreamInfo();
const response = {
success: true,
processed: totalProcessed,
diff --git a/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts b/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts
new file mode 100644
index 0000000000..f360a2957e
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts
@@ -0,0 +1,340 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { sendLimitEmail } from "@/lib/cron/send-limit-email";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { WorkspaceProps } from "@/lib/types";
+import {
+ RedisStreamEntry,
+ WorkspaceLinksUsageEvent,
+ workspaceLinksUsageStream,
+} from "@/lib/upstash/redis-streams";
+import { prisma } from "@dub/prisma";
+import { log } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+export const dynamic = "force-dynamic";
+
+const BATCH_SIZE = 10000;
+
+type WorkspaceLinksUsageAggregate = {
+ workspaceId: string;
+ linksCount: number;
+ entryIds: string[];
+};
+
+type LimitEmailType = "firstLinksLimitEmail" | "secondLinksLimitEmail";
+
+const getLimitEmailType = (percentage: number): LimitEmailType | null => {
+ if (percentage < 80) {
+ return null;
+ }
+
+ if (percentage < 100) {
+ return "firstLinksLimitEmail";
+ }
+
+ return "secondLinksLimitEmail";
+};
+
+const aggregateWorkspaceLinksUsage = (
+ entries: RedisStreamEntry<WorkspaceLinksUsageEvent>[],
+): {
+ updates: WorkspaceLinksUsageAggregate[];
+ lastProcessedId: string | null;
+} => {
+ const aggregatedUsage = new Map<string, WorkspaceLinksUsageAggregate>();
+ let lastProcessedId: string | null = null;
+
+ for (const entry of entries) {
+ const workspaceId = entry.data.workspaceId;
+ const linksCount = Number(entry.data.linksCount);
+
+ if (!workspaceId || !Number.isFinite(linksCount) || linksCount <= 0) {
+ continue;
+ }
+
+ lastProcessedId = entry.id;
+
+ if (aggregatedUsage.has(workspaceId)) {
+ const existing = aggregatedUsage.get(workspaceId)!;
+ existing.linksCount += linksCount;
+ existing.entryIds.push(entry.id);
+ continue;
+ }
+
+ aggregatedUsage.set(workspaceId, {
+ workspaceId,
+ linksCount,
+ entryIds: [entry.id],
+ });
+ }
+
+ return {
+ updates: Array.from(aggregatedUsage.values()),
+ lastProcessedId,
+ };
+};
+
+const processWorkspaceLinksUsageBatch = () =>
+ workspaceLinksUsageStream.processBatch<WorkspaceLinksUsageEvent>(
+ async (entries) => {
+ if (!entries || entries.length === 0) {
+ return {
+ success: true,
+ updates: [],
+ processedEntryIds: [],
+ };
+ }
+
+ const { updates, lastProcessedId } =
+ aggregateWorkspaceLinksUsage(entries);
+
+ if (updates.length === 0) {
+ return {
+ success: true,
+ updates: [],
+ processedEntryIds: [],
+ };
+ }
+
+ const SUB_BATCH_SIZE = 50;
+ const batches: WorkspaceLinksUsageAggregate[][] = [];
+
+ for (let i = 0; i < updates.length; i += SUB_BATCH_SIZE) {
+ batches.push(updates.slice(i, i + SUB_BATCH_SIZE));
+ }
+
+ const processedEntryIds: string[] = [];
+ const errors: { workspaceId: string; error: unknown }[] = [];
+ const updatedWorkspaces: (WorkspaceProps & {
+ linksUsage: number;
+ linksLimit: number;
+ })[] = [];
+ let totalProcessed = 0;
+
+ for (const batch of batches) {
+ const batchResults = await Promise.allSettled(
+ batch.map(async (update) => {
+ const workspace = await prisma.project.update({
+ where: {
+ id: update.workspaceId,
+ },
+ data: {
+ linksUsage: {
+ increment: update.linksCount,
+ },
+ totalLinks: {
+ increment: update.linksCount,
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ linksUsage: true,
+ linksLimit: true,
+ plan: true,
+ },
+ });
+
+ processedEntryIds.push(...update.entryIds);
+ return workspace;
+ }),
+ );
+
+ batchResults.forEach((result, index) => {
+ if (result.status === "fulfilled") {
+ totalProcessed++;
+ updatedWorkspaces.push(
+ result.value as (typeof updatedWorkspaces)[number],
+ );
+ return;
+ }
+
+ errors.push({
+ workspaceId: batch[index].workspaceId,
+ error: result.reason,
+ });
+ });
+ }
+
+ const workspacesAboveThreshold = updatedWorkspaces
+ .map((workspace) => {
+ const percentage = Math.round(
+ (workspace.linksUsage / workspace.linksLimit) * 100,
+ );
+ const emailType = getLimitEmailType(percentage);
+
+ return {
+ workspace,
+ percentage,
+ emailType,
+ };
+ })
+ .filter(
+ (
+ item,
+ ): item is {
+ workspace: (typeof updatedWorkspaces)[number];
+ percentage: number;
+ emailType: LimitEmailType;
+ } => item.emailType !== null,
+ );
+
+ const workspaceIds = workspacesAboveThreshold.map(
+ ({ workspace }) => workspace.id,
+ );
+ let notificationsSent = 0;
+
+ if (workspaceIds.length > 0) {
+ const sentEmails = await prisma.sentEmail.findMany({
+ where: {
+ projectId: {
+ in: workspaceIds,
+ },
+ type: {
+ in: ["firstLinksLimitEmail", "secondLinksLimitEmail"],
+ },
+ },
+ select: {
+ projectId: true,
+ type: true,
+ },
+ });
+
+ const sentEmailSet = new Set(
+ sentEmails.map((email) => `${email.projectId}:${email.type}`),
+ );
+
+ const users = await prisma.user.findMany({
+ where: {
+ projects: {
+ some: {
+ projectId: {
+ in: workspaceIds,
+ },
+ },
+ },
+ },
+ select: {
+ email: true,
+ projects: {
+ where: {
+ projectId: {
+ in: workspaceIds,
+ },
+ },
+ select: {
+ projectId: true,
+ },
+ },
+ },
+ });
+
+ const emailsByWorkspace = new Map<string, string[]>();
+ for (const user of users) {
+ if (!user.email) {
+ continue;
+ }
+
+ for (const project of user.projects) {
+ if (!project.projectId) {
+ continue;
+ }
+
+ const existingEmails =
+ emailsByWorkspace.get(project.projectId) ?? [];
+ existingEmails.push(user.email);
+ emailsByWorkspace.set(project.projectId, existingEmails);
+ }
+ }
+
+ const notificationResults = await Promise.allSettled(
+ workspacesAboveThreshold.map(
+ async ({ workspace, percentage, emailType }) => {
+ const sentKey = `${workspace.id}:${emailType}`;
+ if (sentEmailSet.has(sentKey)) {
+ return { skipped: true };
+ }
+
+ const emails = emailsByWorkspace.get(workspace.id) ?? [];
+ if (emails.length === 0) {
+ return { skipped: true };
+ }
+
+ await Promise.allSettled([
+ sendLimitEmail({
+ emails,
+ workspace: workspace as WorkspaceProps,
+ type: emailType,
+ }),
+ log({
+ message: `*${workspace.slug}* has used ${percentage.toString()}% of its links limit for the month.`,
+ type: workspace.plan === "free" ? "cron" : "alerts",
+ mention: workspace.plan !== "free",
+ }),
+ ]);
+
+ return { skipped: false };
+ },
+ ),
+ );
+
+ notificationsSent = notificationResults.filter(
+ (result) =>
+ result.status === "fulfilled" && result.value.skipped === false,
+ ).length;
+ }
+
+ return {
+ updates,
+ errors,
+ totalProcessed,
+ notificationsSent,
+ lastProcessedId,
+ processedEntryIds,
+ };
+ },
+ {
+ count: BATCH_SIZE,
+ deleteAfterRead: true,
+ },
+ );
+
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ const {
+ updates,
+ errors,
+ totalProcessed,
+ notificationsSent,
+ lastProcessedId,
+ } = await processWorkspaceLinksUsageBatch();
+
+ if (!updates.length) {
+ return NextResponse.json({
+ success: true,
+ message: "No updates to process",
+ processed: 0,
+ });
+ }
+
+ const streamInfo = await workspaceLinksUsageStream.getStreamInfo();
+ const response = {
+ success: true,
+ processed: totalProcessed,
+ notificationsSent,
+ errors: errors?.length || 0,
+ lastProcessedId,
+ streamInfo,
+ message: `Successfully processed ${totalProcessed} workspace links usage updates`,
+ };
+
+ console.log(response);
+ return NextResponse.json(response);
+ } catch (error) {
+ console.error("Failed to process workspace links usage updates:", error);
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.ts
index 60860e415c..73a1a60e81 100644
--- a/apps/web/app/api/links/sync/route.ts
+++ b/apps/web/app/api/links/sync/route.ts
@@ -1,8 +1,8 @@
import { propagateBulkLinkChanges } from "@/lib/api/links/propagate-bulk-link-changes";
-import { updateLinksUsage } from "@/lib/api/links/update-links-usage";
import { withWorkspace } from "@/lib/auth";
import { exceededLimitError } from "@/lib/exceeded-limit-error";
import { SimpleLinkProps } from "@/lib/types";
+import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams";
import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
@@ -76,9 +76,10 @@ export const POST = withWorkspace(
tags: [],
})),
}),
- updateLinksUsage({
+ publishWorkspaceLinksUsageEvent({
workspaceId: workspace.id,
- increment: unclaimedLinks.length,
+ linksCount: unclaimedLinks.length,
+ timestamp: new Date().toISOString(),
}),
]);
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
index 18a2a313b9..9838f1b6f2 100644
--- a/apps/web/lib/api/links/bulk-create-links.ts
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -1,4 +1,5 @@
import { ProcessedLinkProps } from "@/lib/types";
+import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { getParamsFromURL, linkConstructorSimple, truncate } from "@dub/utils";
@@ -9,7 +10,6 @@ import { encodeKeyIfCaseSensitive } from "./case-sensitivity";
import { includeProgramEnrollment } from "./include-program-enrollment";
import { includeTags } from "./include-tags";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
-import { updateLinksUsage } from "./update-links-usage";
import { checkIfLinksHaveTags } from "./utils/check-if-links-have-tags";
import { checkIfLinksHaveWebhooks } from "./utils/check-if-links-have-webhooks";
import { transformLink } from "./utils/transform-link";
@@ -227,9 +227,10 @@ export async function bulkCreateLinks({
links: createdLinksData,
skipRedisCache,
}),
- updateLinksUsage({
+ publishWorkspaceLinksUsageEvent({
workspaceId: links[0].projectId!, // this will always be present
- increment: links.length,
+ linksCount: links.length,
+ timestamp: new Date().toISOString(),
}),
]),
);
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index caec292ba2..0e062bcd15 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -3,6 +3,7 @@ import { getPartnerEnrollmentInfo } from "@/lib/planetscale/get-partner-enrollme
import { isNotHostedImage, storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { ProcessedLinkProps } from "@/lib/types";
+import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams";
import { propagateWebhookTriggerChanges } from "@/lib/webhook/update-webhook";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
@@ -21,7 +22,6 @@ import { scheduleABTestCompletion } from "./ab-test-scheduler";
import { linkCache } from "./cache";
import { encodeKeyIfCaseSensitive } from "./case-sensitivity";
import { includeTags } from "./include-tags";
-import { updateLinksUsage } from "./update-links-usage";
import { transformLink } from "./utils";
export async function createLink(link: ProcessedLinkProps) {
@@ -200,9 +200,10 @@ export async function createLink(link: ProcessedLinkProps) {
// Update links usage for workspace
link.projectId &&
- updateLinksUsage({
+ publishWorkspaceLinksUsageEvent({
workspaceId: link.projectId,
- increment: 1,
+ linksCount: 1,
+ timestamp: new Date().toISOString(),
}),
// Propagate webhook trigger changes
diff --git a/apps/web/lib/api/links/update-links-usage.ts b/apps/web/lib/api/links/update-links-usage.ts
deleted file mode 100644
index 86ebefeef4..0000000000
--- a/apps/web/lib/api/links/update-links-usage.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { sendLimitEmail } from "@/lib/cron/send-limit-email";
-import { WorkspaceProps } from "@/lib/types";
-import { prisma } from "@dub/prisma";
-import { log } from "@dub/utils";
-
-export async function updateLinksUsage({
- workspaceId,
- increment,
-}: {
- workspaceId: string;
- increment: number;
-}) {
- const workspace = await prisma.project.update({
- where: {
- id: workspaceId,
- },
- data: {
- linksUsage: {
- increment,
- },
- totalLinks: {
- increment,
- },
- },
- select: {
- id: true,
- name: true,
- slug: true,
- linksUsage: true,
- linksLimit: true,
- plan: true,
- },
- });
-
- const percentage = Math.round(
- (workspace.linksUsage / workspace.linksLimit) * 100,
- );
-
- // Skip if the workspace is below 80% of the limit
- if (percentage < 80) {
- return;
- }
-
- const sentEmails = await prisma.sentEmail.findMany({
- where: {
- projectId: workspaceId,
- },
- select: {
- type: true,
- },
- });
-
- const sentNotification = sentEmails.some(
- (email) =>
- email.type ===
- (percentage >= 80 && percentage < 100
- ? "firstLinksLimitEmail"
- : "secondLinksLimitEmail"),
- );
-
- // Skip if the email has already been sent
- if (sentNotification) {
- console.log(`${workspace.slug} has already been notified, skipping...`);
- return;
- }
-
- const users = await prisma.user.findMany({
- where: {
- projects: {
- some: {
- projectId: workspaceId,
- },
- },
- },
- select: {
- email: true,
- },
- });
-
- const emails = users.map(({ email }) => email) as string[];
-
- return await Promise.allSettled([
- sendLimitEmail({
- emails,
- workspace: workspace as WorkspaceProps,
- type:
- percentage >= 80 && percentage < 100
- ? "firstLinksLimitEmail"
- : "secondLinksLimitEmail",
- }),
-
- log({
- message: `*${
- workspace.slug
- }* has used ${percentage.toString()}% of its links limit for the month.`,
- type: workspace.plan === "free" ? "cron" : "alerts",
- mention: workspace.plan !== "free",
- }),
- ]);
-}
diff --git a/apps/web/lib/middleware/utils/crawl-bitly.ts b/apps/web/lib/middleware/utils/crawl-bitly.ts
index 311fb720ec..d43ca2f624 100644
--- a/apps/web/lib/middleware/utils/crawl-bitly.ts
+++ b/apps/web/lib/middleware/utils/crawl-bitly.ts
@@ -2,6 +2,7 @@ import { createId } from "@/lib/api/create-id";
import { linkCache } from "@/lib/api/links/cache";
import { encodeKeyIfCaseSensitive } from "@/lib/api/links/case-sensitivity";
import { recordLink } from "@/lib/tinybird";
+import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams";
import { prisma } from "@dub/prisma";
import {
DUB_HEADERS,
@@ -50,14 +51,10 @@ export const crawlBitly = async (req: NextRequest, ev: NextFetchEvent) => {
.then((data) =>
Promise.allSettled([
recordLink(data),
- prisma.project.update({
- where: {
- id: BUFFER_WORKSPACE_ID,
- },
- data: {
- linksUsage: { increment: 1 },
- totalLinks: { increment: 1 },
- },
+ publishWorkspaceLinksUsageEvent({
+ workspaceId: BUFFER_WORKSPACE_ID,
+ linksCount: 1,
+ timestamp: new Date().toISOString(),
}),
]),
),
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index 7950aaabcc..5fe4099f6d 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -17,8 +17,8 @@ import { conn } from "../planetscale";
import { WorkspaceProps } from "../types";
import { redis } from "../upstash";
import {
- publishClickEvent,
publishPartnerActivityEvent,
+ publishWorkspaceClicksUsageEvent,
} from "../upstash/redis-streams";
import { webhookCache } from "../webhook/cache";
import { sendWebhooks } from "../webhook/qstash";
@@ -203,7 +203,7 @@ export async function recordClick({
// increment the usage count for the workspace
workspaceId &&
url &&
- publishClickEvent({
+ publishWorkspaceClicksUsageEvent({
linkId,
workspaceId,
timestamp: clickData.timestamp,
diff --git a/apps/web/lib/upstash/redis-streams.ts b/apps/web/lib/upstash/redis-streams.ts
index 3fbcd13724..026b427b37 100644
--- a/apps/web/lib/upstash/redis-streams.ts
+++ b/apps/web/lib/upstash/redis-streams.ts
@@ -138,27 +138,58 @@ export class RedisStream {
}
}
-/* Workspace Usage Stream */
-const WORKSPACE_USAGE_UPDATES_STREAM_KEY = "workspace:usage:updates";
-export const workspaceUsageStream = new RedisStream(
- WORKSPACE_USAGE_UPDATES_STREAM_KEY,
+/* Workspace Clicks Usage Stream */
+const WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY = "workspace:usage:updates";
+export const workspaceClicksUsageStream = new RedisStream(
+ WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY,
);
-export interface ClickEvent {
+export interface WorkspaceClicksUsageEvent {
linkId: string;
workspaceId: string;
timestamp: string;
}
// Publishes a click event to any relevant streams in a single transaction
-export const publishClickEvent = async (event: ClickEvent) => {
+export const publishWorkspaceClicksUsageEvent = async (
+ event: WorkspaceClicksUsageEvent,
+) => {
const { linkId, workspaceId, timestamp } = event;
try {
- return await redis.xadd(WORKSPACE_USAGE_UPDATES_STREAM_KEY, "*", {
+ return await redis.xadd(WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY, "*", {
linkId,
workspaceId,
timestamp,
});
} catch (error) {
- console.error("Failed to publish click update to streams:", error);
+ console.error("Failed to publish workspace clicks usage event:", error);
+ throw error;
+ }
+};
+
+/* Workspace Links Usage Stream */
+const WORKSPACE_LINKS_USAGE_UPDATES_STREAM_KEY = "workspace:linksUsage:updates";
+export const workspaceLinksUsageStream = new RedisStream(
+ WORKSPACE_LINKS_USAGE_UPDATES_STREAM_KEY,
+);
+
+export interface WorkspaceLinksUsageEvent {
+ workspaceId: string;
+ linksCount: number;
+ timestamp: string;
+}
+
+export const publishWorkspaceLinksUsageEvent = async (
+ event: WorkspaceLinksUsageEvent,
+) => {
+ const { workspaceId, linksCount, timestamp } = event;
+
+ try {
+ return await redis.xadd(WORKSPACE_LINKS_USAGE_UPDATES_STREAM_KEY, "*", {
+ workspaceId,
+ linksCount,
+ timestamp,
+ });
+ } catch (error) {
+ console.error("Failed to publish workspace links usage event:", error);
throw error;
}
};
diff --git a/apps/web/vercel.json b/apps/web/vercel.json
index 453887ac46..b07f6b7a12 100644
--- a/apps/web/vercel.json
+++ b/apps/web/vercel.json
@@ -20,6 +20,10 @@
"path": "/api/cron/streams/update-workspace-clicks",
"schedule": "* * * * *"
},
+ {
+ "path": "/api/cron/streams/update-workspace-links-usage",
+ "schedule": "* * * * *"
+ },
{
"path": "/api/cron/streams/update-partner-stats",
"schedule": "*/2 * * * *"