platform-events-integration

Use when publishing Platform Events from external systems via REST API, subscribing to Platform Events from outside Salesforce via CometD or Pub/Sub API, designing replay ID strategy for durable external consumers, or handling high-volume event delivery guarantees. Trigger keywords: 'external publish platform event', 'CometD subscribe', 'Pub/Sub API', 'replay ID external', 'durable subscription', 'RetainUntilDate'. NOT for Apex-only event publishing or triggering (use platform-events-apex). NOT for Change Data Capture external subscription (use change-data-capture-integration).

Best use case

platform-events-integration is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when publishing Platform Events from external systems via REST API, subscribing to Platform Events from outside Salesforce via CometD or Pub/Sub API, designing replay ID strategy for durable external consumers, or handling high-volume event delivery guarantees. Trigger keywords: 'external publish platform event', 'CometD subscribe', 'Pub/Sub API', 'replay ID external', 'durable subscription', 'RetainUntilDate'. NOT for Apex-only event publishing or triggering (use platform-events-apex). NOT for Change Data Capture external subscription (use change-data-capture-integration).

Teams using platform-events-integration should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/platform-events-integration/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/integration/platform-events-integration/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/platform-events-integration/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How platform-events-integration Compares

Feature / Agentplatform-events-integrationStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when publishing Platform Events from external systems via REST API, subscribing to Platform Events from outside Salesforce via CometD or Pub/Sub API, designing replay ID strategy for durable external consumers, or handling high-volume event delivery guarantees. Trigger keywords: 'external publish platform event', 'CometD subscribe', 'Pub/Sub API', 'replay ID external', 'durable subscription', 'RetainUntilDate'. NOT for Apex-only event publishing or triggering (use platform-events-apex). NOT for Change Data Capture external subscription (use change-data-capture-integration).

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Platform Events Integration

Use this skill when the integration boundary crosses outside Salesforce: an external system publishes Platform Events into Salesforce via REST, or a middleware consumer subscribes to events using CometD or the newer Pub/Sub API. The skill covers the full external connection lifecycle — auth, replay ID strategy, high-volume vs standard limits, delivery guarantees, and what to do when subscribers fall behind.

---

## Before Starting

- Is the external system acting as a publisher (pushing events into Salesforce), a subscriber (reading events from Salesforce), or both?
- What event API will the subscriber use: the legacy Streaming API over CometD, or the newer Pub/Sub API over gRPC?
- What is the expected event volume per hour? This determines whether you need a High-Volume Platform Event or a standard one.
- Does the subscriber need to recover after downtime? If yes, a durable subscription with explicit replay ID management is mandatory.
- What is the event retention requirement? Platform Events retain for 72 hours by default. High-Volume Platform Events support `RetainUntilDate` for longer windows.

---

## Core Concepts

### Publishing From External Systems via REST

External systems publish Platform Events by POSTing to the Platform Event sObject REST endpoint:

```
POST /services/data/vXX.0/sobjects/OrderShipped__e/
Authorization: Bearer <access_token>
Content-Type: application/json

{ "OrderId__c": "801xx000001234", "ShippedDate__c": "2025-10-01T00:00:00Z" }
```

The response contains a `replayId` for the published event. Authentication uses standard OAuth 2.0 connected app flows — JWT bearer for server-to-server or User-Agent/Web Server for interactive flows. The REST endpoint imposes the same API governor limits as standard sObject REST calls.

### Subscribing From External Systems: CometD vs Pub/Sub API

Two external subscription protocols exist:

**CometD (Streaming API):** Bayeux-protocol long-polling over HTTPS. Mature, supported in many enterprise middleware stacks. Requires managing handshake, re-subscribe after network disconnect, and replay extension (`/meta/subscribe` with `replay` extension field). CometD subscribers must reconnect after 40 seconds of inactivity; failure to reconnect within the replay window causes event loss.

**Pub/Sub API:** gRPC-based binary API introduced in Summer '22. Supports higher throughput, server-side schema fetch via Apache Avro, and bidirectional streaming. Preferred for new integrations where the middleware stack supports gRPC. Salesforce publishes client libraries for Java, Python, and Node. Auth is the same OAuth 2.0 flow used by REST.

The Pub/Sub API endpoint is separate from the standard instance URL: `api.pubsub.salesforce.com:7443`.

### Replay ID: At-Least-Once Delivery and Durable Subscriptions

Platform Events deliver at-least-once. Every event has a `replayId`. External consumers must store the last successfully processed `replayId` durably (database, distributed cache) so they can resume from exactly where they left off after a disconnect or restart.

