Two-Way Salesforce Chat with Platform Events and LWC

Staff reply in a Lightning component, customers answer from a portal or phone, and every message is saved on the record. The steps, limits and tests.

By Published

Your team wants live chat with customers inside Salesforce. Staff type in a Lightning component on the record, the customer answers from a portal, an app or a phone, and every message is saved where reports and flows can use it. Standard platform features carry this: a message object, a Platform Event, an Apex service and a Lightning web component on each side.

We took these steps from one production build of this pattern. Every name below is generic.

What you need before you start

  • Enterprise, Performance, Unlimited or Developer Edition. Salesforce says platform events are not supported in Professional and Group Editions, though its allocation tables list Professional with the API add-on, so confirm with Salesforce.
  • The Customize Application permission, and a developer who can deploy Apex, Lightning web components and a static resource.
  • An Experience Cloud site if customers sign in, and a sandbox to test the live connection.

Step 1: Model the conversation as records

Use two custom objects, a thread and its messages. Relate the thread to the record the conversation is about, such as a Contact or a Case.

Object or fieldTypeJob
Chat_Thread__cCustom objectOwner (agent or queue), customer, status, last message time
Chat_Message__cCustom objectMaster-detail to the thread
Direction__cPicklistInbound, Outbound or System. System notes stay internal
Body__c, Sender_Name__cLong text, textWhat was said and who said it
Read_At__cDate/TimeBlank until the other side reads it; drives Delivered and Read
Client_Message_Id__cText, unique, external IDStops a double-click from saving the message twice
Chat_Error_Log__cCustom objectOne row for each publish, subscribe or delivery failure

As records, messages follow your sharing rules, reports, flows and retention. Keep the error log: a missed event looks exactly like a customer who stopped replying.

Step 2: Define a Platform Event that carries only the thread ID

Create Chat_Event__e under Platform Events in Setup, or deploy it as metadata. New definitions are high volume: Salesforce says standard-volume events exist only for definitions made before Spring '19.

objects/Chat_Event__e/Chat_Event__e.object-meta.xml
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">    <deploymentStatus>Deployed</deploymentStatus>    <eventType>HighVolume</eventType>    <label>Chat Event</label>    <pluralLabel>Chat Events</pluralLabel>    <publishBehavior>PublishAfterCommit</publishBehavior></CustomObject><!-- Two fields: Thread_Id__c (Text 18) and Kind__c (Text 20: message | read) -->

Choose Publish After Commit. Salesforce recommends Publish Immediately for most events and Publish After Commit when the subscriber needs committed data, which a chat window does because it re-queries the thread on every event. A change to this setting can take up to 5 minutes to apply.

Leave the message text out. Every subscriber on the channel receives every event, and field-level security does not apply to event fields, so text in the payload would reach every open console. With only the thread ID, each component asks Apex and gets back the rows that person may see.

An event beats polling because each open window queries once when its thread changes. Polling stays only as a fallback.

Illustration: one message from send to read receipt. The event carries the thread ID only, and each subscriber decides for itself whether to re-query.

Step 3: Publish from the Apex method that saves the message

Staff and portal messages both go through sendMessage, which sets the direction from the user type, upserts on the client message ID and then publishes. A trigger on every insert would also fire for bulk imports and ring every open chat.

