Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): cap the lid->phone in-memory mirror with an LRU (#913)

Yudhi Armyndharis1964482b5d55
diff --git a/.env.example b/.env.example
index ee43b496d..64ab64f3f 100644
--- a/.env.example
+++ b/.env.example
@@ -140,6 +140,12 @@ BAILEYS_SYNC_FULL_HISTORY=false
# works regardless of this flag.
# RESOLVE_LID_TO_PHONE=true
+# Cap on the in-memory lid->phone mirror used for synchronous resolution on the dispatch hot path.
+# The table remains the source of truth; a cache miss falls back to engine re-resolution, so this
+# trades a re-resolution for bounded memory on a long-running, contact-heavy account. 0 disables the
+# cap (legacy unbounded behaviour). Default 5000.
+# LID_MAPPING_CACHE_MAX=5000
+
# Observability — Prometheus scrape endpoint at GET /api/metrics.
# Disabled by default; set a token to enable. Scrapers must send `Authorization: Bearer <token>`.
# METRICS_TOKEN=change-me-to-a-long-random-string
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bdb337bb7..8bb027821 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(build-stage build deps and production-stage Chromium/Puppeteer deps).
Smaller image; no behavior change for the explicitly-listed packages.
+- **The in-memory `@lid -> phone` mirror is now bounded by an LRU cap (`LID_MAPPING_CACHE_MAX`,
+ default 5000).** The mirror backs synchronous sender resolution on the dispatch hot path; it was
+ write-through but never evicted, so on a long-running, contact-heavy account it accumulated one
+ entry per distinct privacy-LID sender ever seen — a slow memory leak, and the lone unbounded
+ long-lived map in the process. `getCached` now touches the entry so iteration order tracks recency,
+ and the map evicts the least-recently-used entry when it exceeds the cap; the reverse `phone -> lids`
+ map is reconciled on each eviction. A cache miss falls back to engine re-resolution (the table
+ remains the source of truth), so the cap trades a re-resolution for bounded memory, never data loss.
+ `LID_MAPPING_CACHE_MAX=0` restores the legacy unbounded behaviour.
+
## [0.10.10] - 2026-07-25
### Added
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 14bf57162..fb3f1345a 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -4,6 +4,11 @@ import { Repository } from 'typeorm';
import { LidMapping } from './lid-mapping.entity';
import { createLogger } from '../../common/services/logger.service';
+// Default cap on the in-memory lid->phone mirror. Every other long-lived map in the audited surface is
+// bounded (the per-session lidPhoneCache is 5000); the LID mirror was the lone exception. A miss falls
+// back to engine re-resolution, so the cap trades a re-resolution for bounded memory, never data loss.
+export const LID_MAPPING_CACHE_DEFAULT = 5000;
+
/**
* Narrow read/write port over the `lid -> phone` table. The Baileys session store depends on this (sync
* reads on the resolution hot path + write-through) and the message from-filter depends on the reverse
@@ -24,17 +29,29 @@ export interface LidMappingStore {
* (filters/dispatch can't await a query), so the table is loaded into an in-memory map on boot and kept
* warm by write-through. A forward map (lid -> phone) serves resolution; a reverse map (phone -> lids)
* serves the from-filter.
+ *
+ * The forward map is bounded by an LRU cap (`LID_MAPPING_CACHE_MAX`, default 5000) so a long-running,
+ * contact-heavy account does not accumulate one entry per distinct LID ever seen into a slow memory leak.
+ * A cache miss falls back to engine re-resolution (the table remains the source of truth), so eviction
+ * only costs a re-resolution, never data loss. The reverse map is reconciled on each eviction so it does
+ * not retain entries for LIDs no longer in the forward cache.
*/
@Injectable()
export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
private readonly logger = createLogger('LidMappingStore');
private readonly lidToPhone = new Map<string, string | null>();
private readonly phoneToLids = new Map<string, Set<string>>();
+ // 0 = unbounded (legacy behaviour). Every other long-lived map in the audited surface is bounded, so
+ // the default is finite; the env override exists for operators who explicitly want the old behaviour.
+ private readonly maxCachedLids: number;
constructor(
@InjectRepository(LidMapping, 'data')
private readonly repo: Repository<LidMapping>,
- ) {}
+ ) {
+ const parsed = Number(process.env.LID_MAPPING_CACHE_MAX ?? LID_MAPPING_CACHE_DEFAULT);
+ this.maxCachedLids = Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : LID_MAPPING_CACHE_DEFAULT;
+ }
async onModuleInit(): Promise<void> {
try {
@@ -42,7 +59,9 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
for (const row of rows) {
this.index(row.lid, row.phone);
}
- this.logger.log(`Loaded ${rows.length} lid->phone mappings into cache`);
+ this.logger.log(
+ `Loaded ${rows.length} lid->phone mappings into cache${this.maxCachedLids ? ` (cap ${this.maxCachedLids})` : ''}`,
+ );
} catch (err) {
// A missing table (migration not yet applied) or a read error must not block boot: resolution
// falls back to the per-session in-memory map until the table is available.
@@ -51,7 +70,15 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
}
getCached(lid: string): string | null | undefined {
- return this.lidToPhone.get(lid);
+ // LRU touch: re-insert the entry so iteration order (insertion order for Map) tracks recency.
+ // A missed lookup returns undefined without disturbing the order.
+ if (this.lidToPhone.has(lid)) {
+ const phone = this.lidToPhone.get(lid);
+ this.lidToPhone.delete(lid);
+ this.lidToPhone.set(lid, phone as string | null);
+ return phone;
+ }
+ return undefined;
}
lidsForPhone(phone: string): string[] {
@@ -79,11 +106,26 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
if (prev && prev !== phone) {
this.phoneToLids.get(prev)?.delete(lid);
}
+ // Re-insert (delete + set) so the entry moves to the most-recent end of the LRU order even on update.
+ this.lidToPhone.delete(lid);
this.lidToPhone.set(lid, phone);
if (phone) {
const set = this.phoneToLids.get(phone) ?? new Set<string>();
set.add(lid);
this.phoneToLids.set(phone, set);
}
+ this.evictIfOverCap();
+ }
+
+ /** Evict the least-recently-used forward entry (and its reverse index) while over the cap. */
+ private evictIfOverCap(): void {
+ if (!this.maxCachedLids) return; // unbounded
+ while (this.lidToPhone.size > this.maxCachedLids) {
+ const oldest = this.lidToPhone.keys().next().value;
+ if (oldest === undefined) break;
+ const phone = this.lidToPhone.get(oldest);
+ this.lidToPhone.delete(oldest);
+ if (phone) this.phoneToLids.get(phone)?.delete(oldest);
+ }
}
}
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index 74dcf74c2..f5f2ba369 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -91,3 +91,69 @@ describe('LidMappingStoreService', () => {
expect(store.getCached('111')).toBeUndefined();
});
});
+
+describe('LidMappingStoreService — LRU cap', () => {
+ const prevMax = process.env.LID_MAPPING_CACHE_MAX;
+ afterEach(() => {
+ if (prevMax === undefined) delete process.env.LID_MAPPING_CACHE_MAX;
+ else process.env.LID_MAPPING_CACHE_MAX = prevMax;
+ });
+
+ it('evicts the least-recently-used forward entry when the cap is exceeded (no unbounded growth)', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '3';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ await store.onModuleInit();
+
+ await store.remember('lid-a', '620001');
+ await store.remember('lid-b', '620002');
+ await store.remember('lid-c', '620003');
+ // Touch lid-a so it is the most-recently-used; lid-b becomes the LRU candidate.
+ expect(store.getCached('lid-a')).toBe('620001');
+ // Inserting a fourth evicts the LRU (lid-b, not lid-a).
+ await store.remember('lid-d', '620004');
+
+ expect(store.getCached('lid-b')).toBeUndefined(); // evicted
+ expect(store.getCached('lid-a')).toBe('620001'); // touched, survived
+ expect(store.getCached('lid-c')).toBe('620003');
+ expect(store.getCached('lid-d')).toBe('620004');
+ });
+
+ it('reconciles the reverse map on eviction (no orphan phoneToLids entries)', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '2';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ await store.onModuleInit();
+
+ await store.remember('lid-a', '620001');
+ await store.remember('lid-b', '620001');
+ expect(store.lidsForPhone('620001')).toEqual(expect.arrayContaining(['lid-a', 'lid-b']));
+ // A third entry evicts lid-a (the LRU); the reverse set must drop it.
+ await store.remember('lid-c', '620002');
+ expect(store.lidsForPhone('620001')).toEqual(['lid-b']);
+ expect(store.lidsForPhone('620002')).toEqual(['lid-c']);
+ });
+
+ it('LID_MAPPING_CACHE_MAX=0 disables the cap (legacy unbounded behaviour)', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '0';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ await store.onModuleInit();
+
+ for (let i = 0; i < 10; i++) {
+ await store.remember(`lid-${i}`, `62000${i}`);
+ }
+ // Nothing evicted — all 10 stay resident.
+ for (let i = 0; i < 10; i++) {
+ expect(store.getCached(`lid-${i}`)).toBe(`62000${i}`);
+ }
+ });
+
+ it('falls back to the default cap on a non-numeric env value', () => {
+ process.env.LID_MAPPING_CACHE_MAX = 'not-a-number';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ // The constructor must not throw, and must apply the default (5000) rather than NaN/0.
+ expect((store as unknown as { maxCachedLids: number }).maxCachedLids).toBe(5000);
+ });
+});