Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

perf(defi): de-duplicate concurrent upstream fetches behind the shared mem-cache

nirholas251faa59dd98
diff --git a/api/defi/chains.js b/api/defi/chains.js
index 0dde7f804..ffafdfd97 100644
--- a/api/defi/chains.js
+++ b/api/defi/chains.js
@@ -8,17 +8,24 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const UPSTREAM = 'https://api.llama.fi/v2/chains';
const TTL_MS = 300_000;
-let _cache = null; // { value, expiresAt }
+// Single-entry cache with single-flight de-dup, so a burst of concurrent
+// requests on a cold or just-expired entry shares one upstream fetch.
+const _cache = createCache({ max: 1, ttlMs: TTL_MS });
+const CACHE_KEY = 'chains';
-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-chains endpoint sells the same cross-chain TVL board this page renders.
export async function buildChains() {
+ return cached(_cache, CACHE_KEY, loadChains);
+}
+
+async function loadChains() {
const now = Date.now();
- if (_cache && _cache.expiresAt > now) return _cache.value;
const resp = await fetch(UPSTREAM, {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
@@ -49,14 +56,12 @@ export async function buildChains() {
};
});
- const value = {
+ return {
total_tvl: totalTvl,
chain_count: eligible.length,
chains,
updated_at: now,
};
- _cache = { value, expiresAt: now + TTL_MS };
- return value;
}
export default wrap(async (req, res) => {
diff --git a/api/defi/dex-volumes.js b/api/defi/dex-volumes.js
index 90f1df8ba..8a769f847 100644
--- a/api/defi/dex-volumes.js
+++ b/api/defi/dex-volumes.js
@@ -11,13 +11,17 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const UPSTREAM = 'https://api.llama.fi/overview/dexs?excludeTotalDataChartBreakdown=true';
const TTL_MS = 600_000;
const MAX_CHART_POINTS = 200;
const MAX_PROTOCOLS = 100;
-let _cache = null; // { value, expiresAt }
+// Single-entry cache with single-flight de-dup, so a burst of concurrent
+// requests on a cold or just-expired entry shares one fetch of this ~2 MB feed.
+const _cache = createCache({ max: 1, ttlMs: TTL_MS });
+const CACHE_KEY = 'dex-volumes';
const finite = (n) => (Number.isFinite(n) ? n : null);
@@ -34,11 +38,14 @@ function normalizeChart(raw) {
return out;
}
-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-dex-volumes endpoint sells the same DEX rankings this page renders.
export async function buildDexVolumes() {
+ return cached(_cache, CACHE_KEY, loadDexVolumes);
+}
+
+async function loadDexVolumes() {
const now = Date.now();
- if (_cache && _cache.expiresAt > now) return _cache.value;
const resp = await fetch(UPSTREAM, {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
@@ -77,7 +84,7 @@ export async function buildDexVolumes() {
};
});
- const value = {
+ return {
total24h: finite(Number(raw.total24h)),
total7d: finite(Number(raw.total7d)),
change_7dover7d: finite(Number(raw.change_7dover7d)),
@@ -85,8 +92,6 @@ export async function buildDexVolumes() {
protocols,
updated_at: now,
};
- _cache = { value, expiresAt: now + TTL_MS };
- return value;
}
export default wrap(async (req, res) => {
diff --git a/api/defi/fees.js b/api/defi/fees.js
index 5ed5f3285..03c748fe7 100644
--- a/api/defi/fees.js
+++ b/api/defi/fees.js
@@ -12,13 +12,16 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const TTL_MS = 600_000;
const MAX_CHART_POINTS = 200;
const MAX_PROTOCOLS = 100;
-// One cache slot per data type — the two series are independent upstream calls.
-const _cache = new Map(); // type -> { value, expiresAt }
+// One cache slot per data type: the two series are independent upstream calls.
+// Single-flight de-dup means a burst of concurrent requests on a cold or
+// just-expired slot shares one fetch of this ~4 MB feed rather than one each.
+const _cache = createCache({ max: 2, ttlMs: TTL_MS });
const finite = (n) => (Number.isFinite(n) ? n : null);
@@ -40,12 +43,17 @@ function normalizeChart(raw) {
return out;
}
-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-fees endpoint sells the same fees/revenue rankings this page renders.
+// Anything other than 'revenue' means the fees series, so the key is normalized
+// here and the cache holds exactly the two slots it can ever need.
export async function buildFees(type) {
+ const key = type === 'revenue' ? 'revenue' : 'fees';
+ return cached(_cache, key, () => loadFees(key));
+}
+
+async function loadFees(type) {
const now = Date.now();
- const hit = _cache.get(type);
- if (hit && hit.expiresAt > now) return hit.value;
const resp = await fetch(upstreamFor(type), {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
@@ -78,8 +86,8 @@ export async function buildFees(type) {
};
});
- const value = {
- type: type === 'revenue' ? 'revenue' : 'fees',
+ return {
+ type,
total24h: finite(Number(raw.total24h)),
total7d: finite(Number(raw.total7d)),
total30d: finite(Number(raw.total30d)),
@@ -88,8 +96,6 @@ export async function buildFees(type) {
protocols,
updated_at: now,
};
- _cache.set(type, { value, expiresAt: now + TTL_MS });
- return value;
}
export default wrap(async (req, res) => {
diff --git a/api/defi/hacks.js b/api/defi/hacks.js
index 0fb9996e4..77f8c26cc 100644
--- a/api/defi/hacks.js
+++ b/api/defi/hacks.js
@@ -15,6 +15,7 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const UPSTREAM = 'https://api.llama.fi/hacks';
const TTL_MS = 600_000;
@@ -22,7 +23,10 @@ const YEAR_MS = 365 * 24 * 60 * 60 * 1000;
const MAX_LIMIT = 200;
const DEFAULT_LIMIT = 100;
-let _cache = null; // { value, expiresAt }
+// Single-entry cache with single-flight de-dup, so a burst of concurrent
+// requests on a cold or just-expired entry shares one upstream fetch.
+const _cache = createCache({ max: 1, ttlMs: TTL_MS });
+const CACHE_KEY = 'hacks';
const finiteOrNull = (n) => (Number.isFinite(n) ? n : null);
@@ -36,8 +40,11 @@ function normalizeChains(chain) {
// sorted, normalized incident list plus the dataset-wide headline stats — the
// per-request search/pagination happens on top of this cached whole.
async function loadDataset() {
+ return cached(_cache, CACHE_KEY, buildDataset);
+}
+
+async function buildDataset() {
const now = Date.now();
- if (_cache && _cache.expiresAt > now) return _cache.value;
const resp = await fetch(UPSTREAM, {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
@@ -89,7 +96,7 @@ async function loadDataset() {
}
}
- const value = {
+ return {
hacks,
stats: {
total_stolen_all_time: totalAllTime,
@@ -99,8 +106,6 @@ async function loadDataset() {
},
updated_at: now,
};
- _cache = { value, expiresAt: now + TTL_MS };
- return value;
}
function clampInt(raw, fallback, min, max) {
diff --git a/api/defi/protocols.js b/api/defi/protocols.js
index 57d0dc0ae..d8927414b 100644
--- a/api/defi/protocols.js
+++ b/api/defi/protocols.js
@@ -8,19 +8,28 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const UPSTREAM = 'https://api.llama.fi/protocols';
const TTL_MS = 300_000;
-let _cache = null; // { value, expiresAt }
+// Single-entry cache with single-flight de-dup. This feed is ~8 MB; without
+// de-dup every concurrent request arriving on a cold or just-expired entry
+// fired its own copy of it, so one page load by N visitors cost N full
+// downloads and could tip the upstream into refusing the burst.
+const _cache = createCache({ max: 1, ttlMs: TTL_MS });
+const CACHE_KEY = 'protocols';
const finite = (n) => (Number.isFinite(n) ? n : null);
-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-defi endpoint sells the same TVL leaderboard this page renders.
export async function buildProtocols() {
+ return cached(_cache, CACHE_KEY, loadProtocols);
+}
+
+async function loadProtocols() {
const now = Date.now();
- if (_cache && _cache.expiresAt > now) return _cache.value;
const resp = await fetch(UPSTREAM, {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
@@ -67,14 +76,12 @@ export async function buildProtocols() {
};
});
- const value = {
+ return {
total_tvl: totalTvl,
protocol_count: protocolCount,
protocols,
updated_at: now,
};
- _cache = { value, expiresAt: now + TTL_MS };
- return value;
}
export default wrap(async (req, res) => {
diff --git a/api/defi/stablecoins.js b/api/defi/stablecoins.js
index 38c278d5a..986b628b8 100644
--- a/api/defi/stablecoins.js
+++ b/api/defi/stablecoins.js
@@ -10,12 +10,16 @@
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { createCache, cached } from '../_lib/mem-cache.js';
const UPSTREAM = 'https://stablecoins.llama.fi/stablecoins?includePrices=true';
-const TTL_MS = 300_000; // 5 minutes — matches the CDN s-maxage below.
+const TTL_MS = 300_000; // 5 minutes, matches the CDN s-maxage below.
const TOP_N = 100;
-let _cache = null; // { value, expiresAt }
+// Single-entry cache with single-flight de-dup, so a burst of concurrent
+// requests on a cold or just-expired entry shares one upstream fetch.
+const _cache = createCache({ max: 1, ttlMs: TTL_MS });
+const CACHE_KEY = 'stablecoins';
// peg_type keeps DeFiLlama's raw token (`peggedUSD`, `peggedEUR`, …) so the
// client can render the pegged currency (USD, EUR) without a lossy remap; the
@@ -62,12 +66,13 @@ function shape(assets) {
};
}
-// Exported for the paid Market Data API (api/_lib/market-data/) — the x402
+// Exported for the paid Market Data API (api/_lib/market-data/), the x402
// market-stablecoins endpoint sells the same peg board this page renders.
export async function buildStablecoins() {
- const now = Date.now();
- if (_cache && _cache.expiresAt > now) return _cache.value;
+ return cached(_cache, CACHE_KEY, loadStablecoins);
+}
+async function loadStablecoins() {
const resp = await fetch(UPSTREAM, {
headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
signal: AbortSignal.timeout(10_000),
@@ -78,9 +83,7 @@ export async function buildStablecoins() {
const assets = Array.isArray(body?.peggedAssets) ? body.peggedAssets : null;
if (!assets) throw new Error('unexpected upstream shape');
- const value = shape(assets);
- _cache = { value, expiresAt: now + TTL_MS };
- return value;
+ return shape(assets);
}
export default wrap(async (req, res) => {