Sub topic 14
Anti-patterns to avoid
This chapter assumes you know basic Salesforce concepts (objects, records, the platform APIs), can read REST and JSON, and have met the earlier chapters on native options, governor limits, and when middleware fits. Here the focus is on the mistakes teams make in both directions: using too little integration tooling and using too much.
Why anti-patterns matter here
An anti-pattern is a common solution that looks reasonable and then causes problems. Integration anti-patterns are costly because they usually work in a demo. They fail later, under volume, during an outage, or when a second team needs the same data.
Most of them fall into two groups:
- Under-building: forcing native tools to do work they were not designed for.
- Over-building: adding middleware where a native feature would do, or using middleware badly.
Under-building anti-patterns
Point-to-point sprawl
Each new system gets its own direct connection to every other system it needs. With 4 systems fully connected there are 6 links. With 10 systems there are 45. Each link has its own credentials, field mappings, error handling, and owner.
Signs you have this problem:
- A change to one system's API breaks several unrelated integrations.
- Nobody can list every system that reads Salesforce Account data.
- The same mapping, such as a status code translation, is copied in several places and has drifted.
One or two direct links are fine. The anti-pattern is letting the count grow with no shared layer, as covered in the chapter on integration styles.
Orchestrating many systems inside Apex
A single Apex transaction calls an ERP, then a billing system, then a shipping service, and combines the results. It breaks for several reasons:
- A transaction allows at most 100 callouts and a limited total callout time. A slow downstream system consumes that budget.
- You cannot make a database change, then call out, then change data again without careful ordering. Salesforce rejects callouts after uncommitted DML in the same transaction.
- If step three fails, you must write your own compensation logic to undo steps one and two.
Apex is the right place for Salesforce-side logic. Multi-system orchestration with rollback is what middleware is for.
Business logic buried in callout code
This version is small and looks fine:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:ERP_Credential/orders/' + orderId);
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> order = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
System.debug(order.get('status'));
}It stays healthy while it is one request and one field. It becomes an anti-pattern when the same class grows to handle ten response shapes, three authentication styles, retry loops, and field translation for four systems. At that point the code is a hand-built integration platform with no monitoring and a deployment process tied to Salesforce releases.
A useful check: if you are writing retry loops, queues, or format converters in Apex, stop and ask whether this belongs in a different layer.
Ignoring failure: no retries, no idempotency
An integration that works only when everything is up is not finished. Common failures:
- A callout times out, and the code logs a debug line and moves on. The record is never synced.
- A retry sends the same "create order" request twice and the target creates two orders.
- A Platform Event publish returns a failure that nobody checks.
Publishing code should always read the result:
Order_Event__e evt = new Order_Event__e(Order_Number__c = '10045', Status__c = 'Shipped');
Database.SaveResult result = EventBus.publish(evt);
if (!result.isSuccess()) {
for (Database.Error err : result.getErrors()) {
System.debug(err.getMessage());
}
}Even this example only logs the error. In a real system, record the failure somewhere a person or a job will see it. For retries to be safe, the receiving side needs an idempotency key, a unique identifier such as the order number, so that a repeated request updates the existing record instead of creating a new one. In Salesforce, an upsert on an external ID field gives you this.
Polling in a loop
A scheduled job asks an external system "anything new?" every minute. Most of those calls return nothing, yet each one consumes API calls and callout limits. Prefer event-driven approaches where the source pushes changes, such as Platform Events or Change Data Capture, and keep polling for systems that cannot push.
Moving large volumes through the wrong API
Loading millions of records through single-record REST calls, or through Flow loops, burns API request allocation and runs slowly. Use Bulk API for large batch loads. If the volume and scheduling needs go beyond that, a middleware batch process with chunking and restart support is the next step.
Storing secrets in code or custom settings
Hard-coded endpoints and API keys in Apex, or passwords in unprotected custom fields, are a security failure and a deployment problem, since each sandbox needs a different value. Use Named Credentials so Salesforce manages the endpoint and authentication, and so the secret never appears in code.
Over-building anti-patterns
Middleware for a single simple integration
A team buys or licenses a middleware platform to make one request-reply call to one system. The extra layer adds license cost, a second deployment pipeline, another place to monitor, and new skills to hire for. If the integration is one call, uses standard authentication, has modest volume, and has one owner, the native example above is enough.
Middleware as a pass-through
The middleware receives a request and forwards it unchanged. It performs no transformation, no orchestration, no routing, and adds no security or monitoring value beyond what the endpoints already have. It adds latency and a failure point. Before adding the layer, name the function it will perform from the list in the earlier chapter on what middleware adds. If you cannot name one, you do not need it yet.
Hiding business rules in the middleware
Middleware is good at transformation like this DataWeave mapping:
%dw 2.0
output application/json
---
payload map (customer) -> {
Name: customer.company_name,
BillingCity: customer.address.city,
External_Id__c: customer.id
}It is a poor home for decisions such as "which accounts qualify for a discount." When rules like that live in flows nobody on the Salesforce team can see, admins change Salesforce validation and get surprising results. Keep business rules in the system of record that owns the data. Keep the middleware responsible for moving and reshaping data.
One giant API for everything
In an API-led design, some teams build a single "do everything" API that exposes every back-end system. It recreates tight coupling inside the middleware. Separate system, process, and experience layers exist so a change to one back-end touches one system API, not every consumer.
Treating middleware as someone else's problem
Teams hand integration to a central group and then have no say in error handling, SLAs, or change schedules. When an overnight sync fails, no one knows who owns the fix. Decide up front who monitors alerts, who handles dead-letter records, and who approves mapping changes.
Building before measuring
Choosing middleware because "we will need it eventually" is a guess. Measure expected volume, number of systems, and required latency first. Moving from a native integration to middleware later is real work, but it is usually cheaper than carrying unused platform cost and complexity for a year.
Quick reference
| Anti-pattern | Direction | Typical symptom | Better approach |
|---|---|---|---|
| Point-to-point sprawl | Under-building | Changes break many links | Shared layer or API-led design |
| Multi-system orchestration in Apex | Under-building | Limit errors, partial updates | Orchestrate in middleware |
| No retries or idempotency | Under-building | Duplicates, missing records | Idempotency keys, upsert, error queues |
| Polling loops | Under-building | Wasted API calls | Platform Events or Change Data Capture |
| Hard-coded secrets | Under-building | Leaks, broken deployments | Named Credentials |
| Middleware for one call | Over-building | Cost and slow delivery | Native callout or Flow |
| Pass-through middleware | Over-building | Extra latency, no gain | Remove it or give it a real job |
| Business rules in middleware | Over-building | Hidden behavior | Keep rules in the owning system |
Exercises
Exercise
An Apex class on Opportunity close calls a billing system, waits, then calls a provisioning system, then updates a CRM record. If provisioning fails, the code tries to cancel the billing call. Name two anti-patterns here and where the logic should move.
Show answer
It is multi-system orchestration inside Apex, and it also puts compensation (rollback) logic in callout code. Each callout uses transaction limits, and a slow system can exhaust them. The orchestration and compensation should move to a middleware process, or at least to an asynchronous design. Salesforce should publish an event or make one call, and the middleware coordinates billing and provisioning with retries and error handling.
Exercise
A retry job re-sends "create customer" requests after a timeout, and the target system now contains duplicate customers. What is missing, and how do you fix it in Salesforce?
Show answer
Idempotency is missing. The request has no unique key the receiver can use to recognize a repeat. Send a stable identifier, such as an external ID, and have the receiver (or Salesforce, when it is the receiver) upsert on that field so a repeated request updates the same record instead of creating another.
Exercise
A company with two systems, one REST call per day, and one admin team proposes adding a middleware platform "for future growth." Which anti-pattern is this, and what would you ask before agreeing?
Show answer
It is middleware for a single simple integration, built before measuring. Ask which middleware function (transformation, orchestration, routing, security, monitoring) is needed today, what the expected volume and number of systems are, and who would own the new platform. If none of the answers show a real need, use a native callout with a Named Credential.