The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Publish link clicks to both streams and delete used stream events
Ian MacCallum76f6c70d0c18
diff --git a/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts b/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.tsindex fbde466084..d74482e993 100644--- a/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts+++ b/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts@@ -44,6 +44,7 @@ export async function GET(req: Request) {const errors: any[] = [];for (const batch of batches) {+ console.log("Processing batch:", JSON.stringify(batch, null, 2));try {// Execute all updates in the batch in parallelconst batchPromises = batch.map(async (update) => {diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex db1c34c990..b6a6941b44 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -19,6 +19,7 @@ import {import { conn } from "../planetscale";import { WorkspaceProps } from "../types";import { redis } from "../upstash";+import { publishLinkClick } from "../upstash/redis-streams";import { webhookCache } from "../webhook/cache";import { sendWebhooks } from "../webhook/qstash";import { transformClickEventData } from "../webhook/transform";@@ -181,19 +182,8 @@ export async function recordClick({// cache the recorded click for the corresponding IP address in Redis for 1 hourrecordClickCache.set({ domain, key, ip, clickId }),- // increment the click count for the link (based on their ID)- // we have to use planetscale connection directly (not prismaEdge) because of connection pooling- conn.execute(- "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",- [linkId],- ),- // if the link has a destination URL, increment the usage count for the workspace- // and then we have a cron that will reset it at the start of new billing cycle- url &&- conn.execute(- "UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1, p.totalClicks = p.totalClicks + 1 WHERE l.id = ?",- [linkId],- ),+ // Publish the click event to the click events stream+ publishLinkClick({ linkId, timestamp: clickData.timestamp, url }),]);// Find the rejected promises and log themdiff --git a/apps/web/lib/upstash/README.md b/apps/web/lib/upstash/README.mdindex cce70da92d..54075f210a 100644--- a/apps/web/lib/upstash/README.md+++ b/apps/web/lib/upstash/README.md@@ -20,7 +20,6 @@ Core class that handles stream operations:- `readAndProcessUpdates(options)`: Reads and aggregates click data from the stream- `readAndProcessProjectUpdates(options)`: Reads and aggregates project usage data from the stream- `getStreamInfo()`: Gets stream metadata for monitoring-- `clearStream()`: Emergency cleanup (use with caution)### Stream Instancesdiff --git a/apps/web/lib/upstash/redis-streams.ts b/apps/web/lib/upstash/redis-streams.tsindex b4cfd1e2c5..9e3106be6d 100644--- a/apps/web/lib/upstash/redis-streams.ts+++ b/apps/web/lib/upstash/redis-streams.ts@@ -1,31 +1,25 @@import { redis } from "./redis";-export interface ClickUpdateEvent {- linkId: string;- timestamp: number;- count?: number;-}+// Stream key constants+export const LINK_CLICK_UPDATES_STREAM_KEY = "link:click:updates";+export const PROJECT_USAGE_UPDATES_STREAM_KEY = "project:usage:updates";-export interface ProjectUsageUpdateEvent {- projectId: string;- timestamp: number;- usageCount?: number;- clickCount?: number;+export interface ClickEvent {+ linkId: string;+ timestamp: string;+ url?: string;}export interface StreamEntry {id: string;linkId: string;timestamp: string;- count: string;}export interface ProjectStreamEntry {id: string;- projectId: string;+ linkId: string;timestamp: string;- usageCount: string;- clickCount: string;}export interface ProcessedClickUpdate {@@ -46,53 +40,10 @@ export interface ProcessedProjectUpdate {export class RedisStream {private streamKey: string;- constructor(streamKey: string = "click-updates") {+ constructor(streamKey: string) {this.streamKey = streamKey;}- /**- * Publish a click update event to the stream- * This method is optimized for high-frequency writes (10+ times per second)- */- async publishClickUpdate(event: ClickUpdateEvent): Promise<string> {- try {- // Use "*" to auto-generate stream ID for optimal performance- const streamId = await redis.xadd(this.streamKey, "*", {- linkId: event.linkId,- timestamp: event.timestamp.toString(),- count: (event.count || 1).toString(),- });-- return streamId;- } catch (error) {- console.error("Failed to publish click update to stream:", error);- throw error;- }- }-- /**- * Publish a project usage update event to the stream- * This method is optimized for high-frequency writes (10+ times per second)- */- async publishProjectUsageUpdate(- event: ProjectUsageUpdateEvent,- ): Promise<string> {- try {- // Use "*" to auto-generate stream ID for optimal performance- const streamId = await redis.xadd(this.streamKey, "*", {- projectId: event.projectId,- timestamp: event.timestamp.toString(),- usageCount: (event.usageCount || 0).toString(),- clickCount: (event.clickCount || 0).toString(),- });-- return streamId;- } catch (error) {- console.error("Failed to publish project usage update to stream:", error);- throw error;- }- }-/*** Read and process click updates from the stream* This method aggregates clicks by linkId and returns the total counts@@ -131,11 +82,10 @@ export class RedisStream {const entry = fields as unknown as {linkId: string;timestamp: string;- count: string;};const linkId = entry.linkId;- const timestamp = parseInt(entry.timestamp);- const count = parseInt(entry.count);+ const timestamp = Date.parse(entry.timestamp) / 1000;+ const count = 1;lastId = streamId;@@ -158,29 +108,52 @@ export class RedisStream {}// Optionally delete processed entries to prevent memory buildup+ // xackdel is not a standard Redis command, but if you are referring to a custom helper or a pattern+ // that acknowledges and deletes entries in a consumer group (as with xack + xdel), you could use it+ // if you are using consumer groups. However, this code is not using consumer groups, so xdel is correct.+ // If you want to use xackdel, you must be using XREADGROUP and have a consumer group context.+ // For now, keep xdel, but add a note:+if (deleteAfterRead && lastId) {try {- // Remove entries up to the last processed ID- // We'll implement this by deleting all entries older than the last processed one- // For now, we'll keep a maximum number of entries to prevent unbounded growth- const allEntries = await redis.xrange(this.streamKey, "-", "+");- const totalEntries = Object.keys(allEntries || {}).length;-- // Keep only the last 1000 entries if we have more than 2000- if (totalEntries > 2000) {- const entryIds = Object.keys(allEntries);- const keepFromIndex = totalEntries - 1000;- const minIdToKeep = entryIds[keepFromIndex];-- // Delete entries older than minIdToKeep (this is a workaround for xtrim)- for (let i = 0; i < keepFromIndex; i++) {+ // NOTE: If using Redis Streams with consumer groups, you should use XACK to acknowledge+ // entries for a group/consumer, and optionally XDEL to delete. Here, we are not using consumer groups,+ // so we just delete processed entries directly.+ // If you migrate to consumer groups, replace this with xack + xdel as appropriate.++ // Remove all processed entries up to and including lastId+ // Get all entry IDs up to lastId+ const processedEntries = await redis.xrange(+ this.streamKey,+ "-",+ lastId,+ );+ const processedEntryIds = Object.keys(processedEntries || {});+ if (processedEntryIds.length > 0) {+ // xdel supports deleting multiple IDs at once, but Upstash limits batch size, so chunk if needed+ const BATCH_SIZE = 100;+ for (let i = 0; i < processedEntryIds.length; i += BATCH_SIZE) {+ const batch = processedEntryIds.slice(i, i + BATCH_SIZE);try {- await redis.xdel(this.streamKey, entryIds[i]);+ await redis.xdel(this.streamKey, batch);} catch (delError) {- // Continue if individual delete fails+ // Continue if individual batch delete fails}}}++ // Additionally, trim the stream to prevent unbounded growth+ // Keep only the last 2000 entries (soft limit)+ try {+ // Upstash/Redis xtrim expects an options object, not just a number+ await redis.xtrim(this.streamKey, {+ strategy: "MAXLEN",+ threshold: 2000,+ exactness: "~",+ });+ } catch (trimError) {+ // Not critical if trim fails+ }} catch (error) {console.warn("Failed to clean up stream entries:", error);// Don't throw - this is not critical@@ -239,7 +212,7 @@ export class RedisStream {clickCount: string;};const projectId = entry.projectId;- const timestamp = parseInt(entry.timestamp);+ const timestamp = Date.parse(entry.timestamp) / 1000;const usageCount = parseInt(entry.usageCount);const clickCount = parseInt(entry.clickCount);@@ -331,15 +304,29 @@ export class RedisStream {length = Object.keys(entries || {}).length;if (length > 0) {- const lastEntry = await redis.xrange(this.streamKey, "+", "+", 1);+ // Use "$" to get the last entry instead of "+"+ const lastEntry = await redis.xrevrange(+ this.streamKey,+ "+",+ "-",+ 1,+ );+if (lastEntry && Object.keys(lastEntry).length > 0) {- lastEntryId = Object.keys(lastEntry)[0];+ const entryId = Object.keys(lastEntry)[0];++ if (entryId !== firstEntryId) {+ lastEntryId = entryId;+ }}}}} catch (streamError) {// Stream might not exist yet, which is fineconsole.log("Stream does not exist or is empty:", streamError);+ console.log(streamError.message);+ console.log(streamError.type);+ console.log(JSON.stringify(streamError, null, 2));}return {@@ -352,20 +339,32 @@ export class RedisStream {throw error;}}-- /**- * Clear all entries from the stream (use with caution!)- */- async clearStream(): Promise<void> {- try {- await redis.del(this.streamKey);- } catch (error) {- console.error("Failed to clear stream:", error);- throw error;- }- }}// Export instances for both click and project usage updates-export const clickUpdatesStream = new RedisStream("link-click-updates");-export const projectUsageStream = new RedisStream("project-usage-updates");+export const clickUpdatesStream = new RedisStream(+ LINK_CLICK_UPDATES_STREAM_KEY,+);+export const projectUsageStream = new RedisStream(+ PROJECT_USAGE_UPDATES_STREAM_KEY,+);++export const publishLinkClick = async (event: ClickEvent) => {+ const { linkId, timestamp, url } = event;+ const entry = { linkId, timestamp };++ try {+ const pipeline = redis.pipeline();++ pipeline.xadd(LINK_CLICK_UPDATES_STREAM_KEY, "*", entry);++ if (url) {+ pipeline.xadd(PROJECT_USAGE_UPDATES_STREAM_KEY, "*", entry);+ }++ return await pipeline.exec();+ } catch (error) {+ console.error("Failed to publish click update to streams:", error);+ throw error;+ }+};