Thanksgiving Week Special – Get 50% OFF on FileTranz

Claim Your Offer

Mastering MuleSoft Batch Processing for Real World ETL

Master MuleSoft Batch Processing with the step-by-step architecture, debugging, watermarking, and a real-world database to Salesforce ETL sync pipeline.

By Prasanna Saravanan
Assistant Software Developer

Mastering MuleSoft Batch Processing for Real World ETL

When I started learning about Batch Processing in MuleSoft”, I was confused by the available documentations. However, after putting theory into practice and doing some thorough research, I have come to understand how Batch Processing works. In this blog, I will explain everything you need to know about Batch Processing in simple terms. I will explain what a Batch Job is, what each step and aggregator does, and help you understand.

What is Batch Processing?

  • Let’s say we need to load 500,000 customer records from our database into Salesforce every night. If we do this using a normal Mule flow, we will have issues with high-memory consumption, timeouts and if one record fails all the records will fail.
  • Batch processing in Mule 4 allows us to process large volumes of data in a reliable way. Within the Batch Job scope, we can split our data into individual records and process in parallel in small chunks. Once processing completes we receive a summary. This is what Batch Processing does within MuleSoft.

 

How does a Batch Job Work?

There are three stages that are performed inside the batch job.

  • Load & Dispatch: This is an automatic process. Mule will take the incoming payload, splits this into individual records and add them to a queue.
  • Process: Records will be removed from the queue in batches and processed by one or more Batch Steps. Each Batch Step will perform an action such as Transform, Validation or API call. The records will be transferred between all steps, and each record is monitored individually.
  • On Complete: This stage will provide a summary, telling us how many records have been processed, how many have been successful and how many have failed. This is where we would want to send through a report or notification.

Batch Job:

This is the main scope within batch processing. We can set options such as block size and maximum failed records.

Note: Inside Anypoint Studio, you can access the batch job in the Mule Palette.

 

Configurations:

  • Name: Unique name used to identify this Batch Job within the application logs.
  • Max Failed Records: Number of failed records to allow before stopping the runtime. 0 means no failed records are allowed. -1 means allowing all failed records.
  • Scheduling Strategy: Whether your batch jobs will be executed one after the other (ORDERED_SEQUENTIAL) or distributed evenly.
  • Job Instance ID: Custom DataWeave expression to give each instance a unique ID. For example: correlationId.
  • Batch Block Size: The amount of records to batch together in to one block (Default 100).
  • Max Concurrency: The maximum amount of threads that can be active at once. we can keep the concurrency based on the amount of data we are going to deal.
  • Target: Variable name to store the results of the execution.

Batch Step:

A batch step will act as a filter part for our project. There can be multiple steps, and each record will pass through the steps. You can use an accept expression or policy to decide which records to process.

E.g: (ALL, ONLY FAILURES, NO FAILURES (default)).

 

Configurations:

  • Name: Unique name used to identify this Batch step within the application logs.
  • Accept Expression: Here we are going to write our Boolean expression like (payload.age as Number >= 18).
  • Accept Policy: This determines whether you will process records which have been successful or failed in previous Batch Steps.
  • NO_FAILURES (Default): Only process records that have been successful in previous steps.
  • ONLY_FAILURES: If we choose this then it will process, only if the data is failed in the previous step.
  • ALL: Process all records.

Batch Aggregator:

This will group records together so they can be processed as a batch. For example, instead of inserting 10,000 records individually, you could insert 100 records at a time using a bulk insert. This will greatly improve the performance of our real-time process. 

Note : You are not able to place a components inside the Batch Aggregator, First you need to drag and drop the Batch Aggregator component inside that Aggregate scope and we need to place the components inside it. Inside Anypoint Studio, You can access the batch Aggregator in the Mule Palette.

 

Configurations:

  • Aggregator Size: This determines that how many records will be sent in an array to be passed to the aggregator. This can be used for bulk inserting into a database or bulk calling an API. In real time use case, we are implementing our logic inside the Aggregator portion.
  • Streaming: Process your data in batches, so that you can avoid running into any memory problems.
  • Preserve MIME Types: Keep your data format (for example JSON, Java Object and CSV) intact for each individual record.

