Skip to content

[DISCUSSION] LID Mapping Best Practices & Debugging Guide for Production #2414

Description

@alessandropcostabr

LID Mapping Best Practices & Debugging Guide

Background

We've been running a production WhatsApp Web system with Baileys for 6+ accounts handling thousands of conversations. Through extensive monitoring and real-world debugging, we discovered that LID (Linked Device) mapping is the most complex and undocumented aspect of the library.

The Problem

When Baileys emits events, JIDs come in multiple formats:

  • Phone JID: 5511947763114@s.whatsapp.net ← actual phone number
  • LID (Local ID): 123456789@lid ← arbitrary number, NOT a phone!

This causes issues when:

  • Passing LID directly to external APIs expecting phone numbers
  • Resolving contacts in external databases
  • Cross-worker communication in clustered systems

What Works: 3-Layer Fallback Pattern

async function resolveLidToPhone(jid, store, lidMap) {
  // Layer 1: If already a phone JID
  const phoneMatch = jid.match(/^(\d+)@/);
  if (phoneMatch) return phoneMatch[1];

  // Layer 2: Check store.contacts (local cache)
  const contact = Object.values(store.contacts || {}).find(c =>
    c.id === jid || c.jid === jid
  );
  if (contact?.phoneNumber) return contact.phoneNumber;

  // Layer 3: Check lidToPhoneMap (loaded from auth files)
  if (lidMap.has(jid)) return lidMap.get(jid);

  logger.warn('[LID fallback] could not resolve', { jid });
  return jid;
}

Key Insights

  1. store.contacts is unreliable alone — populated by contacts.upsert, not all events
  2. contact.phoneNumber can be undefined — depends on Phone Number Privacy setting
  3. lid-mapping-*.json files in auth dir — persistent mapping, should load on startup
  4. Multiple events populate the LID map:
    • contacts.update + contacts.upsert
    • messaging-history.set (during history sync)
    • Internal Signal/lid-mapping.js (not exposed as event)

Questions for Maintainers

  • Is contact.phoneNumber guaranteed when Phone Number Privacy = shareOwnPn?
  • Should there be a public API to access/load LidMappingStore?
  • Would a helper to warmup lid-mapping-*.json on init be useful?

Related

Full debugging guide with embedded code examples: #2417

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions