Sub topic 12
Monitoring and operating integrations
This chapter assumes you have read the earlier chapters on the three patterns, Named Credentials, governor limits, idempotency, and retries. You should be comfortable with Apex callouts, platform events, Bulk API 2.0 jobs, and reading HTTP status codes.
An integration that works on release day is not finished. Credentials expire, partner systems slow down, and data volumes grow. Operating an integration means you find out about these problems before your users or the other system's team do.
What operating an integration involves
Most integration incidents are silent. A fire-and-forget publisher reports success even when no subscriber processed the event. A nightly Bulk API job can finish with JobComplete while thousands of rows failed. A request-reply callout that times out may have succeeded on the remote side.
Operations work answers four questions for each integration:
- Is it running? Did the expected callouts, events, or jobs happen in the expected window?
- Is it correct? Did the work succeed, and what happened to the records that failed?
- Is it within limits? How much of the API, callout, and event allocation is used?
- Can we recover? Can we find a failed message and safely replay it?
The sections below map these questions to Salesforce tools, then to the three patterns.
The monitoring toolbox
Salesforce provides several built-in sources. No single one covers everything.
| Source | Where | Best for |
|---|---|---|
| Apex Jobs | Setup, Apex Jobs | Status of queueable, batch, and scheduled Apex, including failures |
| Bulk Data Load Jobs | Setup, Bulk Data Load Jobs | State and record counts of Bulk API 2.0 jobs |
| Debug logs | Setup, Debug Logs | Detail on one callout or trigger run while you investigate |
| `/limits` REST resource | `GET /services/data/vXX.0/limits` | Remaining API requests and other org allocations |
| `EventBusSubscriber` | SOQL | Position, retries, and last error of platform event subscribers |
| Event Monitoring (`EventLogFile`) | SOQL or API, licensed add-on | Historical logs of API calls, Apex callouts, and logins |
| Setup Audit Trail | Setup | Who changed a Named Credential, connected app, or event definition |
Debug logs are for diagnosis, not monitoring. They expire after a short time and are limited in size and number, so they cannot tell you what happened last Tuesday night.
Event Monitoring is a separate licensed feature in many editions. Check what your org has before you design around it.
A model for integration telemetry
Think of operations as a pipeline. Each integration emits signals. Signals are checked against thresholds. A breach produces an alert, and an alert leads to a runbook action.
The point of the "cause known?" step is that different failures need different responses. Retrying a data error wastes calls. Fixing data does not help a network timeout.
Log every integration event with a correlation ID
Salesforce records do not tell you which remote call touched them. Add a correlation ID, a unique string you generate per business operation. Send it in a header on every callout and store it on every log entry. When a partner says "request 7f3a... failed," you can find your side of that exchange.
Write log entries somewhere that survives a transaction rollback. If a callout fails and your code throws an exception, any Integration_Log__c record you inserted in the same transaction is rolled back with it. A platform event published with the default "Publish Immediately" behavior is not rolled back, so it makes a reliable log channel.
The example below assumes you have defined a custom platform event Integration_Log__e with the text fields shown and a number field Status_Code__c. A trigger or flow on that event can then write durable log records.
public with sharing class IntegrationLogger {
public static void logFailure(
String integrationName,
String correlationId,
Integer statusCode,
String message
) {
Integration_Log__e evt = new Integration_Log__e(
Integration_Name__c = integrationName,
Correlation_Id__c = correlationId,
Status_Code__c = statusCode,
Message__c = String.isBlank(message) ? '' : message.abbreviate(255)
);
Database.SaveResult result = EventBus.publish(evt);
if (!result.isSuccess()) {
// Last resort: the debug log is better than losing the failure silently.
System.debug(LoggingLevel.ERROR,
'Could not publish log event for ' + correlationId);
}
}
}Use it in the request-reply client from the earlier chapter. The new parts are the correlation header and the logging call:
public with sharing class InvoiceClientWithLogging {
public static String fetchInvoiceStatus(String invoiceId) {
String correlationId = String.valueOf(Crypto.getRandomLong());
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/'
+ EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setHeader('X-Correlation-Id', correlationId);
req.setTimeout(10000);
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('status');
}
IntegrationLogger.logFailure('Billing_API', correlationId,
res.getStatusCode(), res.getBody());
throw new CalloutException('Billing API returned ' + res.getStatusCode());
} catch (System.CalloutException e) {
IntegrationLogger.logFailure('Billing_API', correlationId, null, e.getMessage());
throw e;
}
}
}Never log secrets, access tokens, or full personal data in the message. Log the status code, the correlation ID, and a short excerpt.
Monitoring request-reply integrations
Request-reply failures show up immediately, to the user or the calling code. What you need is trends.
Track these signals:
- Error rate by status code. A rise in 401 or 403 responses usually means expired or revoked credentials. A rise in 429 or 503 means the remote system is throttling or struggling. A rise in 5xx means the remote side is failing.
- Latency. Compare response time with your
setTimeoutvalue. Callouts that regularly take 8 seconds against a 10 second timeout are about to fail. - Callout counts per transaction. Apex limits the number of callouts per transaction, so a loop that makes one callout per record will fail at volume. The
Limits.getCallouts()method shows how many you have used. - Concurrent long-running requests. Synchronous Apex requests that run for a long time count against an org-wide concurrency limit, and slow remote calls consume it.
When your org is the server (an external system calls the REST API), the /limits resource shows how much of the daily API request allocation remains:
GET /services/data/v60.0/limits
Authorization: Bearer <access_token>The response includes entries such as DailyApiRequests, each with Max and Remaining values. Calls to the REST API also return a Sforce-Limit-Info response header, for example api-usage=18/15000. Have the calling system record this header so its team can see consumption without querying you.
Poll /limits on a schedule from your monitoring tool and alert at a percentage threshold, such as 80 percent of the daily allocation, rather than at zero. A flat threshold at zero gives you no time to react.
Monitoring fire-and-forget integrations
A publisher only learns that Salesforce accepted the event. Everything after that is invisible from the publishing code, so you must check the subscribers directly.
For subscribers inside Salesforce (Apex triggers on platform events), query EventBusSubscriber:
SELECT Name, Type, Topic, Position, Tip, Retries, LastError, Status
FROM EventBusSubscriber
WHERE Topic = 'Order_Shipped__e'How to read it:
Tipis the position of the newest event on the bus.Positionis the last event the subscriber processed. A growing gap between them means the subscriber is falling behind.Retriescounts retries after a retryable error, andLastErrorholds the most recent error text. A trigger that keeps throwingEventBus.RetryableExceptionshows up here.Statusshows whether the subscriber is running, in error, or suspended. A subscriber in an error or suspended state does not process events until it is fixed and resumed.
Also watch the allocations. Platform events have a limit on publishing volume and on delivery to external subscribers per 24 hours. The PlatformEventUsageMetric object reports usage against these allocations. If your org is near the delivery allocation, new external deliveries can be refused.
Events are stored on the bus for a limited time (72 hours for high-volume platform events). An external subscriber that is down longer than that cannot replay the missed events. Alert on subscriber lag well inside that window.
Monitoring batch sync
Bulk API 2.0 gives a clear status for every job, which makes batch the easiest pattern to monitor, as long as you read the counts and not just the state.
Get job status:
GET /services/data/v60.0/jobs/ingest/750xx0000000001AAA
Authorization: Bearer <access_token>The response includes state and the counters numberRecordsProcessed and numberRecordsFailed. States include Open, UploadComplete, InProgress, JobComplete, Failed, and Aborted.
The key gotcha: JobComplete means Salesforce finished processing, not that every row succeeded. Always check numberRecordsFailed. If it is greater than zero, download the failed rows:
GET /services/data/v60.0/jobs/ingest/750xx0000000001AAA/failedResults
Authorization: Bearer <access_token>The result is a CSV with the original row data plus sf__Error explaining each failure. A related unprocessedrecords resource lists rows that were never attempted, which happens when a job fails or is aborted midway.
A reliable batch run checks these in order:
- Create the job and record its ID with your own run ID.
- Upload the data and set the state to
UploadComplete. - Poll until the state is
JobComplete,Failed, orAborted. - Compare
numberRecordsProcessedwith the number of rows you uploaded. - If
numberRecordsFailedis above zero, fetchfailedResults, classify the errors, and either fix and resubmit those rows or send them to a person. - Record the counts in your run history.
Because the earlier chapter uses upsert by external ID, resubmitting only the failed rows is safe. A row that succeeded on the first run is not touched again.
Also alert on a job that never started. A scheduled batch that did not run produces no failure at all, so the check must be "no successful run in the last N hours," not "an error occurred."
What to alert on, by pattern
| Pattern | Alert on | Typical cause |
|---|---|---|
| Request-reply | Error rate over a threshold, p95 latency near the timeout, 401 or 403 spike | Expired credential, slow remote system, throttling |
| Fire-and-forget | Subscriber lag growing, subscriber status not running, event usage near allocation | Trigger error, retry loop, traffic spike |
| Batch sync | No completed job in the expected window, `numberRecordsFailed` above zero, job in `Failed` | Bad data, schema change, locked records, scheduler failure |
| All | Daily API usage near the allocation, configuration changes by an unexpected user | Runaway loop, unreviewed change |
Send alerts to a channel someone owns. An alert that goes to a shared inbox no one reads is the same as no alert.
Changes and credentials
Many incidents follow a change. Use Setup Audit Trail to see recent changes to Named Credentials, external credentials, connected apps, event definitions, and Apex classes. It keeps a limited history (180 days in the Setup UI), so export it if you need longer retention.
Credentials expire. For OAuth-based Named Credentials, know when the underlying client secret or certificate expires and put the date on a calendar owned by the integration team. For integration users, make sure the user is not subject to password expiry that would break the connection.
Keep a short runbook for each integration:
- Who owns it and how to reach them.
- What normal looks like (volume per hour, typical latency).
- The first three checks when an alert fires.
- How to replay or re-run safely, and which operations are not idempotent.
- How to disable it without losing data, for example pausing a subscriber or unscheduling a job.
Common operating mistakes
- Treating "published" as "delivered." Check subscriber position, not the
SaveResultalone. - Reading
JobCompleteas success. Always read the failed row count. - Alerting only at 100 percent of a limit. By then the integration has already stopped.
- Logging inside the transaction that may roll back. Use a channel that survives the failure.
- Keeping debug logs as the only history. They expire quickly.
- No owner. An integration with no named owner has no one to receive the alert.
Exercise
A nightly Bulk API 2.0 upsert job shows state JobComplete, yet the sales team says some accounts were not updated. What do you check first, and how do you fix the missing data safely?
Show answer
Check numberRecordsFailed on the job info, because JobComplete only means processing finished. Download the failedResults CSV and read the sf__Error column to classify the failures. Fix the data issues (or the field mapping), then resubmit only the failed rows as a new upsert job using the same external ID field. Since upsert by external ID is idempotent, rows that already succeeded are not duplicated.
Exercise
A trigger subscribed to OrderShipped_e throws EventBus.RetryableException on every event because a downstream lookup is failing. Which fields in EventBusSubscriber show the problem, and why is the publisher unaware of it?
Show answer
Retries rises and LastError shows the exception text. Position falls behind Tip as the subscriber stops advancing. The publisher is unaware because EventBus.publish only reports whether Salesforce accepted the event onto the bus. Delivery to and processing by subscribers happen afterward and independently.