Sub topic 5
What a Middleware Layer Adds
This chapter assumes you know basic Salesforce concepts (objects, records, and the platform APIs), can read REST and JSON, and have seen an integration between two systems. It covers what a middleware layer does that native Salesforce tools do not do well. Later chapters cover MuleSoft in particular and the decision of when to use it.
What middleware is
Middleware is a runtime that sits between systems and handles the work of connecting them. Systems send messages to it or call it. It transforms, routes, secures, and records those messages, and it passes them on to other systems.
Salesforce can connect to other systems on its own with Flow, Apex callouts, Platform Events, and its APIs. Those tools run inside Salesforce and share its limits. Middleware runs outside Salesforce and has its own compute, its own queues, and its own tooling. That separation is the main thing it adds.
A middleware layer typically provides six functions:
| Function | What it does | What it replaces inside Salesforce |
|---|---|---|
| Transformation | Converts data between formats and field models | Apex mapping code |
| Orchestration | Runs a multi-step process across systems | Long Apex chains or Flow sequences |
| Routing | Chooses a destination based on message content or rules | `if` branches in Apex |
| Protocol mediation | Translates between protocols such as REST, SOAP, JMS, SFTP, and database connections | Custom callout code per protocol |
| Security | Authenticates callers, enforces policies, hides backend systems | Per-integration credential handling |
| Monitoring | Records traffic, errors, and latency in one place | Debug logs and ad hoc error objects |
The sections below take these in turn.
Transformation
Each system has its own data model. An ERP may call a company company_name and nest its address, while Salesforce expects Name and BillingCity. Doing this mapping in Apex works for one or two fields. It becomes a maintenance problem when many systems need the same mapping.
Middleware centralizes mapping in one place and usually in a dedicated language. MuleSoft uses DataWeave. This example maps a list of external customer records to Salesforce Account field names:
%dw 2.0
output application/json
---
payload map (customer) -> {
Name: customer.company_name,
BillingCity: customer.address.city,
External_Id__c: customer.id
}The mapping lives outside Salesforce. If the ERP renames company_name, you change the middleware and leave the Salesforce org alone. Several systems can also share one mapping instead of each carrying its own copy.
Orchestration
Orchestration means coordinating several calls into one business process. Consider order creation. The process might check credit in a finance system, reserve stock in a warehouse system, create the order in the ERP, and then write the result back to Salesforce. If the stock reservation fails, the credit hold may need to be released.
Inside Salesforce, this becomes a chain of callouts. Each callout counts against the per-transaction callout limit, and the whole chain must finish within the transaction's time limits. Compensating a failed step (undoing earlier steps) requires code you write and test yourself.
Middleware moves the process out of the Salesforce transaction. Salesforce sends one request, and the middleware runs the steps, handles partial failures, and reports a result. Salesforce stays simple and the sequence of steps is visible in one flow definition.
Routing
Routing decides where a message goes. Rules can depend on content, such as sending orders over a value threshold to an approval service. They can also depend on the target, such as sending EU customers to a regional system.
Without middleware, Salesforce must know every destination and the rules for choosing among them. Adding a destination means changing Salesforce. With middleware, Salesforce sends to one endpoint and the routing rules sit in the middleware, where they change without a Salesforce deployment.
Protocol mediation
Many back-end systems do not speak REST with JSON. You may meet SOAP services, message queues, file drops on SFTP, database connections, or older formats such as EDI and fixed-width files. Salesforce can call HTTP endpoints, and it can consume SOAP through WSDL-generated Apex classes. It cannot read an SFTP folder or consume a JMS queue directly.
Middleware ships connectors for these protocols. A common result is that Salesforce speaks REST to the middleware, and the middleware speaks whatever the back end needs. The Salesforce side stays uniform even when the back-end systems are not.
Security
Middleware puts a controlled layer in front of back-end systems. Three things follow from that:
- Credential isolation. Back-end credentials live in the middleware. Salesforce holds only the credential for the middleware.
- Policy enforcement. An API gateway can apply rate limits, client authentication, IP allow lists, and token validation before a request reaches a back end.
- Reduced exposure. A back-end system need not accept connections from Salesforce IP ranges or from the internet. Only the middleware needs a network path to it.
Native Salesforce handles credentials well for a single endpoint. A Named Credential stores the endpoint and authentication so Apex code never holds a secret:
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'));
}This is often enough for one simple request-reply call. The security gain from middleware grows with the number of systems, the number of callers, and the strictness of the policies you need to apply uniformly.
Reliability and error handling
Calls across systems fail. Networks drop, services time out, and targets reject bad data. Middleware commonly adds the following:
- Retries with back-off. A failed call is retried on a schedule instead of failing the user's transaction.
- Durable queues. Messages wait in a queue while a target system is down and are delivered when it returns.
- Dead-letter handling. Messages that keep failing move to a separate place where an operator can inspect and replay them.
- Idempotency support. Retries can create duplicates unless the receiver recognizes a repeated message. Middleware can attach a unique key and filter repeats, so a retried "create order" does not create two orders.
- Compensation. Failed multi-step processes can run undo steps.
Salesforce has partial equivalents. Platform Events are durable for a limited retention window, and Apex can retry through Queueable jobs. You build and operate the rest yourself.
This diagram shows a message that fails twice and then lands in a dead-letter queue.
Note that the middleware answers "Accepted" before the ERP call completes. This is an asynchronous design, and Salesforce learns the final result later, for example through a Platform Event or a callback.
Salesforce can publish an event for the middleware to pick up, so Salesforce does not need to know who listens:
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());
}
}Monitoring and governance
When an integration spans four systems, finding where a message failed is hard without a shared view. Middleware gives you one place to see request counts, error rates, latency, and message traces. It also lets you apply and version policies, publish API documentation, and manage which teams can call which APIs.
Without it, you check Salesforce debug logs, each back end's logs, and any custom error objects you built, and you correlate them by hand.
What middleware does not give you
Middleware has costs, and it is not free capability. Keep these points in mind:
- Another system to run. It needs deployment, upgrades, capacity planning, and on-call ownership.
- Extra latency. Each hop adds time. For a user waiting on a screen, an extra hop may matter.
- A new skill set. Your team must learn the middleware's tools and language.
- Licensing cost. Enterprise platforms are usually priced by capacity or number of connections.
- It does not remove Salesforce limits. API request limits still apply to the calls the middleware makes into Salesforce. Middleware can batch and pace those calls, but it cannot lift the quota.
Summary table: native versus middleware
| Concern | Native Salesforce | Middleware layer |
|---|---|---|
| Field mapping | Apex or Flow, per integration | Central, reusable mapping |
| Multi-step processes | Chained callouts inside limits | Process runs outside Salesforce |
| Non-HTTP protocols | Limited | Connectors for many protocols |
| Retry and replay | Built by you | Built-in queues and dead-letter handling |
| Credential scope | Per Named Credential | Gateway policies across systems |
| Observability | Debug logs, custom objects | Central traces and dashboards |
| Operational burden | Low, part of the org | Higher, a separate runtime |
Exercise
A retail company's Salesforce org must create an order in an ERP, reserve stock in a warehouse system, and notify a shipping provider that only accepts files over SFTP. Name three middleware functions this scenario needs, and explain why each is hard to do natively.
Show answer
Orchestration, because the three steps must run in sequence with undo steps if one fails, and chaining them in Apex would consume callout limits and transaction time. Protocol mediation, because Salesforce cannot write files to an SFTP server directly and would need a connector or an external service. Reliability handling (retries and dead-letter queues), because any of the three systems may be unavailable, and Salesforce would need custom code to hold and replay failed messages. Transformation is also a valid answer, since the three systems likely use different data formats.
Exercise
The middleware replies "Accepted" to Salesforce before the ERP call finishes. What problem does this create, and how can Salesforce learn the final result?
Show answer
Salesforce does not know whether the order was created. The middleware can report the outcome later, for example by publishing a Platform Event that Salesforce subscribes to, by calling a Salesforce API to update the order record, or by exposing a status endpoint that Salesforce polls.