Three special replay ID values:
- `-1` — subscribe from the latest event (miss all events published before subscription)
- `-2` — subscribe from the earliest retained event (replay from 72-hour window start)
- Specific `replayId` — replay from a known position (requires that the event is still within the retention window)

If a consumer starts fresh with `-1` and fails during processing, events emitted during the outage are lost unless the consumer switches to `-2` or a stored position on restart. Design consumers to store replay position before acknowledging processing completion.

### High-Volume Platform Events vs Standard Platform Events

| Feature | Standard Platform Event | High-Volume Platform Event |
|---|---|---|
| Max events per hour (publish) | 250,000 | Unlimited (platform capacity) |
| `RetainUntilDate` support | No (72-hour fixed window) | Yes (configurable retention) |
| Apex subscriber trigger | Supported | Supported |
| External CometD/Pub/Sub | Supported | Supported |
| Event monitoring | Event Log File | Event Log File |

Use High-Volume when message rate exceeds 250,000 per hour or when events must be retained beyond 72 hours (e.g., for batch reconciliation patterns that run on weekly cadence).

---

## Common Patterns

### Pattern 1 — External Publisher via REST with Idempotent Payload

**When to use:** An external order management or ERP system pushes domain events into Salesforce. The publisher controls event creation and timing.

**How it works:**
1. Configure a Connected App with OAuth 2.0 JWT Bearer flow for the external system.
2. Obtain an access token with the `api` scope (or the event-specific scope).
3. POST to `/services/data/vXX.0/sobjects/YourEvent__e/` with the event payload.
4. Include a stable idempotency key field on the event (e.g., `CorrelationId__c` as a Text field). Apex or Flow subscribers can deduplicate on this key.
5. Check the HTTP response for `success: true` and log the returned `replayId` if audit tracing is needed.

**Why not the alternative:** Polling a Salesforce query endpoint instead of publishing events couples the integration to Salesforce record shape and misses the decoupled event model.

### Pattern 2 — Durable External Subscriber via Pub/Sub API

**When to use:** A middleware platform must process Salesforce-published events reliably, including recovery after planned maintenance windows or unplanned outages.

**How it works:**
1. On first start, subscribe with `-2` (earliest) to catch any events already in the retention window, or with a stored `replayId` if one exists.
2. Fetch events in batches using the `FetchRequest` RPC. Pub/Sub API uses a request-credits model: send a `FetchRequest` with a `num_requested` count; the server streams responses until the credit is exhausted.
3. After processing each batch, persist the highest `replayId` to durable storage before acknowledging or processing the next batch.
4. On reconnect, always pass the last stored `replayId`. Never hardcode `-1` except for throw-away consumers.
5. For High-Volume events with `RetainUntilDate`, use Salesforce's `GetTopic` RPC to confirm the schema version before replaying older events.

**Why not the alternative:** CometD requires more client-side reconnect logic and is slower for high-throughput scenarios; Pub/Sub API handles backpressure natively through the credit model.

### Pattern 3 — Dead-Letter Handling When Subscribers Fall Behind

**When to use:** A subscriber has been offline longer than the 72-hour retention window, or a High-Volume event's `RetainUntilDate` has passed.

**How it works:**
1. Accept that events outside the retention window are permanently lost via normal replay.
2. Implement a compensating mechanism: the publisher writes the same payload to a durable store (e.g., a Salesforce Platform Cache partition, a BigObject, or an external message queue) when publishing the event.
3. On subscriber restart after a long outage, the subscriber reads from the durable store to backfill, then resumes live event subscription.
4. Alternatively, design the subscriber to tolerate gaps by requesting a full-state sync from Salesforce (REST or Bulk API query) before resuming event consumption.

---

## Decision Guidance

| Situation | Recommended Approach | Reason |
|---|---|---|
| External system publishes business events into Salesforce | REST POST to `/sobjects/EventName__e/` with JWT auth | Standard REST endpoint, no special client library needed |
| New middleware subscriber, gRPC stack available | Pub/Sub API | Higher throughput, Avro schema fetch, better backpressure |
| Legacy middleware already using Bayeux/CometD | Streaming API CometD | Less migration effort; still fully supported |
| Message rate > 250k/hour or retention > 72 hours | High-Volume Platform Event | Exceeds standard limits; HV events handle unlimited rate |
| Subscriber must recover after multi-day outage | High-Volume + RetainUntilDate + compensating durable store | 72-hour window insufficient; design explicit backfill path |
| Subscriber processing is not idempotent | Add correlation ID field + consumer-side dedup table | At-least-once delivery means duplicates will arrive |