Hands-On Challenge to Learn: Filter and Batch Aggregation in Mule 4:

  • Create an endpoint for a POST call (/batch1). Pass a batch of 1000 employee records into the Batch Job using the configuration below.
    • Note that the batch size is set to 10 and failure tolerance is set to -1.
  • Within your Batch_Step, use a filter to reduce the number of records that you are processing. Only process a candidate if they are aged 18 or older (payload.age as Number >=18). Log each individual record and aggregate into batches of 200.
  • Log details of how the batch was executed using console logging throughout the step, aggregator, and On Complete. Return a JSON object containing a summary of how many total, failed, and processed records there were.

XML code to do hands-on:

As a beginner, you can use the XML code in your Anypoint Studio. That is easy to understand, and it will help you do the hands-on work related to our blog.

<flow name="55555Flow" doc:id="f980b70e-0ffc-4180-b547-7a7581d732c5" >
		<http:listener doc:name="Listener" doc:id="0d89b5c6-9fb5-4135-bd42-c5e18cb0a4c2" config-ref="HTTP_Listener_config" path="/batch"/>
		<batch:job jobName="Batch_Job1" doc:id="e2c92b0b-f1d6-47a3-bde1-b348c3931e3c" maxFailedRecords="-1">
			<batch:process-records >
				<batch:step name="Batch_Step" doc:id="091e84eb-0b38-4ca6-a8c7-f74083ab0245" acceptExpression="payload.age as Number &gt;= 18">
					<logger level="INFO" doc:name="Logger" doc:id="e7f4e188-690b-4572-b2a5-69bfc90e80ea" message="#[payload]" category="AFTER BATCH STEP==============================================&gt;"/>
					<batch:aggregator doc:name="Batch Aggregator" doc:id="5cadb021-4ba7-4180-996d-87c5994f79b5" size="10">
						<logger level="INFO" doc:name="Logger" doc:id="0af01796-32bb-4ba9-b6f2-7641f9f8cb6f" message="#[payload]" category="AFTER BATCH AGGREGATOR==========================&gt;"/>
					</batch:aggregator>
				</batch:step>
				<batch:step name="Batch_Step1" doc:id="87115669-5807-497b-a7b2-13feed7d6061" acceptPolicy="ALL" acceptExpression="payload.age as Number &lt; 18">
					<logger level="INFO" doc:name="Logger" doc:id="87693bd5-27bb-4ebd-9d90-a36490ae8050" message="#[payload]" category="AGE LESS THAN 18==============================&gt;"/>
					<batch:aggregator doc:name="Batch Aggregator" doc:id="b8fdca0c-604c-4651-83b2-6cf23a304344" size="5">
						<logger level="INFO" doc:name="Logger" doc:id="4ee4b6f5-9355-4a6c-b5ed-6c9392234e3e" message="#[payload]" category="AFTER FAILED GGREGATOR=====================================&gt;"/>
					</batch:aggregator>
				</batch:step>
			</batch:process-records>
			<batch:on-complete >
				<logger level="INFO" doc:name="Logger" doc:id="c6c8c167-20f4-4b6b-a29b-d88df67acfd4" message='#[output application/json&#10;---&#10;{&#10;  "message": "Batch processing successfully completed",&#10;  "jobInstanceId": payload.jobInstanceId,&#10;  "totalRecords": payload.totalRecords,&#10;  "loadedRecords": payload.loadedRecords,&#10;  "processedRecords": payload.processedRecords,&#10;  "successfulRecords": payload.successfulRecords,&#10;  "failedRecords": payload.failedRecords,&#10;  "status": if (payload.failedRecords &gt; 0) "COMPLETED_WITH_ERRORS" else "SUCCESS",&#10;  "executionTimeInMillis": payload.elapsedTimeInMillis&#10;}]' category="AFTER ON COMPLETE==================================&gt;"/>
				<ee:transform doc:name="Transform Message" doc:id="a7722b74-e9f1-46b5-9761-0d381366e1e9" >
					<ee:message >
						<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
{
  "message": "Batch processing successfully completed",
  "jobInstanceId": payload.jobInstanceId,
  "totalRecords": payload.totalRecords,
  "loadedRecords": payload.loadedRecords,
  "processedRecords": payload.processedRecords,
  "successfulRecords": payload.successfulRecords,
  "failedRecords": payload.failedRecords,
  "status": if (payload.failedRecords > 0) "COMPLETED_WITH_ERRORS" else "SUCCESS",
  "executionTimeInMillis": payload.elapsedTimeInMillis
}]]></ee:set-payload>
					</ee:message>
				</ee:transform>
			</batch:on-complete>
		</batch:job>
	</flow>

 

