The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
remove lock key + old stream cron
Steven Tey06437b8b7833
diff --git a/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts b/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.tsindex 1beb4e7255..46d681c434 100644--- a/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts+++ b/apps/web/app/(ee)/api/cron/streams/update-click-stats/route.ts@@ -334,6 +334,8 @@ export const GET = withCron(async () => {const streamInfo = await linkClickEventStream.getStreamInfo();await maybeAlertOnBacklog(streamInfo);+ await redis.del(LOCK_KEY);+if (!linkUpdates.length) {return logAndRespond({success: true,@@ -343,8 +345,6 @@ export const GET = withCron(async () => {});}- await redis.del(LOCK_KEY);-return logAndRespond({success: true,processed: totalProcessed,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.tsdeleted file mode 100644index e3f676c9d7..0000000000--- a/apps/web/app/(ee)/api/cron/streams/update-workspace-clicks/route.ts+++ /dev/null@@ -1,208 +0,0 @@-import { withCron } from "@/lib/cron/with-cron";-import { conn } from "@/lib/planetscale";-import { RedisStreamEntry } from "@/lib/upstash/redis-streams/client";-import {- WorkspaceClicksUsageEvent,- workspaceClicksUsageStream,-} from "@/lib/upstash/redis-streams/workspace-clicks-usage";-import { NextResponse } from "next/server";--// TODO: Remove once stream is drained-export const dynamic = "force-dynamic";--const BATCH_SIZE = 10000;--type WorkspaceAggregateUsage = {- workspaceId: string;- clicks: number;- firstTimestamp: number;- lastTimestamp: number;- entryIds: string[];-};--const aggregateWorkspaceUsage = (- entries: RedisStreamEntry<WorkspaceClicksUsageEvent>[],-): { updates: WorkspaceAggregateUsage[]; lastProcessedId: string | null } => {- // Aggregate usage by workspaceId- const aggregatedUsage = new Map<string, WorkspaceAggregateUsage>();-- let lastId: string | null = null;-- console.log(`Aggregating ${entries.length} workspace usage events`);-- // The entries are a batch of workspace usage events, each with workspaceId, timestamp, and linkId.- // We want to aggregate by workspaceId, counting total events (clicks) and tracking first/last timestamps.-- for (const entry of entries) {- const workspaceId = entry.data.workspaceId;-- if (!workspaceId) {- continue;- }-- const timestamp = Date.parse(entry.data.timestamp) / 1000;-- lastId = entry.id;-- if (aggregatedUsage.has(workspaceId)) {- const existing = aggregatedUsage.get(workspaceId)!;- existing.clicks += 1;- existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);- existing.firstTimestamp = Math.min(existing.firstTimestamp, timestamp);- existing.entryIds.push(entry.id);- } else {- aggregatedUsage.set(workspaceId, {- workspaceId,- clicks: 1,- firstTimestamp: timestamp,- lastTimestamp: timestamp,- entryIds: [entry.id],- });- }- }-- return {- updates: Array.from(aggregatedUsage.values()),- lastProcessedId: lastId,- };-};--const processWorkspaceUpdateStreamBatch = () =>- workspaceClicksUsageStream.processBatch<WorkspaceClicksUsageEvent>(- async (entries) => {- if (!entries || Object.keys(entries).length === 0) {- return {- success: true,- updates: [],- processedEntryIds: [],- };- }-- const { updates, lastProcessedId } = aggregateWorkspaceUsage(entries);-- if (updates.length === 0) {- console.log("No workspace usage updates to process");- return { success: true, updates: [], processedEntryIds: [] };- }-- console.log(- `Processing ${updates.length} aggregated workspace usage updates...`,- );-- // Process updates in parallel batches to avoid overwhelming the database- const SUB_BATCH_SIZE = 50;- const batches: (typeof updates)[] = [];-- for (let i = 0; i < updates.length; i += SUB_BATCH_SIZE) {- batches.push(updates.slice(i, i + SUB_BATCH_SIZE));- }-- let totalProcessed = 0;- const errors: { workspaceId: string; error: any }[] = [];- const processedEntryIds: string[] = [];-- for (const batch of batches) {- try {- // Execute all updates in the batch in parallel- const batchPromises = batch.map(async (update) => {- try {- // Update the workspace usage and click counts- await conn.execute(- "UPDATE Project p SET p.usage = p.usage + ?, p.totalClicks = p.totalClicks + ? WHERE id = ?",- [update.clicks, update.clicks, update.workspaceId],- );-- processedEntryIds.push(...update.entryIds);-- return {- ...update,- success: true,- };- } catch (error) {- console.error(- `Failed to update workspace ${update.workspaceId}:`,- error,- );- return {- success: false,- error: { workspaceId: update.workspaceId, error },- };- }- });-- const batchResults = await Promise.allSettled(batchPromises);-- // Count successful updates and collect errors- batchResults.forEach((result) => {- if (result.status === "fulfilled" && result.value.success) {- totalProcessed++;- } else if (- result.status === "fulfilled" &&- !result.value.success &&- result.value.error- ) {- errors.push(result.value.error);- }- });- } catch (error) {- console.error("Failed to process batch:", error);- errors.push(error);- }- }-- // Log results- const successRate = (totalProcessed / updates.length) * 100;- console.log(- `Processed ${totalProcessed}/${updates.length} workspace usage updates (${successRate.toFixed(1)}% success rate)`,- );-- if (errors.length > 0) {- console.error(- `Encountered ${errors.length} errors while processing:`,- errors.slice(0, 5),- ); // Log first 5 errors- }-- return {- updates,- errors,- totalProcessed,- lastProcessedId,- processedEntryIds,- };- },- {- count: BATCH_SIZE,- deleteAfterRead: true,- },- );--// This route is used to process aggregated workspace usage events from Redis streams-// It runs every minute with a batch size of 10,000 to consume high-frequency usage updates-export const GET = withCron(async () => {- const { updates, errors, totalProcessed, lastProcessedId } =- await processWorkspaceUpdateStreamBatch();-- if (!updates.length) {- return NextResponse.json({- success: true,- message: "No updates to process",- processed: 0,- });- }-- const streamInfo = await workspaceClicksUsageStream.getStreamInfo();-- const response = {- success: true,- processed: totalProcessed,- errors: errors?.length || 0,- lastProcessedId,- streamInfo,- message: `Successfully processed ${totalProcessed} workspace usage updates`,- };-- console.log(response);-- return NextResponse.json(response);-});diff --git a/apps/web/lib/upstash/redis-streams/workspace-clicks-usage.ts b/apps/web/lib/upstash/redis-streams/workspace-clicks-usage.tsdeleted file mode 100644index 005bf41827..0000000000--- a/apps/web/lib/upstash/redis-streams/workspace-clicks-usage.ts+++ /dev/null@@ -1,31 +0,0 @@-import { redis } from "../redis";-import { RedisStream } from "./client";--// TODO: Remove once stream is drained-const WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY = "workspace:usage:updates";--export const workspaceClicksUsageStream = new RedisStream(- WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY,-);--export interface WorkspaceClicksUsageEvent {- linkId: string;- workspaceId: string;- timestamp: string;-}-// Publishes a click event to any relevant streams in a single transaction-export const publishWorkspaceClicksUsageEvent = async (- event: WorkspaceClicksUsageEvent,-) => {- const { linkId, workspaceId, timestamp } = event;- try {- return await redis.xadd(WORKSPACE_CLICKS_USAGE_UPDATES_STREAM_KEY, "*", {- linkId,- workspaceId,- timestamp,- });- } catch (error) {- console.error("Failed to publish workspace clicks usage event:", error);- throw error;- }-};diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex 8e7130cda4..8c45a4a896 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -20,10 +20,6 @@"path": "/api/cron/streams/send-link-clicked-webhooks","schedule": "* * * * *"},- {- "path": "/api/cron/streams/update-workspace-clicks",- "schedule": "* * * * *"- },{"path": "/api/cron/streams/update-click-stats","schedule": "* * * * *"