---


## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

- [ ] External publisher authenticates with OAuth 2.0 connected app — no hard-coded credentials.
- [ ] Subscriber persists last processed `replayId` durably before marking batch complete.
- [ ] First-start replay strategy is documented: `-2` (earliest), stored ID, or intentional `-1` (no history).
- [ ] Event volume is confirmed against hourly publish limits; High-Volume tier selected if > 250k/hour.
- [ ] Idempotency: event payload includes a stable correlation or deduplication key.
- [ ] Dead-letter strategy defined for subscribers that may be offline beyond the retention window.
- [ ] High-Volume events that need extended retention have `RetainUntilDate` set explicitly.
- [ ] Monitoring: publisher failures and subscriber lag are observable (event log files, middleware metrics).

---

## Salesforce-Specific Gotchas

1. **`RetainUntilDate` does NOT exist on standard Platform Events** — it is only available on High-Volume Platform Events. Teams that design long-replay windows on standard events will hit silent data loss when the 72-hour window expires.
2. **CometD connections silently expire after 40 seconds of inactivity** — clients must send `/meta/connect` heartbeats continuously or the server closes the channel without error, leading to missed events that appear as gaps in the subscriber.
3. **Pub/Sub API uses a credit-based flow model** — if a client sends a `FetchRequest` and does not issue new credits after consuming the batch, the stream stalls. Middleware that expects a push model without managing credits will stop receiving events under load.
4. **At-least-once delivery means duplicates are guaranteed in retry scenarios** — every external subscriber must be idempotent; not designing for duplicates is the most common production reliability bug.
5. **Replay IDs are not sequential integers across all events** — they are opaque per-channel values. Do not subtract or compare replay IDs numerically to detect gaps; use the CometD or Pub/Sub API ordering guarantees instead.

---

## Output Artifacts

| Artifact | Description |
|---|---|
| REST publish pattern | Endpoint URL, auth setup, and payload structure for external publishers |
| Subscriber design recommendation | CometD vs Pub/Sub API choice, replay ID storage design, and backpressure handling |
| Event tier recommendation | Standard vs High-Volume guidance based on throughput and retention requirements |
| Idempotency and dead-letter design | Correlation key field design and compensating backfill strategy |

---

## Related Skills

- `apex/platform-events-apex` — Use when Apex is the publisher or subscriber. Covers `EventBus.publish`, Apex trigger subscribers, and publish result handling.
- `integration/change-data-capture-integration` — Use when external systems must consume record-change events from Salesforce rather than custom domain events.
- `integration/streaming-api-and-pushtopic` — Use when the integration uses legacy PushTopic queries over CometD instead of Platform Events.
- `architect/platform-selection-guidance` — Use when the decision between Platform Events, CDC, and Outbound Messaging is still open.

Related Skills

scim-provisioning-integration

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing SCIM-based user lifecycle provisioning into Salesforce from Okta, Azure AD / Entra, or another IdP — create/update/deactivate, group-to-permission-set mapping, attribute mapping, and deprovisioning semantics. Triggers: 'scim provisioning', 'okta scim salesforce', 'entra salesforce provisioning', 'user deactivation automation', 'group to permission set mapping'. NOT for SSO/authentication setup (see single-sign-on skills).

omnistudio-lwc-integration

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when embedding OmniScripts in Lightning Web Components, registering custom LWC elements inside OmniScript screens, or calling OmniScript/Integration Procedures from LWC. Triggers: embed omniscript in LWC, custom LWC element in OmniScript, call OmniScript from Lightning page, omnistudio-omni-script tag, seed data JSON, OmniScript launch from LWC. NOT for standalone LWC development, standard Flow embedding, or OmniScript-to-OmniScript embedding.

integration-procedures

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when building, reviewing, or debugging OmniStudio Integration Procedures. Triggers: 'integration procedure', 'IP', 'HTTP action', 'DataRaptor', 'rollbackOnError', 'failureResponse'. NOT for Apex-only integrations unless the main design choice is whether OmniStudio is still appropriate.

integration-procedure-cacheable-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Integration Procedures (IPs) with platform cache to cut latency and callout load. Covers cache key design, TTL selection, per-user vs org-wide partitions, invalidation on data changes, and safe fallback on cache miss/stale. Does NOT cover general IP authoring (see omnistudio-error-handling-patterns) or LWC client-side caching.

