Sub topic 14
Allocations, limits, and monitoring
This chapter assumes you can publish events from Apex, write a platform event trigger, and read Apex governor limit errors. It covers three things:
- the limits that apply to publishing and delivering events
- how to see how close you are to them
- what to do when a subscriber falls behind
Exact allocation numbers differ by edition, add-on licenses, and release. This chapter names the kinds of limits and the tools that report them. Take the current numbers from the Platform Events Developer Guide and from your own org.
Two kinds of limits
Platform event limits fall into two groups. They behave differently, so keep them apart.
| Group | Applies to | What happens at the limit |
|---|---|---|
| Transaction limits | One Apex transaction that publishes or consumes events | A `LimitException`, or a failed `SaveResult` |
| Org-wide allocations | Events published and delivered across the whole org over time | Publishing fails, or delivery to external clients stops until the allocation resets |
Transaction limits
Publishing from Apex is a DML operation, so ordinary governor limits apply.
- Each
EventBus.publishcall counts as one DML statement against the per-transaction DML statement limit. - Each event in the call counts toward the DML rows limit.
- Publish many events in one call. Publishing in a loop spends DML statements quickly.
- An event trigger runs in its own transaction for each batch. That transaction has its own fresh governor limits, including SOQL queries and DML.
- A single event message has a maximum size. Keep payload fields small, and send a record ID rather than a copy of the record.
For events defined with Publish Immediately, Apex also tracks a separate counter. Limits.getPublishImmediateDML() and Limits.getLimitPublishImmediateDML() report it.
The next class checks DML headroom before it publishes. It also reports each failure instead of ignoring the result.
public with sharing class OrderEventPublisher {
public static Boolean publishIfRoom(List<Order_Shipped__e> events) {
Integer dmlLeft = Limits.getLimitDmlStatements() - Limits.getDmlStatements();
if (events.isEmpty() || dmlLeft < 1) {
return false;
}
// One call for the whole list uses one DML statement.
List<Database.SaveResult> results = EventBus.publish(events);
Boolean allOk = true;
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
allOk = false;
for (Database.Error err : results[i].getErrors()) {
System.debug(LoggingLevel.ERROR,
'Event ' + i + ' failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}
}
return allOk;
}
}Org-wide allocations
Salesforce limits the number of event messages an org can use. Three allocations matter in practice:
- Publishing allocation. This caps how many events the org can publish in a period, such as an hour. When it is exhausted,
EventBus.publishreturns an unsuccessfulSaveResult, and REST publishes return an error. - Delivery allocation. This caps how many events can be delivered to CometD and Pub/Sub API clients in 24 hours. Delivery to
empApicomponents and external subscribers counts. Apex triggers and flows are handled differently and are not counted against this daily allocation in the same way. Confirm the exact rule for your release. - Monthly usage entitlement. Some editions and licenses have a monthly event allotment. Additional capacity is available as an add-on.
Each allocation counts per event message, not per subscriber. If several clients receive the same event, delivery usage grows with the number of deliveries.
The block above is a placeholder only if your renderer needs it. The real diagram follows.
Monitoring publishing and delivery
Event usage metrics
PlatformEventUsageMetric is a queryable object. It reports published and delivered counts in time segments, so you can compare usage against your allocation.
List<PlatformEventUsageMetric> metrics = [
SELECT Name, EventName, StartDate, EndDate, Value
FROM PlatformEventUsageMetric
WHERE StartDate = LAST_N_DAYS:1
AND TimeSegment = 'Hourly'
ORDER BY StartDate DESC
];
for (PlatformEventUsageMetric m : metrics) {
System.debug(m.Name + ' ' + m.EventName + ' ' + m.StartDate + ' = ' + m.Value);
}Metric names include one for published events and one for delivered events. Filter on Name once you have seen the values your org returns. Usage data can lag the actual traffic by a few minutes, so do not use it for a hard real-time cutoff.
The REST limits resource
The /limits resource returns the remaining allocation for the org. Look for the keys that mention platform events, such as hourly published events and daily delivered events. Each key returns a Max and a Remaining value.
GET /services/data/v60.0/limits/
Authorization: Bearer <access_token>Poll this resource from a monitoring job. Alert when Remaining falls below a threshold you choose, such as 20 percent of Max.
Monitoring subscribers
Allocations tell you how much traffic there is. Subscriber state tells you whether anything is consuming it.
Subscriber state in Setup
Open Setup > Platform Events, select the event, and look at the Subscriptions related list. Each trigger or flow subscribed to the event is listed with a status, a position, and a tip.
- Tip is the replay ID of the newest event on the bus for this event.
- Position is the replay ID of the last event the subscriber processed.
- The gap between them is the backlog. A gap that grows while Status is Running means the subscriber is slower than the publishers.
Common statuses:
| Status | Meaning | What to do |
|---|---|---|
| Running | The subscriber is processing events | Watch the gap between Position and Tip |
| Idle | There are no new events to process | Nothing |
| Suspended | The subscriber stopped, often after repeated retries | Read the error, fix the cause, then resume it |
| Error | The subscriber failed and needs attention | Read the error message, fix and redeploy |
Querying subscribers with SOQL
EventBusSubscriber exposes the same information, so a scheduled job can check it.
List<EventBusSubscriber> subs = [
SELECT Name, Type, Topic, Position, Tip, Retries, LastError, Status
FROM EventBusSubscriber
WHERE Topic = 'Order_Shipped__e'
];
for (EventBusSubscriber s : subs) {
Long backlog = s.Tip - s.Position;
System.debug(s.Name + ' (' + s.Type + ') status=' + s.Status
+ ' backlog=' + backlog + ' retries=' + s.Retries);
if (s.LastError != null) {
System.debug(LoggingLevel.WARN, 'Last error: ' + s.LastError);
}
}The Position and Tip values are replay-ID-style numbers, not guaranteed to be contiguous. Treat the difference as a relative signal and not as an exact count of events.
Keeping a trigger within its limits
An event trigger receives events in batches. The default batch size is 2,000, and your code must handle a batch of that size within one transaction's governor limits. Three habits keep it safe:
- Never run SOQL or DML inside the
forloop. Collect values first, query once, then act on the results. - Use a smaller batch size if each event needs heavy work. Configure it with a
PlatformEventSubscriberConfigrecord, which also lets you choose the running user. - Set resume checkpoints and throw
EventBus.RetryableExceptiononly for transient failures. A non-transient error that retries forever leaves the subscriber suspended with a growing backlog.
A smaller batch size reduces the work per transaction but increases the number of transactions. It does not remove backlog on its own. If the backlog grows, you need faster processing per event or fewer events.
Common mistakes
- Ignoring the
SaveResult. A publish that hits an allocation returns a failed result and does not throw. Without a check, events are lost silently. - Publishing inside loops. This spends DML statements and can fail the transaction before any events leave Apex.
- Assuming delivery counts equal publish counts. Delivery usage scales with the number of external subscribers.
- Watching only the publisher. Publishing can look healthy while a suspended trigger builds a backlog nobody sees.
- Putting large payloads in events. Large messages use more of the size and delivery budget. Send keys and let the subscriber query for details.
Exercise
A trigger subscribed to OrderShipped_e shows Status Running, but the Tip is 40,000 higher than its Position and the gap grows every hour. Publishing is working and no errors are reported. Name two possible causes and one action for each.
Show answer
The trigger processes events more slowly than they are published. Possible cause 1: each batch does expensive work, such as SOQL or DML inside a loop, or callouts and heavy logic per event. Action: bulkify the trigger so queries and DML happen once per batch, and reduce per-event work. Possible cause 2: the batch size is too large for the work per event, causing slow or limit-bound transactions. Action: lower the batch size with a PlatformEventSubscriberConfig record, and measure again. If volume is simply too high, reduce the number of events published or combine them into fewer events.
Exercise
Why must code that calls EventBus.publish check the returned SaveResult, and what does a failed result indicate when no exception is thrown?
Show answer
A publish that cannot be accepted, for example because a publishing allocation is exhausted, returns an unsuccessful SaveResult and does not throw an exception. If the code ignores the result, the event is lost without any sign of failure. Checking isSuccess() and logging getErrors() lets you detect the problem and retry or alert.