Anypoint Studio Flow:

After enter the XML in your Anypoint Studio . Your flow will looks like this:

 

Real World Implementation: Scheduled Database to Salesforce with MuleSoft Batch Jobs:

When using batch jobs in production environments it often will be used with additional components. These could include an automated scheduler, object store (watermark) pattern to extract data in batches and a batch aggregator to do bulk actions on systems like Salesforce.

Hands-On Challenge: Synchronising Watermarks Between Database and Salesforce:

  • Challenge: Watermark Sync between Database and Salesforce.
  • Watermarked Incremental Extract: Create a scheduled poll that will extract the last processing time from the Object Store and extract new employee data using a parameterised SQL query.
  • Fault Tolerant Batch Job: Create a Mule 4 Batch Job which will ensure all the data is processed (maxFailedRecords="-1").
  • Security: All sensitive data (DB + Client) should be externalised using dynamic properties. The watermark should only be updated in the Object Store on complete.
  • Batch Aggregator: Convert data from your database to the correct format for your Salesforce custom object. Use a Batch Aggregator (size="100") to do a batch upsert of this data using the Salesforce Connector, based on an external ID.

Architecture Patterns Used:

  • Abstract Secure Properties: Any sensitive data including DB password, host, Salesforce OAuth details and tokens have been moved away from the application XML using Dynamic Property Replacement (e.g. ${db.password}, ${sfdc.clientId}).
  • Delta Sync (Watermark): Rather than extract all data from the table we are extracting the lastUpdated value from the last run from the Object Store. We then query only new/updated data from MySQL.
  • Resilient (maxFailedRecords="-1"): The batch will process all data in each block. If any of the data in the batch is causing an error it will not fail halfway through. This means we get the maximum amount of data through.
  • Bulk Upsert: Data has been batched up using the step aggregator and grouped into blocks of 5. This data is then upsert in bulk using the Salesforce Connector meaning we are using our API as efficiently as possible.
  • Watermark Commit: Our watermark is only committed in the On Complete phase. This means that until all of our current data has been processed our watermark will not be updated.