lwc-server-sent-events

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when building LWCs that must react to live server pushes — Platform Events, Change Data Capture, or streaming updates — via the lightning/empApi (CometD) subscription model. Covers lifecycle, replayId, error handling, reconnection, scale considerations, and multi-tab behavior. Does NOT cover publishing events (see platform-events or apex-platform-events).

slack-salesforce-integration-setup

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when setting up or troubleshooting the Salesforce for Slack managed app — including connecting a Salesforce org to a Slack workspace, configuring the three-party admin handshake, linking Slack channels to Salesforce records, enabling record preview sharing, and managing org-level limits. Triggers on: Salesforce for Slack app not connecting, Slack org connection setup, Salesforce record sharing in Slack, Slack workspace admin approval, connecting Salesforce to Slack. NOT for building custom Slack apps or Slack bots (separate development platform), not for Slack Workflow Builder Salesforce connector (use slack-workflow-builder skill), not for Flow-based Slack messaging (use flow-for-slack skill).

sis-integration-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill when designing or implementing an integration between a Student Information System (SIS) — such as Ellucian Banner, Ellucian Colleague, Anthology Student, Oracle PeopleSoft Campus Solutions, or Workday Student — and Salesforce Education Cloud. Covers the canonical Education Cloud data model objects (AcademicTermEnrollment, CourseOfferingParticipant, CourseOfferingPtcpResult, LearnerProfile, PersonAcademicCredential), external ID / upsert keying strategies using SIS-native identifiers (Banner PIDM, PeopleSoft EMPLID), batch nightly upsert patterns, Change Data Capture (CDC) for enrollment status writeback, and MuleSoft/middleware watermark patterns. Trigger keywords: SIS integration, Banner integration, PeopleSoft integration, Education Cloud data model, enrollment sync, grade writeback, AcademicTermEnrollment, LearnerProfile upsert. NOT for Salesforce Admissions Connect application processing, Financial Aid integration, Learning Management System (LMS) integrations, or general ETL tooling not involving Education Cloud objects.

salesforce-to-salesforce-integration

8
from PranavNagrecha/AwesomeSalesforceSkills

Use this skill to implement Salesforce-to-Salesforce integration patterns — covering the native S2S feature, API-based cross-org sync, Platform Event bridging, and Salesforce Connect Cross-Org adapter. Trigger keywords: Salesforce to Salesforce integration, cross-org data sharing, S2S feature, cross-org Platform Events, Salesforce Connect cross-org. NOT for multi-org strategy or architecture decisions (use architect/multi-org-strategy), single-org data sharing, or external (non-Salesforce) system integration.

real-time-vs-batch-integration

8
from PranavNagrecha/AwesomeSalesforceSkills

When to use this skill: choosing between real-time (synchronous callouts, Platform Events, CDC, Pub/Sub API) and batch (Bulk API 2.0, scheduled ETL) integration patterns. Trigger keywords: should I use real-time or batch, how to sync high-volume data, when to use Platform Events vs Bulk API, integration latency vs volume tradeoff. NOT for Batch Apex internals (use batch-apex-patterns), NOT for MuleSoft middleware design (use middleware-integration-patterns), NOT for CDC field tracking configuration.

platform-event-schema-evolution

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when modifying the schema of a Platform Event that already has live publishers and subscribers — adding fields, deprecating fields, or splitting events. Triggers: 'add field to platform event without breaking subscribers', 'platform event versioning', 'evolve event schema safely', 'rename a field on a published event'. NOT for initial event design (use integration/platform-events-integration) or for Change Data Capture event schemas.

platform-event-publish-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Publishing Platform Events: EventBus.publish, PublishBehavior (PublishImmediately vs PublishAfterCommit), high-volume events, event allocation, publish failures, Change Data Capture comparison. NOT for subscribing/consuming (use platform-event-subscribe-patterns). NOT for CDC architecture (use cdc-patterns).

middleware-integration-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when selecting or comparing middleware / iPaaS tools (MuleSoft, Dell Boomi, Workato, Informatica) for Salesforce connectivity, or when determining whether a scenario requires middleware at all versus native Salesforce capabilities. Triggers: 'which iPaaS should I use', 'MuleSoft vs Boomi vs Workato', 'when do I need middleware for Salesforce', 'message transformation orchestration middleware'. NOT for MuleSoft Anypoint Salesforce Connector configuration (use mulesoft-salesforce-connector). NOT for API-led connectivity layer design (use api-led-connectivity). NOT for native Salesforce-to-Salesforce integration, Platform Events, or CDC.