Skip to content

Scatter-gather Flow Control

Ballerina is an open-source programming language that empowers developers to integrate their system easily with the support of connectors.

Scatter-Gather is an integration pattern where a request is sent to multiple recipients and each of the responses are aggregated and returned back to the client as a single response. This guide demonstrates a simple scatter-gather scenario where two files in an FTP location are read simultaneously, their contents aggregated and sent back to the client.

What you'll build

We create service employeeDetails which accepts a client request and reads two different CSV files with employee details from an FTP server. It then converts the responses of each read to json, aggregates both the json and sends back to the client.


Before you begin

  • Download and install Ballerina Integrator for your operating system

    Note: This installs Ballerina language version 1.0.1, a compiler plugin to help mitigate errors, and snippet .jar files for custom auto-completion.

  • Install Oracle JDK 1.8.*
  • Install VS Code

    Tip: For a better development experience, use VS Code (which is the recommended editor for Ballerina Integrator).

  • Install the Ballerina Integrator Extension from the VS Code marketplace
  • An FTP Server

Get the code

You can download the ZIP file and extract the contents to get the project code.

Download ZIP


  • Create a new Ballerina project named scatter-gather-flow.
$ ballerina new scatter-gather-flow
  • Navigate to the scatter-gather-flow directory.

  • Add a new module named scatter_gather_flow to the project.

$ ballerina add scatter_gather_flow
  • Open the project with VS Code. The project structure will be similar to the following.

├── Ballerina.toml
└── src
   └── scatter_gather_flow
      ├── main.bal
      ├── resources
      │   └── ballerina.conf
      └── tests
            ├── main_test.bal
            └── resources
We can remove the file main_test.bal for the moment, since we are not writing any tests for our service.

  • Now let's create a file called ballerina.conf under the root path of the project structure. The file should have the following configurations.
FTP_HOST = "<ftp_host>"
FTP_PORT = <port>
FTP_USER = "<username>"
FTP_PASSWORD = "<password>"

The username and password are sensitive data. Therefore those should not be hard-coded. Ballerina supports encrypting sensitive data and uses them in the program.

$ ballerina encrypt

The execution of the encrypt action will ask for value and secret key. Once you provide input, it'll output the encrypted value that can directly be used in the config file.

Enter value:

Enter secret:

Re-enter secret to verify:

Add the following to the configuration file:

Or provide it as a command line argument:

Now we can use the encrypted value in the ballerina.conf file.

FTP_USER = "@encrypted:{aoIlSvOPeBEZ0COma+Wz2uWznlNn1IWz4StiWQCO6g4=}"
FTP_PASSWORD = "@encrypted:{aoIlSvOPeBEZ0COma+Wz2uWznlNn1IWz4StiWQCO6g4=}"
  • Before writing the service, let's create two CSV files employees1.csv and employees2.csv with the following content and upload to an FTP server.
  • Now open the main.bal file and add the following content. This is going to be our integration logic.


import ballerina/http;
import ballerina/io;
import ballerina/config;
import wso2/ftp;

ftp:ClientEndpointConfig ftpConfig = {
    protocol: ftp:FTP,
    host: config:getAsString("FTP_HOST"),
    port: config:getAsInt("FTP_PORT"),
    secureSocket: {
        basicAuth: {
            username: config:getAsString("FTP_USER"),
            password: config:getAsString("FTP_PASSWORD")
ftp:Client ftpClient = new (ftpConfig);

json[] employees = [];

@http:ServiceConfig {
    basePath: "/organization"
service employeeDetails on new http:Listener(9090) {
    @http:ResourceConfig {
        methods: ["GET"],
        path: "/employees"
    resource function getEmployees(http:Caller caller, http:Request req) {

        fork {
            worker w1 returns io:ReadableByteChannel {
                return checkpanic ftpClient->get("/home/ftp-user/in/employees1.csv");
            worker w2 returns io:ReadableByteChannel {
                return checkpanic ftpClient->get("/home/ftp-user/in/employees2.csv");
        record {io:ReadableByteChannel w1; io:ReadableByteChannel w2;} results = wait {w1, w2};
        http:Response response = new;
        error? respond = caller->respond(response);

//populating the employees json array with employee rows
function populateEmp(io:ReadableByteChannel ch) {
    string[][] employeeRows = convertToStringArray(ch);
    foreach var i in 1 ... employeeRows.length() - 1 {
        json m = convertToJson(employeeRows[i]);
        employees[employees.length()] = <@untainted>m;

//extracting a string array of arrays from a ReadableByteChannel
function convertToStringArray(io:ReadableByteChannel rbChannel) returns @tainted string[][] {
    io:ReadableCharacterChannel characters = new (rbChannel, "utf-8");
    io:ReadableCSVChannel csvChannel = new (characters);
    string[][] rows = [];
    while (csvChannel.hasNext()) {
        string[] currentRow = <string[]> checkpanic csvChannel.getNext();
        rows[rows.length()] = currentRow;
    var closeResult = characters.close();
    return rows;

//converting a string array to required json format
function convertToJson(string[] empRow) returns json {
    json emp = {
        "empId": empRow[0],
        "firstName": empRow[1],
        "lastName": empRow[2],
        "joinedDate": empRow[3]
    return emp;


  • First let’s build the module. While being in the scatter-gather-flow directory, execute the following command.
$ ballerina build scatter_gather_flow

This would create the executables.

  • Now run the .jar file created in the above step.

$ java -jar target/bin/scatter_gather_flow.jar
You will be prompted to enter the secret you used for encrypting the FTP username and password.

ballerina: enter secret for config value decryption:
Now we can see that the service has started on port 9090.

  • Let’s access this service by executing the following curl command.
$ curl http://localhost:9090/organization/employees

We receive a JSON response similar to the following.