⚡
SF DEV TOOLKIT
Apex · SOQL · LWC · Patterns
API v62.0
Integration Deep Dive
MuleSoft ↔ Salesforce Handbook
Edge cases, pitfalls, and battle-tested patterns for MuleSoft-Salesforce integrations. What to solve in Mule vs. Salesforce, and how to avoid the common traps.
⚠️
Edge Case: Platform Event Replay After Mule Downtime
Scenario: MuleSoft subscriber goes offline for 30 minutes. When it reconnects, it misses 200 events published during downtime. Platform Events only retain events for 24-72 hours depending on event type. How do you guarantee no data loss?
Solve in Mule
Solve in Salesforce

MuleSoft Solution: Pub/Sub API with Durable Subscription

Use the Salesforce Pub/Sub API (gRPC) with a durable subscription. Each subscriber maintains a replay ID cursor. When Mule reconnects, it automatically resumes from the last processed event.

  • Configure MuleSoft to use gRPC Pub/Sub API instead of CometD Streaming API
  • Store the last successful replay ID in a persistent store (database, Redis)
  • On reconnect, resume from stored replay ID
  • Set replay preset to CUSTOM and pass the stored replay ID
Why This Works
Pub/Sub API maintains event retention for 24-72 hours. Durable subscriptions survive Mule restarts. You can replay missed events as long as they're within retention window.

Salesforce Solution: Change Data Capture + Batch Recovery

Instead of Platform Events, use Change Data Capture. CDC provides a guaranteed replay buffer. Combine with a nightly batch job as safety net.

  • Enable Change Data Capture on critical objects instead of Platform Events
  • CDC retains all changes for 3 days minimum (up to 30 days with Event Relay)
  • Build an Apex Batch job that runs hourly to sync any records updated in last 2 hours
  • Batch job acts as reconciliation — catches anything Mule missed
Trade-off
CDC has longer retention but higher licensing cost. Batch job adds complexity. Use this when missing events has severe business impact (financial transactions, compliance data).
🔄
Edge Case: Circular Update Loop (SF → Mule → SF)
Scenario: Opportunity update in Salesforce triggers Platform Event → MuleSoft enriches data from ERP → Mule upserts back to SF → this triggers another Platform Event → infinite loop crashes both systems.
Solve in Mule
Solve in Salesforce

MuleSoft Solution: Idempotency Header + Correlation ID

Add a custom header to every Mule → SF upsert request. Salesforce trigger checks this header and skips Platform Event publish if present.

  • Mule sets HTTP header: X-Integration-Source: MuleSoft
  • Mule sets unique correlation ID: X-Correlation-Id: uuid
  • Salesforce trigger checks Request.getCurrent().getHeader('X-Integration-Source')
  • If header equals 'MuleSoft', skip Platform Event publish
Limitation
This only works for API-based updates. If Mule uses Bulk API 2.0, headers are not available in triggers. Use Salesforce solution instead.

Salesforce Solution: Integration User + Bypass Flag

Create a dedicated Integration User for Mule. Trigger checks running user and skips Platform Event publish if it's the integration user.

  • Create Salesforce user: [email protected]
  • Grant this user a custom Permission Set: Integration_User_Bypass
  • In trigger: if (!FeatureManagement.checkPermission('Integration_User_Bypass')) { publishEvent(); }
  • All Mule API calls authenticate as this user
Best Practice
This pattern scales well. Works with Bulk API, REST API, and SOAP API. Easy to audit — all integration updates show as single user in field history.
⏱️
Edge Case: Bulk API Job Exceeds 24-Hour Processing Time
Scenario: MuleSoft submits a Bulk API 2.0 job with 5 million records. Salesforce takes 26 hours to process it. Job times out. You lose partial results and can't easily identify which records failed.
Solve in Mule
Solve in Salesforce

MuleSoft Solution: Chunking + Parallel Job Submission

