#4571·dub

Deferred deep linking: /track/open IP fallback can return the wrong link and never consumes clicks

Author: canbalCreated Sep 25, 2026Updated Sep 25, 2026

When /track/open is called with only dubDomain (the iOS path where the user skips copying, or denies the paste prompt), it falls back to matching cached clicks by IP. That fallback can return the wrong link, and it can attribute installs that never came from a link at all.

Clicks are cached one key per link, with a 1-hour TTL (cache-deeplink-click-data.ts#L29-L37):

typescript
redis.set(`deepLinkClickCache:${ip}:${link.domain}:${link.key}`, { clickId, link }, { ex: 60 * 60 })

/track/open then scans one page and returns whichever key comes back first (route.ts#L44-L53):

typescript
const [_, cacheKeysForDomain] = await redis.scan(0, { match: `deepLinkClickCache:${ip}:${dubDomain}:*`, count: 10 });
const cachedData = await redis.get(cacheKeysForDomain[0]);

This causes four problems:

  • The wrong link wins. When several links were clicked from one IP within the hour, the result follows SCAN order, not click time.
  • Clicks are never consumed. The matched key isn't deleted, so every install from that IP for the rest of the hour gets the same attribution.
  • Clicks can be missed. Only the first SCAN cursor is read, so a matching key can be skipped once enough keys exist.
  • Claimed clicks stay in the pool. When the app sends the copied deepLink, that click's IP entry isn't removed, so the next install on the same IP can still receive it through the fallback.

Steps to reproduce

This uses a custom domain with deep links configured and two links (A and B), each with ios set to an App Store URL. Everything happens on one iOS device and network.

  1. Open link A in Safari; the Deep View page shows.
  2. Open link B in Safari; the Deep View page shows.
  3. Install the app fresh and call /track/open with { dubDomain } only. It returns link A, although B was clicked last.
  4. Delete the app, reinstall it without tapping any link, and call /track/open again. It returns link A again.

This matters most on shared IPs (carrier NAT, schools, offices). There, one person's click gets credited to another person's organic install. For apps that use deep links for referrals or invites, that means a wrong referral credit.

Possible fix

  1. Record each click in a per-IP sorted set, deepLinkClickIndex:{ip}:{domain}, scored by click time, next to the existing key.
  2. In /track/open, drop entries older than the TTL, take the newest one, and claim it with ZREM plus GETDEL. This also replaces SCAN.
  3. On the deterministic deepLink path, remove that click from the IP pool.

A patch against 77b50d9 is below. It's about 80 lines across cache-deeplink-click-data.ts and track/open/route.ts, and it applies cleanly with git apply. Caveat: I haven't run it. I wrote it without a working local Dub stack, so it hasn't been typechecked or run against tests/tracks/track-open.test.ts, which also doesn't cover the IP fallback today. Treat it as a sketch of the approach. I'm happy to turn it into a proper PR with a test if you'd like.

Patch
diff
diff --git a/apps/web/app/(ee)/api/track/open/route.ts b/apps/web/app/(ee)/api/track/open/route.ts
index daaeddc..9cca37f 100644
--- a/apps/web/app/(ee)/api/track/open/route.ts
+++ b/apps/web/app/(ee)/api/track/open/route.ts
@@ -5,7 +5,12 @@ import { linkCache } from "@/lib/api/links/cache";
 import { recordClickCache } from "@/lib/api/links/record-click-cache";
 import { parseRequestBody } from "@/lib/api/utils";
 import { withAxiom } from "@/lib/axiom/server";
-import { DeepLinkClickData } from "@/lib/middleware/utils/cache-deeplink-click-data";
+import {
+  DEEP_LINK_CLICK_TTL,
+  DeepLinkClickData,
+  deepLinkClickCacheKey,
+  deepLinkClickIndexKey,
+} from "@/lib/middleware/utils/cache-deeplink-click-data";
 import { getIdentityHash } from "@/lib/middleware/utils/get-identity-hash";
 import { getLinkViaEdge } from "@/lib/planetscale";
 import { recordClick } from "@/lib/tinybird";
@@ -41,16 +46,24 @@ export const POST = withAxiom(async (req) => {
         // if ip address is present, check if there's a cached click
         console.log(`Checking cache for ${ip}:${dubDomain}:*`);
 
-        // Get all iOS click cache keys for this IP address
-        const [_, cacheKeysForDomain] = await redis.scan(0, {
-          match: `deepLinkClickCache:${ip}:${dubDomain}:*`,
-          count: 10,
+        const indexKey = deepLinkClickIndexKey({ ip, domain: dubDomain });
+
+        // Drop entries older than the click TTL, then take the most recent click
+        await redis.zremrangebyscore(
+          indexKey,
+          0,
+          Date.now() - DEEP_LINK_CLICK_TTL * 1000,
+        );
+        const [latestCacheKey] = await redis.zrange<string[]>(indexKey, 0, 0, {
+          rev: true,
         });
 
-        if (cacheKeysForDomain.length > 0) {
-          const cachedData = await redis.get<DeepLinkClickData>(
-            cacheKeysForDomain[0],
-          );
+        if (latestCacheKey) {
+          // Claim the click so later installs from the same IP don't inherit it
+          const [, cachedData] = await Promise.all([
+            redis.zrem(indexKey, latestCacheKey),
+            redis.getdel<DeepLinkClickData>(latestCacheKey),
+          ]);
 
           if (cachedData) {
             return NextResponse.json(
@@ -124,6 +137,18 @@ export const POST = withAxiom(async (req) => {
       url: cachedLink.url,
     };
 
+    // This click was matched deterministically, so remove it from the IP
+    // fallback pool; otherwise the next install on this IP would inherit it
+    if (ip) {
+      const cacheKey = deepLinkClickCacheKey({ ip, domain, key });
+      waitUntil(
+        Promise.all([
+          redis.del(cacheKey),
+          redis.zrem(deepLinkClickIndexKey({ ip, domain }), cacheKey),
+        ]),
+      );
+    }
+
     // if there's no cached clickId, track the click event
     if (!cachedClickId) {
       const clickData = await recordClick({
diff --git a/apps/web/lib/middleware/utils/cache-deeplink-click-data.ts b/apps/web/lib/middleware/utils/cache-deeplink-click-data.ts
index 6f3830a..265bac4 100644
--- a/apps/web/lib/middleware/utils/cache-deeplink-click-data.ts
+++ b/apps/web/lib/middleware/utils/cache-deeplink-click-data.ts
@@ -26,14 +26,41 @@ export async function cacheDeepLinkClickData({
     return;
   }
 
-  return await redis.set<DeepLinkClickData>(
-    `deepLinkClickCache:${ip}:${link.domain}:${link.key}`,
-    {
-      clickId,
-      link,
-    },
-    {
-      ex: 60 * 60,
-    },
+  const cacheKey = deepLinkClickCacheKey({
+    ip,
+    domain: link.domain,
+    key: link.key,
+  });
+  const indexKey = deepLinkClickIndexKey({ ip, domain: link.domain });
+
+  // Index this IP's clicks by time so /track/open can return the most recent one
+  const pipeline = redis.pipeline();
+  pipeline.set<DeepLinkClickData>(
+    cacheKey,
+    { clickId, link },
+    { ex: DEEP_LINK_CLICK_TTL },
   );
+  pipeline.zadd(indexKey, { score: Date.now(), member: cacheKey });
+  pipeline.expire(indexKey, DEEP_LINK_CLICK_TTL);
+  return await pipeline.exec();
 }
+
+export const DEEP_LINK_CLICK_TTL = 60 * 60;
+
+export const deepLinkClickCacheKey = ({
+  ip,
+  domain,
+  key,
+}: {
+  ip: string;
+  domain: string;
+  key: string;
+}) => `deepLinkClickCache:${ip}:${domain}:${key}`;
+
+export const deepLinkClickIndexKey = ({
+  ip,
+  domain,
+}: {
+  ip: string;
+  domain: string;
+}) => `deepLinkClickIndex:${ip}:${domain}`;