The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Use Redis Streams to offload link.clicks and project.usage updates
Steven Tey0a343ffc69ae
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.tsnew file mode 100644index 0000000000..fbde466084--- /dev/null+++ b/apps/web/app/(ee)/api/cron/links/click-updates-queue/route.ts@@ -0,0 +1,118 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";+import { conn } from "@/lib/planetscale";+import { clickUpdatesStream } from "@/lib/upstash/redis-streams";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++// This route is used to process aggregated click events from Redis streams+// It runs every 5 seconds to consume high-frequency click updates+export async function GET(req: Request) {+ try {+ await verifyVercelSignature(req);++ console.log("Processing click updates from Redis stream...");++ // Read and process updates from the stream+ const { updates, lastProcessedId } =+ await clickUpdatesStream.readAndProcessUpdates({+ count: 1000, // Process up to 1000 entries at once+ deleteAfterRead: true, // Clean up processed entries+ });++ if (updates.length === 0) {+ console.log("No click updates to process");+ return NextResponse.json({+ success: true,+ message: "No updates to process",+ processed: 0,+ });+ }++ console.log(`Processing ${updates.length} aggregated click updates`);++ // Process updates in parallel batches to avoid overwhelming the database+ const BATCH_SIZE = 50;+ const batches: (typeof updates)[] = [];++ for (let i = 0; i < updates.length; i += BATCH_SIZE) {+ batches.push(updates.slice(i, i + BATCH_SIZE));+ }++ let totalProcessed = 0;+ const errors: any[] = [];++ for (const batch of batches) {+ try {+ // Execute all updates in the batch in parallel+ const batchPromises = batch.map(async (update) => {+ try {+ // Update the click count for the link+ await conn.execute(+ "UPDATE Link SET clicks = clicks + ?, lastClicked = FROM_UNIXTIME(?) WHERE id = ?",+ [+ update.totalCount,+ Math.floor(update.lastTimestamp / 1000),+ update.linkId,+ ],+ );++ return {+ success: true,+ linkId: update.linkId,+ count: update.totalCount,+ };+ } catch (error) {+ console.error(`Failed to update link ${update.linkId}:`, error);+ return { success: false, linkId: update.linkId, 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 {+ errors.push(+ result.status === "fulfilled" ? result.value : result.reason,+ );+ }+ });+ } 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} click 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+ }++ // Get stream info for monitoring+ const streamInfo = await clickUpdatesStream.getStreamInfo();++ return NextResponse.json({+ success: true,+ processed: totalProcessed,+ errors: errors.length,+ lastProcessedId,+ streamInfo,+ message: `Successfully processed ${totalProcessed} click updates`,+ });+ } catch (error) {+ console.error("Failed to process click updates:", error);+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts b/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.tsnew file mode 100644index 0000000000..acb112509e--- /dev/null+++ b/apps/web/app/(ee)/api/cron/projects/usage-updates-queue/route.ts@@ -0,0 +1,120 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";+import { conn } from "@/lib/planetscale";+import { projectUsageStream } from "@/lib/upstash/redis-streams";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++// This route is used to process aggregated project usage events from Redis streams+// It runs every 5 seconds to consume high-frequency usage updates+export async function GET(req: Request) {+ try {+ await verifyVercelSignature(req);++ console.log("Processing project usage updates from Redis stream...");++ // Read and process updates from the stream+ const { updates, lastProcessedId } =+ await projectUsageStream.readAndProcessProjectUpdates({+ count: 1000, // Process up to 1000 entries at once+ deleteAfterRead: true, // Clean up processed entries+ });++ if (updates.length === 0) {+ console.log("No project usage updates to process");+ return NextResponse.json({+ success: true,+ message: "No updates to process",+ processed: 0,+ });+ }++ console.log(+ `Processing ${updates.length} aggregated project usage updates`,+ );++ // Process updates in parallel batches to avoid overwhelming the database+ const BATCH_SIZE = 50;+ const batches: (typeof updates)[] = [];++ for (let i = 0; i < updates.length; i += BATCH_SIZE) {+ batches.push(updates.slice(i, i + BATCH_SIZE));+ }++ let totalProcessed = 0;+ const errors: any[] = [];++ for (const batch of batches) {+ try {+ // Execute all updates in the batch in parallel+ const batchPromises = batch.map(async (update) => {+ try {+ // Update the project usage and click counts+ await conn.execute(+ "UPDATE Project SET usage = usage + ?, totalClicks = totalClicks + ? WHERE id = ?",+ [update.totalUsage, update.totalClicks, update.projectId],+ );++ return {+ success: true,+ projectId: update.projectId,+ usage: update.totalUsage,+ clicks: update.totalClicks,+ };+ } catch (error) {+ console.error(+ `Failed to update project ${update.projectId}:`,+ error,+ );+ return { success: false, projectId: update.projectId, 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 {+ errors.push(+ result.status === "fulfilled" ? result.value : result.reason,+ );+ }+ });+ } 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} project 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+ }++ // Get stream info for monitoring+ const streamInfo = await projectUsageStream.getStreamInfo();++ return NextResponse.json({+ success: true,+ processed: totalProcessed,+ errors: errors.length,+ lastProcessedId,+ streamInfo,+ message: `Successfully processed ${totalProcessed} project usage updates`,+ });+ } catch (error) {+ console.error("Failed to process project usage updates:", error);+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/upstash/README.md b/apps/web/lib/upstash/README.mdnew file mode 100644index 0000000000..cce70da92d--- /dev/null+++ b/apps/web/lib/upstash/README.md@@ -0,0 +1,205 @@+# Redis Streams for High-Frequency Click Tracking++This implementation uses Redis Streams to handle high-frequency link click and project usage updates efficiently. Instead of immediately updating the database for each event, we publish events to separate Redis Streams and process them in batches via dedicated cron jobs.++## Architecture++1. **High-frequency publishing**: Click and usage events are published to separate Redis Streams at 10+ times per second+2. **Dual-stream processing**: Separate cron jobs run every 5 seconds to consume and aggregate updates+3. **Database efficiency**: Aggregated updates reduce database load and improve performance+4. **Separation of concerns**: Link clicks and project usage are handled in separate streams for better modularity++## Components++### RedisStream Class (`redis-streams.ts`)++Core class that handles stream operations:++- `publishClickUpdate(event)`: Publishes click events to the stream+- `publishProjectUsageUpdate(event)`: Publishes project usage events to the stream+- `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 Instances++Two separate stream instances for different concerns:++- `clickUpdatesStream`: Handles link click events (`link-click-updates` stream)+- `projectUsageStream`: Handles project usage events (`project-usage-updates` stream)++### Cron Jobs++**Link Clicks** (`/api/cron/links/click-updates-queue/route.ts`):++- Processes aggregated click updates every 5 seconds+- Reads up to 1000 entries at once+- Aggregates clicks by linkId+- Updates Link table with click counts+- Cleans up processed entries++**Project Usage** (`/api/cron/projects/usage-updates-queue/route.ts`):++- Processes aggregated usage updates every 5 seconds+- Reads up to 1000 entries at once+- Aggregates usage and clicks by projectId+- Updates Project table with usage and totalClicks+- Cleans up processed entries++## Usage Example++### Publishing Click Updates++```typescript+import { clickUpdatesStream } from "@/lib/upstash/redis-streams";++// Publish a single click+await clickUpdatesStream.publishClickUpdate({+ linkId: "link-123",+ timestamp: Date.now(),+ count: 1,+});+```++### Publishing Project Usage Updates++```typescript+import { projectUsageStream } from "@/lib/upstash/redis-streams";++// Publish project usage update+await projectUsageStream.publishProjectUsageUpdate({+ projectId: "project-456",+ timestamp: Date.now(),+ usageCount: 1,+ clickCount: 1,+});+```++### Integration with Existing Click Recording++Instead of directly updating the database in your click recording logic:++```typescript+// Before (direct database updates)+await conn.execute(+ "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",+ [linkId],+);+await 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],+);++// After (dual-stream approach)+await clickUpdatesStream.publishClickUpdate({+ linkId,+ timestamp: Date.now(),+ count: 1,+});++await projectUsageStream.publishProjectUsageUpdate({+ projectId,+ timestamp: Date.now(),+ usageCount: 1,+ clickCount: 1,+});+```++### Monitoring Stream Health++```typescript+// Monitor click stream+const clickStreamInfo = await clickUpdatesStream.getStreamInfo();+console.log(`Click stream has ${clickStreamInfo.length} entries`);++// Monitor project usage stream+const usageStreamInfo = await projectUsageStream.getStreamInfo();+console.log(`Usage stream has ${usageStreamInfo.length} entries`);+```++## Configuration++### Cron Job Setup++Set up cron jobs to run both processing endpoints every 5 seconds:++```bash+# In your cron configuration or deployment platform++# Link clicks processing+*/5 * * * * curl -X GET https://your-domain.com/api/cron/links/click-updates-queue++# Project usage processing+*/5 * * * * curl -X GET https://your-domain.com/api/cron/projects/usage-updates-queue+```++### Environment Variables++Make sure these are set in your environment:++- `UPSTASH_REDIS_REST_URL`+- `UPSTASH_REDIS_REST_TOKEN`++## Performance Benefits++1. **Reduced Database Load**: Batch processing reduces individual database calls+2. **High Throughput**: Can handle 10+ events per second without performance degradation+3. **Fault Tolerance**: If processing fails, events remain in streams for retry+4. **Memory Management**: Automatic cleanup prevents unbounded memory growth+5. **Separation of Concerns**: Independent processing of clicks and usage allows for different scaling strategies+6. **Better Resource Utilization**: Dedicated streams prevent blocking between different types of updates++## Monitoring++Both cron jobs return detailed metrics:++**Click Updates Response:**++```json+{+ "success": true,+ "processed": 150,+ "errors": 0,+ "lastProcessedId": "1734633600000-5",+ "streamInfo": {+ "length": 0,+ "firstEntryId": null,+ "lastEntryId": null+ },+ "message": "Successfully processed 150 click updates"+}+```++**Project Usage Response:**++```json+{+ "success": true,+ "processed": 75,+ "errors": 0,+ "lastProcessedId": "1734633600000-3",+ "streamInfo": {+ "length": 0,+ "firstEntryId": null,+ "lastEntryId": null+ },+ "message": "Successfully processed 75 project usage updates"+}+```++## Error Handling++- Stream operations include comprehensive error handling+- Failed database updates are logged but don't stop processing+- Stream cleanup failures are non-fatal+- Detailed logging for debugging++## Deployment Notes++1. Make sure both cron job endpoints are secured with Vercel signature verification+2. Monitor both stream lengths to ensure they don't grow unbounded+3. Set up alerts for processing errors on both streams+4. Consider adjusting batch sizes based on your database capacity+5. Both streams can be scaled independently based on their respective load patterns+6. Consider staggering the cron jobs slightly to avoid database contention (e.g., run one at :00, :05, :10 and the other at :02, :07, :12)diff --git a/apps/web/lib/upstash/redis-streams.ts b/apps/web/lib/upstash/redis-streams.tsnew file mode 100644index 0000000000..b4cfd1e2c5--- /dev/null+++ b/apps/web/lib/upstash/redis-streams.ts@@ -0,0 +1,371 @@+import { redis } from "./redis";++export interface ClickUpdateEvent {+ linkId: string;+ timestamp: number;+ count?: number;+}++export interface ProjectUsageUpdateEvent {+ projectId: string;+ timestamp: number;+ usageCount?: number;+ clickCount?: number;+}++export interface StreamEntry {+ id: string;+ linkId: string;+ timestamp: string;+ count: string;+}++export interface ProjectStreamEntry {+ id: string;+ projectId: string;+ timestamp: string;+ usageCount: string;+ clickCount: string;+}++export interface ProcessedClickUpdate {+ linkId: string;+ totalCount: number;+ firstTimestamp: number;+ lastTimestamp: number;+}++export interface ProcessedProjectUpdate {+ projectId: string;+ totalUsage: number;+ totalClicks: number;+ firstTimestamp: number;+ lastTimestamp: number;+}++export class RedisStream {+ private streamKey: string;++ constructor(streamKey: string = "click-updates") {+ 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+ */+ async readAndProcessUpdates(+ options: {+ startId?: string;+ endId?: string;+ count?: number;+ deleteAfterRead?: boolean;+ } = {},+ ): Promise<{+ updates: ProcessedClickUpdate[];+ lastProcessedId: string | null;+ }> {+ const {+ startId = "0",+ endId = "+",+ count = 1000,+ deleteAfterRead = true,+ } = options;++ try {+ // Read entries from the stream+ const entries = await redis.xrange(this.streamKey, startId, endId, count);++ if (!entries || Object.keys(entries).length === 0) {+ return { updates: [], lastProcessedId: null };+ }++ // Aggregate clicks by linkId+ const aggregatedClicks = new Map<string, ProcessedClickUpdate>();+ let lastId: string | null = null;++ for (const [streamId, fields] of Object.entries(entries)) {+ 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);++ lastId = streamId;++ if (aggregatedClicks.has(linkId)) {+ const existing = aggregatedClicks.get(linkId)!;+ existing.totalCount += count;+ existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);+ existing.firstTimestamp = Math.min(+ existing.firstTimestamp,+ timestamp,+ );+ } else {+ aggregatedClicks.set(linkId, {+ linkId,+ totalCount: count,+ firstTimestamp: timestamp,+ lastTimestamp: timestamp,+ });+ }+ }++ // Optionally delete processed entries to prevent memory buildup+ 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++) {+ try {+ await redis.xdel(this.streamKey, entryIds[i]);+ } catch (delError) {+ // Continue if individual delete fails+ }+ }+ }+ } catch (error) {+ console.warn("Failed to clean up stream entries:", error);+ // Don't throw - this is not critical+ }+ }++ return {+ updates: Array.from(aggregatedClicks.values()),+ lastProcessedId: lastId,+ };+ } catch (error) {+ console.error("Failed to read updates from stream:", error);+ throw error;+ }+ }++ /**+ * Read and process project usage updates from the stream+ * This method aggregates usage and clicks by projectId and returns the total counts+ */+ async readAndProcessProjectUpdates(+ options: {+ startId?: string;+ endId?: string;+ count?: number;+ deleteAfterRead?: boolean;+ } = {},+ ): Promise<{+ updates: ProcessedProjectUpdate[];+ lastProcessedId: string | null;+ }> {+ const {+ startId = "0",+ endId = "+",+ count = 1000,+ deleteAfterRead = true,+ } = options;++ try {+ // Read entries from the stream+ const entries = await redis.xrange(this.streamKey, startId, endId, count);++ if (!entries || Object.keys(entries).length === 0) {+ return { updates: [], lastProcessedId: null };+ }++ // Aggregate usage by projectId+ const aggregatedUsage = new Map<string, ProcessedProjectUpdate>();+ let lastId: string | null = null;++ for (const [streamId, fields] of Object.entries(entries)) {+ const entry = fields as unknown as {+ projectId: string;+ timestamp: string;+ usageCount: string;+ clickCount: string;+ };+ const projectId = entry.projectId;+ const timestamp = parseInt(entry.timestamp);+ const usageCount = parseInt(entry.usageCount);+ const clickCount = parseInt(entry.clickCount);++ lastId = streamId;++ if (aggregatedUsage.has(projectId)) {+ const existing = aggregatedUsage.get(projectId)!;+ existing.totalUsage += usageCount;+ existing.totalClicks += clickCount;+ existing.lastTimestamp = Math.max(existing.lastTimestamp, timestamp);+ existing.firstTimestamp = Math.min(+ existing.firstTimestamp,+ timestamp,+ );+ } else {+ aggregatedUsage.set(projectId, {+ projectId,+ totalUsage: usageCount,+ totalClicks: clickCount,+ firstTimestamp: timestamp,+ lastTimestamp: timestamp,+ });+ }+ }++ // Optionally delete processed entries to prevent memory buildup+ 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++) {+ try {+ await redis.xdel(this.streamKey, entryIds[i]);+ } catch (delError) {+ // Continue if individual delete fails+ }+ }+ }+ } catch (error) {+ console.warn("Failed to clean up stream entries:", error);+ // Don't throw - this is not critical+ }+ }++ return {+ updates: Array.from(aggregatedUsage.values()),+ lastProcessedId: lastId,+ };+ } catch (error) {+ console.error("Failed to read project usage updates from stream:", error);+ throw error;+ }+ }++ /**+ * Get stream information (length, first/last entry, etc.)+ */+ async getStreamInfo(): Promise<{+ length: number;+ firstEntryId: string | null;+ lastEntryId: string | null;+ }> {+ try {+ // Get stream length - check if stream exists first+ let length = 0;+ let firstEntryId: string | null = null;+ let lastEntryId: string | null = null;++ try {+ // Try to get first entry to check if stream exists+ const firstEntry = await redis.xrange(this.streamKey, "-", "+", 1);++ if (firstEntry && Object.keys(firstEntry).length > 0) {+ firstEntryId = Object.keys(firstEntry)[0];++ // If stream exists, get its length and last entry+ const entries = await redis.xrange(this.streamKey, "-", "+");+ length = Object.keys(entries || {}).length;++ if (length > 0) {+ const lastEntry = await redis.xrange(this.streamKey, "+", "+", 1);+ if (lastEntry && Object.keys(lastEntry).length > 0) {+ lastEntryId = Object.keys(lastEntry)[0];+ }+ }+ }+ } catch (streamError) {+ // Stream might not exist yet, which is fine+ console.log("Stream does not exist or is empty:", streamError);+ }++ return {+ length,+ firstEntryId,+ lastEntryId,+ };+ } catch (error) {+ console.error("Failed to get stream info:", error);+ 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");