Split the 5M records into 50 separate Bulk API jobs of 100k each. Submit them in parallel with max concurrency of 10 jobs at a time.

  • Use DataWeave to split CSV into 100k-row chunks
  • Submit each chunk as separate Bulk API job
  • Use Scatter-Gather pattern with 10 parallel routes
  • Poll each job independently until complete
  • Aggregate failed records from all jobs into single retry file
Performance Gain
10 parallel jobs finish in ~3 hours vs. 1 massive job taking 26+ hours. Easier to retry small failed chunks. Each job stays well under 24hr limit.

Salesforce Solution: Apex Batch + Platform Events for Progress

Don't use Bulk API for data already in Salesforce. Use Apex Batch to process in chunks with progress tracking via Platform Events.

  • Mule triggers an Apex REST endpoint to initiate batch job
  • Apex Batch processes records in 200-record chunks (well under governor limits)
  • Each chunk publishes a Progress Platform Event with success/failure count
  • Mule subscribes to progress events and monitors completion
  • No 24-hour timeout risk — Batch Apex has separate limits
When to Use
Only use this if data is already in Salesforce. For external → SF data loads, Mule chunking is faster. Apex Batch max: 5 jobs queued at once.
🔐
Edge Case: OAuth Token Expires Mid-Job (15-minute Expiry)
Scenario: MuleSoft starts a long-running process that makes incremental Salesforce API calls over 2 hours. After 15 minutes, the OAuth access token expires. Subsequent API calls fail with 401 Unauthorized. Entire process crashes.
Solve in Mule
Solve in Salesforce

MuleSoft Solution: Proactive Token Refresh with Interceptor

Implement a custom Mule interceptor that checks token expiry before each API call and refreshes proactively.

  • Store token metadata: { access_token, issued_at, expires_in }
  • Before each SF API call, check: if (now - issued_at > expires_in - 60s) refresh()
  • Refresh 60 seconds before actual expiry (safety buffer)
  • Use OAuth refresh token flow: POST /services/oauth2/token with grant_type=refresh_token
  • Update stored access_token and issued_at atomically
Recommended Approach
This prevents all 401 errors. MuleSoft Salesforce Connector handles this automatically, but if using HTTP Request connector, implement this manually.

Salesforce Solution: Use Session ID with Connected App

Instead of OAuth access tokens (15-min expiry), use Salesforce Session ID which lasts 2+ hours (configurable up to 12 hours).

  • Mule authenticates via SOAP login() call instead of OAuth
  • SOAP login returns sessionId with much longer expiry
  • Configure Session Settings in Salesforce: Setup → Session Settings → Timeout = 12 hours
  • sessionId valid for entire session duration
