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): share the 8 MB protocol feed across chain profiles and bound the per-entity caches

nirholasb026b8f93a66
diff --git a/api/defi/chain.js b/api/defi/chain.js
index 50ca2f995..5ad24297e 100644
--- a/api/defi/chain.js
+++ b/api/defi/chain.js
@@ -22,10 +22,12 @@
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 NAME_RE = /^[a-z0-9 ._-]{1,40}$/i;
const CHAINS_URL = 'https://api.llama.fi/v2/chains';
+const PROTOCOLS_URL = 'https://api.llama.fi/protocols';
const CHAINS_TTL_MS = 300_000;
const CHAIN_TTL_MS = 300_000;
@@ -58,36 +60,44 @@ function downsample(arr, max) {
// ── /v2/chains: canonical-name resolution + market totals ────────────────────
-let _chainsCache = null; // { value: { list, totalTvl }, expiresAt }
+// Both feeds below are single-entry caches with single-flight de-dup, so a
+// burst of concurrent requests on a cold or just-expired entry shares one
+// upstream fetch. That matters most for the protocols feed: it is ~8 MB and
+// every distinct chain's profile needs it, so without sharing, warming N chains
+// meant N downloads of the same payload.
+const _chainsCache = createCache({ max: 1, ttlMs: CHAINS_TTL_MS });
+const _protocolsCache = createCache({ max: 1, ttlMs: CHAINS_TTL_MS });
async function loadChains() {
- const now = Date.now();
- if (_chainsCache && _chainsCache.expiresAt > now) return _chainsCache.value;
-
- const raw = await fetchJson(CHAINS_URL);
- if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');
-
- let totalTvl = 0;
- const list = [];
- for (const c of raw) {
- if (typeof c?.name !== 'string') continue;
- const tvl = Number(c.tvl);
- const posTvl = Number.isFinite(tvl) && tvl > 0 ? tvl : 0;
- totalTvl += posTvl;
- list.push({
- name: c.name,
- tvl: posTvl,
- tokenSymbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,
- chainId: c.chainId != null && Number.isFinite(Number(c.chainId)) ? Number(c.chainId) : null,
- });
- }
- // Rank is assigned over chains with a positive TVL, highest first.
- const ranked = list.filter((c) => c.tvl > 0).sort((a, b) => b.tvl - a.tvl);
- const rankByName = new Map(ranked.map((c, i) => [c.name, i + 1]));
+ return cached(_chainsCache, 'chains', async () => {
+ const raw = await fetchJson(CHAINS_URL);
+ if (!Array.isArray(raw)) throw new Error('unexpected upstream shape');
+
+ let totalTvl = 0;
+ const list = [];
+ for (const c of raw) {
+ if (typeof c?.name !== 'string') continue;
+ const tvl = Number(c.tvl);
+ const posTvl = Number.isFinite(tvl) && tvl > 0 ? tvl : 0;
+ totalTvl += posTvl;
+ list.push({
+ name: c.name,
+ tvl: posTvl,
+ tokenSymbol: typeof c.tokenSymbol === 'string' && c.tokenSymbol ? c.tokenSymbol : null,
+ chainId: c.chainId != null && Number.isFinite(Number(c.chainId)) ? Number(c.chainId) : null,
+ });
+ }
+ // Rank is assigned over chains with a positive TVL, highest first.
+ const ranked = list.filter((c) => c.tvl > 0).sort((a, b) => b.tvl - a.tvl);
+ const rankByName = new Map(ranked.map((c, i) => [c.name, i + 1]));
+
+ return { list, totalTvl, rankByName };
+ });
+}
- const value = { list, totalTvl, rankByName };
- _chainsCache = { value, expiresAt: now + CHAINS_TTL_MS };
- return value;
+// The full protocol feed, shared across every chain profile built in this TTL.
+async function loadProtocols() {
+ return cached(_protocolsCache, 'protocols', () => fetchJson(PROTOCOLS_URL));
}
// Resolve the request name to DeFiLlama's exact casing. Exact hit first, then a
@@ -185,17 +195,21 @@ function shapeFees(raw) {
// ── Per-chain payload (cached by canonical name) ─────────────────────────────
-const _chainCache = new Map(); // canonicalName → { value, expiresAt }
+// Per-chain cache, LRU-bounded so a scan across every chain name evicts the
+// coldest profile rather than clearing every warm one.
+const _chainCache = createCache({ max: 512, ttlMs: CHAIN_TTL_MS });
async function buildChain(canonical, chains) {
+ return cached(_chainCache, canonical.name, () => fetchChain(canonical, chains));
+}
+
+async function fetchChain(canonical, chains) {
const now = Date.now();
- const cached = _chainCache.get(canonical.name);
- if (cached && cached.expiresAt > now) return cached.value;
const enc = encodeURIComponent(canonical.name);
const [tvlRes, protoRes, stableRes, dexRes, feesRes] = await Promise.allSettled([
fetchJson(`https://api.llama.fi/v2/historicalChainTvl/${enc}`),
- fetchJson('https://api.llama.fi/protocols'),
+ loadProtocols(),
fetchJson(`https://stablecoins.llama.fi/stablecoincharts/${enc}`),
fetchJson(`https://api.llama.fi/overview/dexs/${enc}?excludeTotalDataChartBreakdown=true`),
fetchJson(
@@ -216,7 +230,7 @@ async function buildChain(canonical, chains) {
const rank = chains.rankByName.get(canonical.name) ?? null;
const share_pct = chains.totalTvl > 0 ? (canonical.tvl / chains.totalTvl) * 100 : null;
- const value = {
+ return {
chain: {
name: canonical.name,
token_symbol: canonical.tokenSymbol,
@@ -234,11 +248,6 @@ async function buildChain(canonical, chains) {
fees,
updated_at: now,
};
-
- // Bound the cache so a scan across every chain name can't grow it unbounded.
- if (_chainCache.size > 500) _chainCache.clear();
- _chainCache.set(canonical.name, { value, expiresAt: now + CHAIN_TTL_MS });
- return value;
}
export default wrap(async (req, res) => {
diff --git a/api/defi/protocol.js b/api/defi/protocol.js
index a6eeb8f29..ec3fd0c1a 100644
--- a/api/defi/protocol.js
+++ b/api/defi/protocol.js
@@ -17,13 +17,18 @@
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 SLUG_RE = /^[a-z0-9.-]{1,80}$/i;
const TTL_MS = 300_000;
const MAX_TVL_POINTS = 400;
const UA = 'three.ws/1.0';
-const _cache = new Map(); // slug -> { value, expiresAt }
+// Per-slug cache, LRU-bounded so a crawl over many slugs evicts the coldest
+// entry rather than discarding every warm one, with single-flight de-dup so
+// concurrent misses on the same slug share one round of the four upstream
+// calls below instead of firing four each.
+const _cache = createCache({ max: 512, ttlMs: TTL_MS });
// Coerce numbers and DeFiLlama's occasional numeric strings (audits count, some
// summary totals) to a finite number, else null.
@@ -222,24 +227,18 @@ function build(slug, proto, fees, revenue, dexs) {
}
async function load(slug) {
- const now = Date.now();
- const hit = _cache.get(slug);
- if (hit && hit.expiresAt > now) return hit.value;
+ return cached(_cache, slug, async () => {
+ // Main call is required; the rest are best-effort enrichment fetched in
+ // parallel. The main fetch throwing a 400/404 propagates as not-found.
+ const [proto, fees, revenue, dexs] = await Promise.all([
+ fetchJson(`https://api.llama.fi/protocol/${encodeURIComponent(slug)}`),
+ fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyFees`),
+ fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyRevenue`),
+ fetchOptional(`https://api.llama.fi/summary/dexs/${encodeURIComponent(slug)}`),
+ ]);
- // Main call is required; the rest are best-effort enrichment fetched in
- // parallel. The main fetch throwing a 400/404 propagates as not-found.
- const [proto, fees, revenue, dexs] = await Promise.all([
- fetchJson(`https://api.llama.fi/protocol/${encodeURIComponent(slug)}`),
- fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyFees`),
- fetchOptional(`https://api.llama.fi/summary/fees/${encodeURIComponent(slug)}?dataType=dailyRevenue`),
- fetchOptional(`https://api.llama.fi/summary/dexs/${encodeURIComponent(slug)}`),
- ]);
-
- const value = build(slug, proto, fees, revenue, dexs);
- // Bound the cache so a scan over many distinct slugs can't grow it unbounded.
- if (_cache.size > 500) _cache.clear();
- _cache.set(slug, { value, expiresAt: now + TTL_MS });
- return value;
+ return build(slug, proto, fees, revenue, dexs);
+ });
}
export default wrap(async (req, res) => {
diff --git a/api/defi/stablecoin.js b/api/defi/stablecoin.js
index 24c63f50f..3e00155c1 100644
--- a/api/defi/stablecoin.js
+++ b/api/defi/stablecoin.js
@@ -14,16 +14,19 @@
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 ID_RE = /^\d{1,6}$/;
const UPSTREAM = (id) => `https://stablecoins.llama.fi/stablecoin/${id}`;
-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 MAX_SUPPLY_POINTS = 400;
const MAX_CHAIN_POINTS = 200;
const TOP_CHAIN_SERIES = 5;
-// Per-id in-memory cache. { [id]: { value, expiresAt } }.
-const _cache = new Map();
+// Per-id cache, LRU-bounded so a scanner walking ids evicts the coldest entry
+// rather than the whole set, with single-flight de-dup so concurrent misses on
+// the same id share one upstream fetch.
+const _cache = createCache({ max: 512, ttlMs: TTL_MS });
const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
const httpUrl = (v) => (typeof v === 'string' && /^https?:\/\//.test(v.trim()) ? v.trim() : null);
@@ -172,32 +175,21 @@ function shape(raw, id) {
// Fetches + shapes one stablecoin, cached per id. Throws { status: 404 } when
// the id is unknown upstream so the handler can map it to a clean 404.
async function build(id) {
- const now = Date.now();
- const hit = _cache.get(id);
- if (hit && hit.expiresAt > now) return hit.value;
-
- const resp = await fetch(UPSTREAM(id), {
- headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
- signal: AbortSignal.timeout(10_000),
- });
- if (resp.status === 404) throw Object.assign(new Error('not found'), { status: 404 });
- if (!resp.ok) throw new Error(`llama ${resp.status}`);
-
- const body = await resp.json();
- if (!body || typeof body !== 'object' || body.id == null) {
- throw new Error('unexpected upstream shape');
- }
+ return cached(_cache, id, async () => {
+ const resp = await fetch(UPSTREAM(id), {
+ headers: { accept: 'application/json', 'user-agent': 'three.ws/1.0' },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (resp.status === 404) throw Object.assign(new Error('not found'), { status: 404 });
+ if (!resp.ok) throw new Error(`llama ${resp.status}`);
- const value = shape(body, id);
- _cache.set(id, { value, expiresAt: now + TTL_MS });
- // Bound the map — one entry per distinct id is tiny, but a scanner walking
- // ids could grow it unbounded across a long-lived warm instance.
- if (_cache.size > 512) {
- for (const key of _cache.keys()) {
- if (_cache.get(key).expiresAt <= now) _cache.delete(key);
+ const body = await resp.json();
+ if (!body || typeof body !== 'object' || body.id == null) {
+ throw new Error('unexpected upstream shape');
}
- }
- return value;
+
+ return shape(body, id);
+ });
}
export default wrap(async (req, res) => {
diff --git a/public/changelog.json b/public/changelog.json
index 94323af0d..a956fbd46 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T20:32:31.244Z",
+ "generated_at": "2026-08-12T20:34:07.075Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 7dd7e942e..5166ac9f8 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T20:32:31.223Z",
+ "generated_at": "2026-08-12T20:34:07.007Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",