Production-Ready Configuration XML:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:salesforce="http://www.mulesoft.org/schema/mule/salesforce" 
    xmlns:batch="http://www.mulesoft.org/schema/mule/batch" 
    xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" 
    xmlns:db="http://www.mulesoft.org/schema/mule/db" 
    xmlns:http="http://www.mulesoft.org/schema/mule/http" 
    xmlns:os="http://www.mulesoft.org/schema/mule/os"
    xmlns="http://www.mulesoft.org/schema/mule/core" 
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/batch http://www.mulesoft.org/schema/mule/batch/current/mule-batch.xsd
http://www.mulesoft.org/schema/mule/salesforce http://www.mulesoft.org/schema/mule/salesforce/current/mule-salesforce.xsd
http://www.mulesoft.org/schema/mule/os http://www.mulesoft.org/schema/mule/os/current/mule-os.xsd">
    <!-- Database Global Configuration referencing external properties -->
    <db:config name="Database_Config" doc:name="Database Config">
        <db:my-sql-connection 
            host="${db.host}" 
            port="${db.port}" 
            user="${db.user}" 
            password="${db.password}" 
            database="${db.database}" />
    </db:config>
    <!-- Salesforce Global Configuration referencing external properties -->
    <salesforce:sfdc-config name="Salesforce_Config" doc:name="Salesforce Config">
        <salesforce:oauth-client-credentials-connection>
            <salesforce:oauth-client-credentials 
                clientId="${sfdc.clientId}" 
                clientSecret="${sfdc.clientSecret}" 
                tokenUrl="${sfdc.tokenUrl}" />
        </salesforce:oauth-client-credentials-connection>
    </salesforce:sfdc-config>
    <!-- Object Store Configuration for Watermarking -->
    <os:config name="ObjectStore_Config" doc:name="ObjectStore Config">
        <os:connection>
            <reconnection failsDeployment="true">
                <reconnect />
            </reconnection>
        </os:connection>
    </os:config>
    
    <os:object-store name="Object_store" doc:name="Object store" 
        maxEntries="1000000" 
        entryTtl="3" 
        entryTtlUnit="DAYS" 
        expirationInterval="4" 
        expirationIntervalUnit="DAYS" 
        config-ref="ObjectStore_Config" />
    <!-- Main Scheduled Batch Processing Flow -->
    <flow name="db-to-salesforce-batch-sync-flow">
        <scheduler doc:name="Scheduler">
            <scheduling-strategy>
                <fixed-frequency frequency="${scheduler.frequency}" timeUnit="${scheduler.timeUnit}"/>
            </scheduling-strategy>
        </scheduler>
        
        <os:retrieve doc:name="Retrieve Last Watermark" key="LastUpdateddata" objectStore="Object_store" target="waterMark">
            <os:default-value><![CDATA[${watermark.defaultDate}]]></os:default-value>
        </os:retrieve>
        
        <db:select doc:name="Fetch Incremental Records" config-ref="Database_Config">
            <db:sql><![CDATA[SELECT * FROM project_1 
WHERE lastUpdated > :waterMark
ORDER BY lastUpdated ASC]]></db:sql>
            <db:input-parameters><![CDATA[#[{
    "waterMark": vars.waterMark
}]]]></db:input-parameters>
        </db:select>
        
        <choice doc:name="Check If Records Found">
            <when expression="#[!isEmpty(payload)]">
                <set-variable value='#[payload[-1].lastUpdated as String {format: "yyyy-MM-dd HH:mm:ss"}]' doc:name="Store Newest Timestamp" variableName="originalValue" />
                
                <batch:job jobName="Sync_Batch_Job" blockSize="10" maxFailedRecords="-1">
                    <batch:process-records>
                        <batch:step name="Process_Records_Step" acceptPolicy="ALL">
                            <ee:transform doc:name="Transform to Java Object">
                                <ee:message>
                                    <ee:set-payload><![CDATA[%dw 2.0
output application/java
---
payload]]></ee:set-payload>
                                </ee:message>
                            </ee:transform>
                            
                            <batch:aggregator doc:name="Bulk Aggregator" size="100">
                                <ee:transform doc:name="Map to Salesforce Schema">
                                    <ee:message>
                                        <ee:set-payload><![CDATA[%dw 2.0
output application/java
---
payload map (item) -> {
   "Employee_ID__c": item.employeeId as Number,
   "Name": item.name,
   "Last_Name__c": item.lastName,
   "Email__c": item.email,
   "Phone__c": item.phone,
   "Department__c": item.department,
   "City__c": item.city,
   "Salary__c": item.salary,
   "Joining_Date__c": item.joiningDate as Date
}]]></ee:set-payload>
                                    </ee:message>
                                </ee:transform>
                                
                                <salesforce:upsert doc:name="Upsert to Salesforce" config-ref="Salesforce_Config" objectType="Employee__c" externalIdFieldName="Employee_ID__c"/>
                                <logger level="INFO" doc:name="Log Batch Upsert" message='#[write(payload, "application/json")]' category="AFTER SFDC UPSERT"/>
                            </batch:aggregator>
                        </batch:step>
                    </batch:process-records>
                    
                    <batch:on-complete>
                        <os:store doc:name="Update Watermark" key="LastUpdateddata" objectStore="Object_store">
                            <os:value><![CDATA[#[vars.originalValue]]]></os:value>
                        </os:store>
                        <logger level="INFO" doc:name="Log Completion" message='#[write(payload, "application/json")]' category="BATCH COMPLETE"/>
                    </batch:on-complete>
                </batch:job>
            </when>
            <otherwise>
                <logger level="INFO" doc:name="Log No Data" message='#["No updated records found since last run."]' category="NO UPDATE"/>
            </otherwise>
        </choice>
    </flow>
</mule>

 

Anypoint Studio Flow:

After entering the XML in your Anypoint Studio I the flow will looks like this:

 

Watch And Learn:

Prefer watching over reading? In this video, I break down the exact flow from this blog step-by-step—explaining what each Batch Job, Step, and Aggregator setting does, why I configured it that way, and how to debug the execution through live console logs to see Mule's batch threading in action.

 

Conclusion:

I hope this blog has given you a good understanding of how to implement Batch Processing into MuleSoft. We have now learnt about some key concepts in Batch Processing (Batch Jobs, Steps & Aggregators) and implemented an enterprise level scheduled database sync into Salesforce. The research behind this document is to help improve your integration skills and ensure you are not confused by the documentation. In upcoming blogs, I will be providing further practical examples of architectures, patterns and deep dives so make sure to stay tuned!


free-consultation