Security Trade-off
Session IDs are less secure than short-lived OAuth tokens. Only use for trusted internal integrations. Not recommended for public-facing APIs.
📋 MuleSoft ↔ Salesforce Best Practices
🔐
Authentication & Security
✓
Use OAuth 2.0 JWT Bearer flow (not username-password)
Server-to-server auth without user interaction. Rotate certificates annually. Store private keys in secure vault (Anypoint Secrets Manager).
✓
Create dedicated Integration User with minimal permissions
Never use admin credentials. Grant only necessary object/field permissions via Permission Set. Easier to audit and revoke access.
✓
Implement IP whitelisting on both sides
Salesforce: Restrict Connected App to Mule's IP range. Mule: Use Anypoint VPC to lock down egress IPs.
📊
Data Sync & Idempotency
✓
Always upsert by External ID — never query-then-insert
Mark Integration_Id__c field as externalId=true and unique=true. Mule upserts using this field. Eliminates race conditions and duplicate records.
✓
Design all endpoints to be idempotent
Same request processed multiple times produces same result. Use correlation IDs to detect duplicate requests. Store processed IDs in Redis/database with 24hr TTL.
✓
Use Bulk API 2.0 for >2,000 records
Bulk API 2.0 is faster and more reliable than REST API for large data volumes. Auto-batches into 10k chunks. Provides per-record success/failure tracking.
✓
Implement delta sync with Last Modified Date
Don't sync full dataset every run. Query: WHERE LastModifiedDate > :lastSyncTime. Store last sync timestamp in persistent store. Reduces API consumption by 95%+.
🚨
Error Handling & Monitoring
✓
Never lose data — implement DLQ (Dead Letter Queue)
Failed records → DLQ (persistent queue). Separate process retries DLQ records hourly with exponential backoff. Alert if DLQ size > threshold.
✓
Distinguish transient vs. permanent failures
Transient (network timeout, 503): Retry with backoff. Permanent (400 validation error, duplicate): Don't retry, log to error table for manual review.
✓
Set up proactive alerting on key metrics
Alert on: API call failures > 5%, Bulk job processing time > 2hr, Platform Event lag > 5 min, OAuth token refresh failures. Use Anypoint Monitoring + PagerDuty.
✓
Log correlation IDs end-to-end for traceability
Generate UUID in Mule entry point. Pass as X-Correlation-Id header to all downstream calls. Log it in Salesforce triggers. Enables tracing request across both systems.
⚡
Performance & Scalability
✓
Use Parallel Processing for independent operations
Scatter-Gather pattern: Query 3 objects in parallel vs. sequentially. Reduces total latency by 60%+. Max 10 parallel routes to avoid overwhelming SF.
✓
Cache reference data (RecordTypes, Picklists) in Mule
Don't query RecordTypeId on every record. Cache in Object Store with 24hr TTL. Refresh cache daily via scheduled flow. Saves 1000s of SOQL queries.
✓
Throttle API calls to stay under rate limits
SF rate limit: 100 API calls/user/20s. Use Rate Limiting policy in Anypoint to enforce 80 calls/20s per user. Prevents 503 errors during peak load.
Complete Mule Flow Example — Idempotent Upsert with Error Handling Mule DSL
<flow name="sync-accounts-to-salesforce">
  <!-- 1. Generate correlation ID for tracing -->
  <set-variable variableName="correlationId" 
                value="#[uuid()]" />
  
  <!-- 2. Transform ERP data to Salesforce format -->
  <ee:transform>
    <ee:message>
      <ee:set-payload>
        %dw 2.0
        output application/json
        ---
        payload map {
          Integration_Id__c: $.erpAccountId,
          Name: $.accountName,
          BillingStreet: $.address.street,
          AnnualRevenue: $.revenue as Number,
          // Correlation ID for idempotency check in SF
          Correlation_Id__c: vars.correlationId
        }
      </ee:set-payload>
    </ee:message>
  </ee:transform>
  
  <!-- 3. Upsert with External ID -->
  <try>
    <salesforce:upsert
      config-ref="Salesforce_Config"
      type="Account"
      externalIdFieldName="Integration_Id__c">
      <salesforce:records>#[payload]</salesforce:records>
    </salesforce:upsert>
    
    <!-- 4. Log success -->
    <logger level="INFO" 
             message="#['Upserted ' ++ sizeOf(payload) ++ ' accounts. Correlation: ' ++ vars.correlationId]" />
    
    <!-- 5. Error handling -->
    <error-handler>
      <on-error-propagate type="SALESFORCE:CONNECTIVITY">
        <!-- Transient error - send to retry queue -->
        <jms:publish destination="salesforce-retry-queue">
          <jms:message>
            <jms:body>#[payload]</jms:body>
            <jms:properties>
              #[{ correlationId: vars.correlationId, retryCount: 0 }]
            </jms:properties>
          </jms:message>
        </jms:publish>
      </on-error-propagate>
      
      <on-error-propagate type="SALESFORCE:INVALID_DATA">
        <!-- Permanent error - log to DLQ for manual review -->
        <db:insert config-ref="Database_Config">
          <db:sql>
            INSERT INTO error_log (correlation_id, error_type, payload, timestamp)
            VALUES (:correlationId, :errorType, :payload, NOW())
          </db:sql>
          <db:input-parameters>
            #[{
              correlationId: vars.correlationId,
              errorType: 'VALIDATION_ERROR',
              payload: write(payload, 'application/json')
            }]
          </db:input-parameters>
        </db:insert>
      </on-error-propagate>
    </error-handler>
  </try>
</flow>