How do external CometD client applications authenticate and subscribe to real-time Salesforce streaming channels?
Answer
Basics: Streaming API uses the Bayeux protocol with CometD over long polling. It lets external apps get Salesforce changes pushed to them without polling the REST API. Channels include /event/ (platform events), /data/ (Change Data Capture), /topic/ (PushTopics) and /u/ (generic streaming).
How it works:
- Obtain an access token with an OAuth flow (JWT bearer for servers, web server flow with PKCE for user apps). The user needs access to the channel's object.
- Connect to
https://<My Domain>/cometd/<api version>/. - Send the handshake, passing
Authorization: Bearer <token>. - Subscribe to the channel, optionally with a replay extension.
- Keep the connect request (long poll) running. Each message arrives with a
payloadand anevent.replayId. - Refresh the token when it expires and reconnect.
Advanced / deep dive: Replay IDs let a client resume from where it stopped. Use -1 for new events only, -2 for everything still retained, or a stored ID. Retention is 72 hours for platform events and change events and 24 hours for PushTopics (verify against current docs). Store the last replay ID durably, and reconnect with backoff. Streaming API has limits on concurrent clients and on events delivered per 24 hours, which depend on edition (verify current numbers). In Salesforce UIs, use lightning/empApi in LWC instead of building your own client. EMP Connector is an open-source sample for Java.
Code / config example:
// LWC: subscribe with lightning/empApi
import { subscribe, onError } from 'lightning/empApi';
connectedCallback() {
onError(e => console.error('EMP error', JSON.stringify(e)));
subscribe('/event/Order_Event__e', -1, msg => {
console.log('Order', msg.data.payload.Order_Id__c, 'replay', msg.data.event.replayId);
}).then(sub => { this.subscription = sub; });
}
Hidden gotchas & must-remember points:
- A bad session or token causes silent disconnects, so listen for handshake and subscription errors.
- Subscribers must have permission on the event object or the underlying object, and field-level security applies to change events.
- If the client falls outside the retention window, it misses events, so plan a resync.
- Cross-origin browser clients are subject to CORS settings.
- Pub/Sub API (gRPC) is the successor for external clients, with flow control and schema-based payloads.
- Streaming API is not guaranteed once-only delivery. Make handlers idempotent.
Best practice: Persist replay IDs, handle reconnects automatically, and choose Pub/Sub API for new external integrations.