Sub topic 11
Choosing the right pattern
This chapter assumes you know the Salesforce data model, basic Apex and triggers, REST and JSON, and HTTP methods and status codes. It also assumes you have read the earlier chapters on the three patterns, Named Credentials, governor limits, idempotency, and retries. Here you combine that material into a way to pick a pattern for a real requirement and defend the choice.
Start with the questions, not the tool
Teams often pick a pattern because a feature is familiar. A better approach is to ask five questions about the business requirement. The answers narrow the choice quickly.
- Does the caller need the answer to continue? If a user or a process cannot proceed without the other system's data, you need request-reply.
- How fast must the other side react? Seconds suggest events or callouts. Hours suggest batch.
- How much data moves, and how often? A single record per user action is different from two million rows per night.
- What happens if the other system is down? If the caller must not fail, decouple with events or batch. If failing fast is acceptable, a synchronous call is fine.
- Who initiates? Salesforce calling out, an external system calling in, or either side.
The three patterns compared
| Dimension | Request-reply | Fire-and-forget | Batch sync |
|---|---|---|---|
| Timing | Synchronous, caller waits | Asynchronous, caller continues | Scheduled or on demand, high latency |
| Coupling | Tight. Both systems must be up. | Loose. Publisher does not know subscribers. | Loose. Systems meet at job time. |
| Failure behavior | Caller sees the error immediately | Publisher succeeds. Subscriber failures happen later and need replay. | Job or individual rows fail. Results are reviewed after the run. |
| Typical Salesforce feature | Apex callout, REST API | Platform events, Change Data Capture | Bulk API 2.0 |
| Volume per operation | Low | Low to medium | Very high |
| Main limit pressure | Callout count, timeout, concurrent long-running requests | Event publishing and delivery allocations | Daily batch and job limits |
The next diagram turns the questions into a decision path.
This is a starting point, not a rule. Real requirements often need more than one pattern, as the scenarios below show.
Worked scenarios
Scenario 1: Credit check during quote approval
A sales rep clicks a button and the quote must show an approved or declined credit status before saving.
- The caller needs the answer, so this is request-reply.
- Use an Apex callout through a Named Credential, as in the earlier
InvoiceClientexample. - Set a short timeout and show the user a clear message on failure.
- Design for the outage case. Decide whether the quote can save with a "credit check pending" status, or whether it must be blocked.
If the credit service is slow, you consume the callout time of the transaction. Keep the call out of triggers on bulk-loaded objects, because a trigger cannot make a callout directly. Move the callout to asynchronous Apex such as a Queueable class if the user does not truly need to wait.
Scenario 2: Notify the warehouse when an order ships
When Salesforce marks an order as shipped, the warehouse system, an analytics tool, and a customer email service all want to know.
- Several consumers, and none of them feeds an answer back to the publisher. This is fire-and-forget.
- Publish a platform event such as
Order_Shipped__e. Each subscriber consumes it independently. - Adding a fourth consumer later requires no change to the publisher.
Check Database.SaveResult on publish, as in the earlier example. A successful publish means Salesforce accepted the event. It does not mean any subscriber processed it. If subscribers need to recover after downtime, they can use the replay ID to resume from a point in the event stream, within the retention window.
Scenario 3: Nightly ERP account load
An ERP holds 3 million customer records. Salesforce should reflect changes every night.
- High volume and no user waiting. This is batch sync.
- Create a Bulk API 2.0 ingest job with the
upsertoperation and an external ID field such asExternal_Id__c. - Upload the CSV, set the job state to
UploadComplete, then poll the job. After it finishes, read the failed-results and successful-results files. - Because the job uses an external ID, rerunning a failed file does not create duplicates.
Scenario 4: Sync one changed record immediately
A support agent edits an account's billing address, and the ERP must see it within a minute.
- One record at a time, with a short delay allowed. This points to fire-and-forget, using Change Data Capture or a platform event, with the consumer calling the ERP.
- The ERP update itself should be an upsert by external ID, for example
PATCH .../sobjects/Account/External_Id__c/ERP-10042. Then a redelivered message is harmless.
Combining patterns
Production systems often use two or three patterns together. A common arrangement is:
- Batch for the initial load and a nightly reconciliation.
- Fire-and-forget for incremental changes during the day.
- Request-reply for the few moments when a user needs live data.
The nightly batch acts as a safety net. If a missed event left the two systems out of step, the next reconciliation corrects it. This only works if both paths use the same external ID and upsert logic, so they cannot fight each other.
Trade-offs to state explicitly
When you justify a choice, name what you give up.
- Request-reply gives you an immediate answer and simple error handling. You give up availability, because the caller is only as reliable as the remote system, and you spend callout limits on every call.
- Fire-and-forget gives you resilience and fan-out. You give up certainty about outcome. Ordering, duplicates, and delivery lag become your problem, which is why idempotent consumers matter.
- Batch sync gives you throughput and cheap per-record cost. You give up freshness, and you must handle partial failure inside a job.
Common mistakes
- Using request-reply for bulk work. Looping over thousands of records with one callout each exhausts limits. Use Bulk API 2.0.
- Using batch for user-facing lookups. A nightly file cannot answer "what is this customer's balance right now?"
- Treating a published event as a processed event. Publish success is not business success. Add acknowledgment or monitoring if the outcome matters.
- Skipping idempotency. Any asynchronous pattern can deliver or run twice. Without an external ID, retries create duplicates.
- Hard-coding endpoints and secrets. Use Named Credentials for every outbound call, whatever the pattern.
- Forcing one pattern everywhere. A hybrid is often the correct design.
A short checklist for the design review
- State the requirement as timing, volume, and failure tolerance.
- Pick the pattern, or the combination, using the questions above.
- Pick the Salesforce feature that implements it.
- Name the authentication method and where credentials live.
- Identify the limits that apply and estimate your peak load against them.
- Define the idempotency key and the retry rule.
- Decide how failures are surfaced and who looks at them.
Exercise
A mobile sales app must show a customer's live credit limit from an external finance system when a rep opens an account. Separately, the finance system needs a copy of 500,000 updated contacts every weekend. Which pattern fits each need, and which Salesforce feature would you use for each?
Show answer
The credit limit lookup needs an immediate answer, so use request-reply: an Apex callout through a Named Credential (or an external service call that waits for the reply). Keep the timeout short and show a clear message when the finance system is unavailable. The weekend contact copy is high volume with no user waiting, so use batch sync with Bulk API 2.0, using an upsert on an external ID field so a rerun does not create duplicates.
Exercise
Your team publishes an Order_Shipped__e platform event. A manager says, "The publish returned success, so the warehouse has the order." What is wrong with that statement, and what two measures reduce the risk?
Show answer
A successful publish only means Salesforce accepted the event. It says nothing about whether any subscriber received or processed it. To reduce the risk, make subscribers idempotent and able to resume from a replay ID after downtime, and add monitoring or a nightly reconciliation (for example a Bulk API 2.0 comparison job) that catches missed events.