classes/ChatService.cls · 76 lines
public with sharing class ChatService {     @TestVisible    static List<Chat_Event__e> published = new List<Chat_Event__e>();     @AuraEnabled    public static Id sendMessage(Id threadId, String body, String clientMessageId) {        if (String.isBlank(body) || body.length() > 4000 || String.isBlank(clientMessageId)) {            throw new AuraHandledException('Message is empty, too long or missing its ID.');        }        // Throws if the running user cannot see this thread.        Chat_Thread__c thread = [            SELECT Id FROM Chat_Thread__c WHERE Id = :threadId WITH USER_MODE        ];        Chat_Message__c msg = new Chat_Message__c(            Thread__c = thread.Id,            Body__c = body,            Direction__c = isInternal() ? 'Outbound' : 'Inbound',            Sender_Name__c = UserInfo.getName(),            Client_Message_Id__c = UserInfo.getUserId() + ':' + clientMessageId // unique, per sender        );        // A retried send updates the same row instead of adding a second one.        Database.upsert(msg, Chat_Message__c.Client_Message_Id__c, true, AccessLevel.USER_MODE);        publish(thread.Id, 'message');        return msg.Id;    }     @AuraEnabled    public static List<Chat_Message__c> getMessages(Id threadId) {        Set<String> visible = isInternal()            ? new Set<String>{ 'Inbound', 'Outbound', 'System' }            : new Set<String>{ 'Inbound', 'Outbound' }; // system notes stay internal        return [            SELECT Id, Body__c, Direction__c, Sender_Name__c, Read_At__c, CreatedDate            FROM Chat_Message__c            WHERE Thread__c = :threadId AND Direction__c IN :visible            WITH USER_MODE            ORDER BY CreatedDate DESC            LIMIT 200        ];    }     @AuraEnabled    public static void markRead(Id threadId) {        String incoming = isInternal() ? 'Inbound' : 'Outbound';        List<Chat_Message__c> unread = [            SELECT Id FROM Chat_Message__c            WHERE Thread__c = :threadId AND Direction__c = :incoming AND Read_At__c = null            WITH USER_MODE        ];        if (unread.isEmpty()) {            return; // nothing new, so no event and no refresh loop        }        for (Chat_Message__c m : unread) {            m.Read_At__c = System.now();        }        Database.update(unread, AccessLevel.USER_MODE);        publish(threadId, 'read');    }     // Publish After Commit: subscribers hear about it only if the save commits.    static void publish(Id threadId, String kind) {        Chat_Event__e evt = new Chat_Event__e(Thread_Id__c = threadId, Kind__c = kind);        published.add(evt);        Database.SaveResult result = EventBus.publish(evt);        if (!result.isSuccess()) {            // Write this to your error-log object. A failed publish looks            // exactly like a customer who stopped replying.            System.debug(LoggingLevel.ERROR, result.getErrors());        }    }     private static Boolean isInternal() {        return UserInfo.getUserType() == 'Standard';    }}
  • EventBus.publish does not throw on failure. A true isSuccess() means the event was queued (OPERATION_ENQUEUED), and the final result comes only from an Apex publish callback (Publish Event Messages with Apex).
  • With Publish After Commit, each publish call counts as one DML statement.
  • Link attachments first and publish last, so the other side never re-queries before the file is there.
  • markRead publishes only when it stamped something, so two open windows cannot refresh each other in a loop.

Step 4: Subscribe in a Lightning web component

There are two ways to listen:

Topiclightning/empApiCometD in a static resource
Runs inLightning Experience on desktop browsers with web worker support, API version 44.0 or laterAny page that loads it, including an Experience Cloud site
SessionHandled for you; one shared connection per userYou pass the signed-in user's session
Counts asOne concurrent CometD client per logged-in user, however many tabsOne concurrent CometD client per connection
Not supportedThe Salesforce mobile app, the utility bar pop-out, child windowsCometD versions before 3.1.0
Watch forSalesforce does not recommend it for apps or sites with many users, such as Experience CloudYou own the handshake, timeouts and retries

Sources: lightning/empApi reference, Subscribe in a Lightning Component, Common Platform Event Allocations and Supported CometD Versions. For staff, empApi is simpler. The build this guide comes from used CometD on both sides, and either works.

lwc/chatConsole/chatConsole.js · 45 lines
import { LightningElement, api } from 'lwc';import { subscribe, unsubscribe, onError } from 'lightning/empApi';import getMessages from '@salesforce/apex/ChatService.getMessages';import markRead from '@salesforce/apex/ChatService.markRead'; const CHANNEL = '/event/Chat_Event__e'; export default class ChatConsole extends LightningElement {    @api recordId; // 18-character Chat_Thread__c Id    messages = [];    subscription;    pending;     async connectedCallback() {        onError((error) => console.error('Chat channel error', JSON.stringify(error)));        await this.refresh(); // load first: the records are the source of truth        this.subscription = await subscribe(CHANNEL, -1, (event) => {            if (event?.data?.payload?.Thread_Id__c === this.recordId) {                this.scheduleRefresh();            }        });    }     disconnectedCallback() {        if (this.subscription) {            unsubscribe(this.subscription);        }        clearTimeout(this.pending);    }     // A message and its read receipt arrive close together: one query, not two.    scheduleRefresh() {        clearTimeout(this.pending);        // eslint-disable-next-line @lwc/lwc/no-async-operation        this.pending = setTimeout(() => this.refresh(), 250);    }     async refresh() {        const rows = await getMessages({ threadId: this.recordId });        this.messages = [...rows].reverse();        if (document.visibilityState === 'visible') {            await markRead({ threadId: this.recordId });        }    }}

Load the thread first, subscribe with replay -1 (new events only), and unsubscribe in disconnectedCallback so a closed tab stops using your delivery allocation.

On the portal, upload the CometD file as its own static resource; a zipped copy stopped loading in the build. Authenticate as the signed-in user with their own session. Salesforce notes that each logged-in site user gets their own Streaming API session.

classes/ChatSiteSession.cls
public with sharing class ChatSiteSession {    // The signed-in site user's own session carries exactly that user's    // access. Guests get nothing.    @AuraEnabled    public static String forSignedInUser() {        if (Auth.CommunitiesUtil.isGuestUser()) {            throw new AuraHandledException('Sign in to use live chat.');        }        return UserInfo.getSessionId();    }}
lwc/chatWindow/chatWindow.js · 86 lines
import { LightningElement, api } from 'lwc';import { loadScript } from 'lightning/platformResourceLoader';import COMETD from '@salesforce/resourceUrl/cometd'; // cometd.js on its own, not in a zipimport forSignedInUser from '@salesforce/apex/ChatSiteSession.forSignedInUser';import getMessages from '@salesforce/apex/ChatService.getMessages';import markRead from '@salesforce/apex/ChatService.markRead'; const CHANNEL = '/event/Chat_Event__e';const MAX_ATTEMPTS = 3;const POLL_MS = 15000; export default class ChatWindow extends LightningElement {    @api threadId;    messages = [];    attempts = 0;    cometd;    poller;     async connectedCallback() {        await loadScript(this, COMETD);        await this.refresh();        this.connect();    }     async connect() {        const session = await forSignedInUser();        const cometd = new window.org.cometd.CometD();        cometd.configure({            // Sites served under a path prefix may need it here; test in a sandbox.            url: `${window.location.origin}/cometd/68.0/`,            requestHeaders: { Authorization: `OAuth ${session}` },            appendMessageTypeToURL: false,        });        cometd.websocketEnabled = false;        // Delivery and client limit errors arrive here, not on the handshake.        cometd.addListener('/meta/connect', (reply) => {            if (!reply.successful && !this.poller && String(reply.error).includes('limit exceeded')) {                this.attempts = MAX_ATTEMPTS;                this.retry(); // straight to polling            }        });        cometd.handshake((reply) => {            if (!reply.successful) {                this.retry();                return;            }            this.attempts = 0;            cometd.subscribe(CHANNEL, (event) => {                if (event?.data?.payload?.Thread_Id__c === this.threadId) {                    this.refresh();                }            });        });        this.cometd = cometd;    }     // Arrow functions keep `this`; the cap stops a loop that never ends.    retry() {        if (this.cometd) {            this.cometd.disconnect();        }        this.attempts += 1;        if (this.attempts > MAX_ATTEMPTS) {            // eslint-disable-next-line @lwc/lwc/no-async-operation            this.poller = setInterval(() => this.refresh(), POLL_MS);            return;        }        // eslint-disable-next-line @lwc/lwc/no-async-operation        setTimeout(() => this.connect(), 1000 * 2 ** this.attempts);    }     async refresh() {        const rows = await getMessages({ threadId: this.threadId });        this.messages = [...rows].reverse();        if (document.visibilityState === 'visible') {            await markRead({ threadId: this.threadId });        }    }     disconnectedCallback() {        if (this.cometd) {            this.cometd.disconnect();        }        clearInterval(this.poller);    }}

Replay IDs. -1 delivers new events only, -2 every stored event (Salesforce says to use it sparingly), and a stored replay ID resumes after that event. Treat replay IDs as opaque: they are not contiguous or guaranteed unique, while EventUuid is (Message Durability). The browser components skip replay and re-query when they connect.

Reconnecting. A waiting Streaming API connection times out after 110 seconds, and a client that does not reconnect within 40 seconds of a response must handshake, subscribe and connect again (Clients and Timeouts). The portal component retries a failed handshake three times with backoff, then polls every 15 seconds. We used those values in one build, so test your own.

Step 5: Connect the customer's side

Signed-in portal users use the chat window above, and their messages are saved as Inbound through the same sendMessage.

Guests should never get a browser subscription, because any token in a browser can be copied and used against the Salesforce API. Two patterns still feel live:

  • Token-guarded polling. The link carries a random token. A narrow Apex method checks its hash, expiry and failed attempts, then returns that one thread. The guest profile needs no access to the chat objects.
  • A server-side relay. A service you run subscribes through Pub/Sub API, Salesforce's gRPC interface for events, with credentials kept on the server. It forwards only “thread changed” to browsers holding a short-lived ticket from Apex.
Guest link token (Apex)
// Issue a link token: keep only its hash on the thread.String token = EncodingUtil.convertToHex(Crypto.generateAesKey(256));thread.Access_Token_Hash__c = EncodingUtil.convertToHex(    Crypto.generateDigest('SHA-256', Blob.valueOf(token)));thread.Access_Token_Expires__c = System.now().addDays(7);// Send the token in the link. Apex compares hashes on every request,// counts failures on the thread record and rejects expired tokens.

If you add a mobile app or an SMS provider, it can receive through the same relay. To send, give it one entry point that calls the chat service, such as an Apex REST resource, so every inbound message is saved and published in one place. Apex REST calls count against the org's API limits. For bursts of webhooks, read platform events as a buffer for webhooks.

In one build, SMS went one way only: a Queueable Apex reminder about unread messages, sent after a consent check. Plan two-way SMS as new work. That build also converted iPhone HEIC photos to JPEG in the browser before upload.

Step 6: Plan for ordering, missed events and limits

Ordering. Order comes from the query, so a late, out-of-order or repeated event cannot scramble the thread. Salesforce publishes at least once and, rarely, delivers a duplicate with the same EventUuid (publishing considerations). A repeat re-query is harmless.

Missed events. The same page says a high-volume event is, in rare cases, never persisted and cannot be recovered. The records stay the source of truth for that reason.

Retention and replay. High-volume events are kept for 72 hours, and PushTopic, generic and standard-volume events for 24. Replay works through CometD and Pub/Sub API, not Apex, and a sandbox refresh or org migration can reset the stream (Apex and API considerations), so a relay should fall back to -1 and a re-query.

Retries. Failed publishes go to the error log, and a relay resumes from its last stored replay ID.

Default Platform Event allocations by edition
AllocationPerformance and UnlimitedEnterpriseDeveloper
Events delivered to CometD, empApi, Pub/Sub API and event relays, rolling 24 hours50,00025,00010,000
Events published per hour250,000250,00050,000
Concurrent CometD clients, all channels2,0001,00020
Platform event definitions100505

Sources: Default and Common Platform Event Allocations. The Enterprise delivery and publishing figures also cover Professional Edition with the API add-on, which gets 20 concurrent clients and 5 definitions. Apex trigger and flow subscribers do not use the delivery allocation, and Change Data Capture shares it.

Delivery runs out first because it counts once per subscribed client: in Salesforce's example, 20,000 events delivered to two clients use 40,000. If 40 people have the chat open and each message makes two events (the message and its read receipt), each message costs 80 deliveries, so an Enterprise org's 25,000 covers about 312 messages a day. Past that, CometD clients drop with 403::Organization total events daily limit exceeded, and a publish over the hourly allocation fails with LIMIT_EXCEEDED and is not queued. Watch PlatformEventUsageMetric, subscribe only where a thread is open, and at scale let one relay receive each event and fan it out.

Step 7: Test the service and the components

Apex tests publish to a separate test event bus, which delivers after Test.stopTest() or Test.getEventBus().deliver() (Testing Your Platform Event in Apex). Test events have their own limit of 500 per test method, and CometD and Pub/Sub API subscribers do not run (test context), so assert on the saved rows and the events the service captured.

classes/ChatServiceTest.cls
@IsTestprivate class ChatServiceTest {    @IsTest    static void retriedSendSavesOneMessageAndPublishesThreadId() {        Chat_Thread__c thread = new Chat_Thread__c();        insert thread;         Test.startTest();        ChatService.sendMessage(thread.Id, 'Hello', 'client-1');        ChatService.sendMessage(thread.Id, 'Hello', 'client-1'); // double-click        Test.stopTest(); // test events are delivered here         Assert.areEqual(1, [SELECT COUNT() FROM Chat_Message__c WHERE Thread__c = :thread.Id]);        Assert.areEqual(2, ChatService.published.size());        for (Chat_Event__e evt : ChatService.published) {            Assert.areEqual(String.valueOf(thread.Id), evt.Thread_Id__c);        }    }}

Add tests that run as a portal user to prove System notes stay hidden.

For the components, Jest tests do not run in a browser or connect to an org (Test Lightning Web Components). Salesforce ships stubs for lightning modules (Jest Test Patterns), and the empApi stub makes subscribe a Jest mock, so a test can feed its callback events.

lwc/chatConsole/__tests__/chatConsole.test.js
import { createElement } from 'lwc';import ChatConsole from 'c/chatConsole';import { subscribe } from 'lightning/empApi'; // stub from sfdx-lwc-jestimport getMessages from '@salesforce/apex/ChatService.getMessages'; jest.mock('@salesforce/apex/ChatService.getMessages', () => ({ default: jest.fn() }), { virtual: true });jest.mock('@salesforce/apex/ChatService.markRead', () => ({ default: jest.fn() }), { virtual: true }); const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0)); it('re-queries only for its own thread', async () => {    getMessages.mockResolvedValue([]);    const element = createElement('c-chat-console', { is: ChatConsole });    element.recordId = 'a01000000000001AAA';    document.body.appendChild(element);    await flushPromises();     const onEvent = subscribe.mock.calls[0][2];    getMessages.mockClear();    jest.useFakeTimers();    onEvent({ data: { payload: { Thread_Id__c: 'a01000000000002AAA' } } });    onEvent({ data: { payload: { Thread_Id__c: 'a01000000000001AAA' } } });    jest.runAllTimers();     expect(getMessages).toHaveBeenCalledTimes(1);});

Then test the portal in a sandbox copy of your site: the handshake, a session that expires mid-chat, the polling fallback and an expired guest link.

Step 8: Decide when to buy a messaging product instead

Build on Platform Events when Salesforce is where your team works, when messages need to drive automation and reporting, and when the number of people online at once fits the allocations above. Buy a messaging product when conversations stand alone, when you need channels such as WhatsApp or SMS threads from day one, or when nobody on your side will own the custom code: Apex, two components, a CometD integration, tests and an error log. If an AI assistant will answer first, see Salesforce AI chatbot architecture.

Every setting on one page

SettingWhere it livesValue in this guide
Message relationshipChat_Message__c.Thread__cMaster-detail to Chat_Thread__c
Direction valuesDirection__c picklistInbound, Outbound, System
Duplicate guardClient_Message_Id__cUnique, external ID, upsert key, prefixed with the sender's user ID
Event typeChat_Event__e definitionHigh volume
Publish BehaviorChat_Event__e definitionPublish After Commit
Event fieldsChat_Event__eThread_Id__c Text(18), Kind__c Text(20)
Apex sharingChatServicewith sharing, every query WITH USER_MODE
Staff subscriptionchatConsolelightning/empApi, /event/Chat_Event__e, replay -1
Portal subscriptionchatWindowCometD 3.1.0 or later, /cometd/68.0/, user's own session
CometD libraryStatic resource cometdThe single JavaScript file, not a zip
Retry and fallbackchatWindow3 attempts with backoff, then polling every 15 seconds
Guest accessToken-guarded Apex methodNo chat object access on the guest profile
Usage monitoringPlatformEventUsageMetricDaily delivery against your edition's allocation

When the chat stops updating

What you seeLikely causeFix
Every event refreshes every open chatNo thread check in the callbackCompare Thread_Id__c with the open thread first
The other side never updatesA component on a related record published that record's IDResolve the thread in Apex before publishing; compare 18-character IDs
The window shows the old thread after an eventThe event is set to Publish ImmediatelySwitch to Publish After Commit and allow up to 5 minutes
A failed handshake retries foreverThe callback lost thisArrow functions, a cap of three attempts, backoff, then polling
The CometD library will not loadIn one build, it sat inside a zip static resourceUpload cometd.js as its own static resource
The same message appears twiceA double-click sent it twiceDisable Send during the call and upsert on the client message ID
The event arrives before the attached filePublish ran before the files were linkedLink files first and publish last, in the same Apex call
Nothing happens in the mobile app or utility bar pop-outempApi is not supported thereOpen the record in the main desktop window
Clients drop with 403::Organization total events daily limit exceededThe 24-hour delivery allocation is used upPolling fallback, fewer subscribers, a relay, or an add-on
A stored replay ID fails after a sandbox refreshThe event stream was resetResubscribe with -1 and re-query the thread
Saving messages in bulk hits limitsA message trigger queries or launches a flow per recordKeep publishing out of the trigger and bulkify what stays

Frequently asked questions

Can you build two-way chat in Salesforce without a messaging product?

Yes. Save each message as a record, publish a Platform Event from the Apex method that saves it, and subscribe from Lightning web components that re-query the thread. It fits modest scale; thousands of people online at once hit the delivery and concurrent client allocations.

Which should you use, lightning/empApi or CometD?

Use lightning/empApi for staff in Lightning Experience on a desktop browser. Salesforce does not recommend it for apps or sites with many users, such as Experience Cloud sites, so a portal component usually loads a CometD client and authenticates as the signed-in user.

Can guest users subscribe to Platform Events?

Keep them off the event bus, because anything a guest's browser holds can be copied. Give guests a token-guarded Apex method to poll, or a relay that subscribes with server-side credentials and forwards only a thread-changed signal.

Should the Platform Event carry the message text?

No. Every subscriber on the channel receives every event, and field-level security does not apply to event fields. Send the thread ID and fetch the messages through Apex that enforces sharing.

What happens to messages sent while someone is offline?

They are records, so the chat window loads them when it next connects. Salesforce keeps high-volume events for 72 hours for replay by a stored replay ID, which a server-side relay can use.

Official references

All on Salesforce Developers unless marked.

GAT Solutions is an independent Salesforce consultancy. Salesforce is a trademark of Salesforce, Inc.

Continue the decision

View all resources →

Free consultation

Planning chat inside Salesforce? Tell us where it stands.

Never send us a key or password.

See Salesforce integration services

Book a call, or send us what is stuck.

What is stuck right now?

We reply the same day, or the next business day at the latest, and never sell your information.