Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): negative caching for index URL->id lookups (v2) (#3775)
Gergő Móricz63aac03d1a1c
diff --git a/apps/api/src/__tests__/snips/index-cache.test.ts b/apps/api/src/__tests__/snips/index-cache.test.tsindex 12e0496e8..e1bb881eb 100644--- a/apps/api/src/__tests__/snips/index-cache.test.ts+++ b/apps/api/src/__tests__/snips/index-cache.test.ts@@ -4,6 +4,9 @@ import {filterIndexEntries,getCachedIndexEntries,getCachedMaxAge,+ getCachedNegative,+ isNegativeStillValid,+ setCachedNegative,upsertCachedIndexEntries,type IndexCacheEntry,} from "../../services/index-cache";@@ -187,6 +190,36 @@ describe("filterIndexEntries", () => {});});+describe("isNegativeStillValid", () => {+ // A marker written at Tq with maxAge Mq stores emptyFrom = Tq - Mq, the left+ // edge of the confirmed-empty window. A later request is still-empty iff its+ // own left edge (now - maxAge) is no earlier than emptyFrom.+ const Tq = 1_000_000_000_000;+ const Mq = 2 * 24 * 60 * 60 * 1000; // 2 days+ const emptyFrom = Tq - Mq;++ it("stays valid as time passes with the same maxAge window", () => {+ // 1 hour later, same 2-day window: left edge moved forward, still >= emptyFrom.+ expect(isNegativeStillValid(emptyFrom, Mq, Tq + 60 * 60 * 1000)).toBe(true);+ });++ it("stays valid for a smaller (more recent) window", () => {+ expect(isNegativeStillValid(emptyFrom, 60 * 60 * 1000, Tq)).toBe(true);+ });++ it("is invalid for a larger window that looks further back than confirmed", () => {+ // 14-day window now reaches earlier than the 2-day confirmed-empty left edge.+ expect(+ isNegativeStillValid(emptyFrom, 14 * 24 * 60 * 60 * 1000, Tq),+ ).toBe(false);+ });++ it("is exactly valid at the boundary", () => {+ // now - maxAge == emptyFrom+ expect(isNegativeStillValid(emptyFrom, Mq, Tq)).toBe(true);+ });+});+describe("index cache fail-open", () => {// Points at a port nothing listens on: every operation must resolve (not// throw, not hang) so the read path can fall back to Postgres.@@ -227,4 +260,16 @@ describe("index cache fail-open", () => {getCachedMaxAge(urlHash, undefined, deadClient),).resolves.toBeNull();}, 5000);++ it("getCachedNegative resolves to null (disabled or dead) and never throws", async () => {+ await expect(+ getCachedNegative("idxc:test", undefined, deadClient),+ ).resolves.toBeNull();+ }, 5000);++ it("setCachedNegative resolves without throwing", async () => {+ await expect(+ setCachedNegative("idxc:test", Date.now(), undefined, deadClient),+ ).resolves.toBeUndefined();+ }, 5000);});diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex c3e1872c0..fa52802ad 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -85,6 +85,11 @@ const configSchema = z.object({DATABASE_REPLICA_URL: z.string().optional(),INDEX_DATABASE_URL: z.string().optional(),INDEX_CACHE_REDIS_URL: z.string().optional(),+ // Negative (miss) caching TTL for index URL->id lookups, in ms. 0 disables+ // it; the cache then only shields lookups that find data. A positive value+ // (e.g. 600000 = 10min) also short-circuits repeat lookups for URLs with no+ // index entry. Kept short so any missed cache-clear self-heals quickly.+ INDEX_CACHE_NEGATIVE_TTL_MS: z.coerce.number().default(0),REDIS_URL: z.string().optional(),REDIS_EVICT_URL: z.string().optional(),REDIS_RATE_LIMIT_URL: z.string().optional(),diff --git a/apps/api/src/scraper/scrapeURL/engines/index/index.ts b/apps/api/src/scraper/scrapeURL/engines/index/index.tsindex eb499ed67..0f607d1f5 100644--- a/apps/api/src/scraper/scrapeURL/engines/index/index.ts+++ b/apps/api/src/scraper/scrapeURL/engines/index/index.ts@@ -20,9 +20,13 @@ import {filterIndexEntries,getCachedIndexEntries,getCachedMaxAge,+ getCachedNegative,+ isNegativeStillValid,setCachedMaxAge,+ setCachedNegative,upsertCachedIndexEntries,useIndexCache,+ useIndexNegativeCache,type IndexCacheEntry,} from "../../../../services/index-cache";import { indexLookupCounter } from "../../../../lib/index-cache-metrics";@@ -314,6 +318,7 @@ export async function scrapeURLWithIndex(let cacheStatus: "hit" | "filtered" | "miss" | "error" | "disabled" ="disabled";let servedFromCache = false;+ let negativeHit = false;let timingsCache = 0;let timingsDb = 0;@@ -325,8 +330,9 @@ export async function scrapeURLWithIndex(dbResult: "hit" | "miss" | "error",extra: Record<string, unknown> = {},) => {- const outcome =- cacheStatus === "hit"+ const outcome = negativeHit+ ? "cache_neg_hit"+ : cacheStatus === "hit"? "cache_hit": cacheStatus === "disabled"? `db_only_${dbResult}`@@ -384,7 +390,26 @@ export async function scrapeURLWithIndex(}}- if (!servedFromCache) {+ // Negative cache: on a clean positive miss (key absent), a still-valid+ // negative marker proves there's no index entry for this window, so we can+ // skip Postgres. Not consulted on "filtered"/"error" (entries exist, or the+ // cache is unhealthy and we must fall back to the DB), nor for minAge+ // requests (different no-data semantics — NoCachedDataError, no waterfall).+ if (+ !servedFromCache &&+ useIndexNegativeCache &&+ cacheStatus === "miss" &&+ meta.options.minAge === undefined+ ) {+ const negStart = Date.now();+ const neg = await getCachedNegative(variantKey, meta.logger);+ timingsCache += Date.now() - negStart;+ if (neg !== null && isNegativeStillValid(neg.emptyFrom, maxAge, Date.now())) {+ negativeHit = true;+ }+ }++ if (!servedFromCache && !negativeHit) {const dbStart = Date.now();try {const rows = await indexGetRecent5({@@ -418,6 +443,15 @@ export async function scrapeURLWithIndex(upsertCachedIndexEntries(variantKey, entries, meta.logger).catch(() => {},);+ } else if (+ useIndexNegativeCache &&+ rows.length === 0 &&+ meta.options.minAge === undefined+ ) {+ // Confirmed empty for [dbStart - maxAge, dbStart]; record the left edge.+ setCachedNegative(variantKey, dbStart - maxAge, meta.logger).catch(+ () => {},+ );}data = rows;} catch (error) {diff --git a/apps/api/src/services/index-cache.ts b/apps/api/src/services/index-cache.tsindex 16a8fa859..3786d526e 100644--- a/apps/api/src/services/index-cache.ts+++ b/apps/api/src/services/index-cache.ts@@ -16,6 +16,7 @@ import type { Logger } from "winston";// instance.const ENTRY_KEY_PREFIX = "idxc:";+const NEG_KEY_PREFIX = "idxcneg:";const MAX_AGE_KEY_PREFIX = "idxma:";const ENTRY_TTL_SECONDS = 7 * 24 * 60 * 60;const MAX_AGE_TTL_SECONDS = 15 * 60;@@ -43,6 +44,18 @@ indexCacheRedis?.on("error", error => {export const useIndexCache = indexCacheRedis !== null;+// Negative (miss) caching is opt-in via a positive TTL. When enabled, a+// confirmed DB miss is recorded so repeat lookups for URLs with no index+// entry can skip Postgres entirely.+const NEGATIVE_TTL_MS = config.INDEX_CACHE_NEGATIVE_TTL_MS;+export const useIndexNegativeCache = useIndexCache && NEGATIVE_TTL_MS > 0;++// The negative marker shares the variant's hash but lives under its own+// prefix and TTL (deriveIndexVariantKey returns "idxc:<hash>").+function negKeyFor(variantKey: string): string {+ return NEG_KEY_PREFIX + variantKey.slice(ENTRY_KEY_PREFIX.length);+}+export type IndexCacheEntry = {id: string;created_at: string;@@ -203,9 +216,13 @@ export async function upsertCachedIndexEntries(const pipeline = client.pipeline();pipeline.hset(key, fields);pipeline.expire(key, ENTRY_TTL_SECONDS);+ // Writing positive entries invalidates any negative marker for this+ // variant — this is what keeps a surviving negative marker a proof that+ // nothing was inserted since it was set.+ pipeline.del(negKeyFor(key));pipeline.hlen(key);const results = await pipeline.exec();- const hlen = results?.[2]?.[1];+ const hlen = results?.[3]?.[1];if (typeof hlen === "number" && hlen > ENTRY_CAP) {const raw = await client.hgetall(key);const parsed = Object.entries(raw)@@ -314,3 +331,75 @@ export async function setCachedMaxAge(});}}++// A negative marker records that, as of when it was written, there was no+// index entry in [emptyFrom, writeTime] for the variant. A later lookup for+// window [now - maxAgeMs, now] is still guaranteed empty iff its left edge is+// no earlier than emptyFrom AND the marker still exists (a positive write+// would have deleted it, covering the (writeTime, now] tail). So the only+// check needed at read time is the left-edge comparison.+export function isNegativeStillValid(+ emptyFrom: number,+ maxAgeMs: number,+ now: number,+): boolean {+ return now - maxAgeMs >= emptyFrom;+}++export async function getCachedNegative(+ variantKey: string,+ logger: Logger = _logger,+ client: IORedis | null = indexCacheRedis,+): Promise<{ emptyFrom: number } | null> {+ if (client === null || !useIndexNegativeCache) {+ return null;+ }+ try {+ const raw = await withTimeout(+ client.get(negKeyFor(variantKey)),+ READ_TIMEOUT_MS,+ );+ if (raw === TIMED_OUT) {+ indexCacheErrorCounter.inc({ op: "negative_read_timeout" });+ return null;+ }+ if (raw === null || raw === undefined) {+ return null;+ }+ const emptyFrom = JSON.parse(raw).emptyFrom;+ return typeof emptyFrom === "number" ? { emptyFrom } : null;+ } catch (error) {+ indexCacheErrorCounter.inc({ op: "negative_read" });+ logger.warn("Index cache negative read failed", {+ module: "index-cache",+ error,+ });+ return null;+ }+}++// emptyFrom is the left edge of the confirmed-empty window: queryTime - maxAge.+export async function setCachedNegative(+ variantKey: string,+ emptyFrom: number,+ logger: Logger = _logger,+ client: IORedis | null = indexCacheRedis,+): Promise<void> {+ if (client === null || !useIndexNegativeCache) {+ return;+ }+ try {+ await client.set(+ negKeyFor(variantKey),+ JSON.stringify({ emptyFrom }),+ "PX",+ NEGATIVE_TTL_MS,+ );+ } catch (error) {+ indexCacheErrorCounter.inc({ op: "negative_write" });+ logger.warn("Index cache negative write failed", {+ module: "index-cache",+ error,+ });+ }+}