MapReduce model

Updated at:

The MapReduce model is a lightweight, distributed batch processing model developed by SchedulerX. It uses the MapJobProcessor or MapReduceJobProcessor interface to organize connected workers into a distributed computing engine for big data batch processing. Compared to traditional big data batch processing on platforms such as Hadoop and Spark, the SchedulerX MapReduce model can process massive amounts of data in seconds without importing the data into a big data platform, and without extra storage or computing costs. It is low-cost, fast, and easy to program.

Notes

  • A single subtask cannot exceed 64 KB in size.

  • The result returned by ProcessResult cannot exceed 1,000 bytes.

  • If you use the reduce method, the results of all subtasks are cached on the master node, causing high memory pressure. Keep the number of subtasks and the size of the returned result small. If you do not need the reduce functionality, use the MapJobProcessor interface.

  • SchedulerX does not guarantee exactly-once execution for subtasks. In certain failover conditions, a subtask may be executed more than once. Your application must handle this by being idempotent.

Interfaces

Extend the MapJobProcessor class

API

Description

Required

public ProcessResult process(JobContext context) throws Exception;

The entry point for executing the business logic of each subtask. You must retrieve the task name from the context to handle the subtask accordingly. After the logic is executed, return a ProcessResult.

Yes

public ProcessResult map(List<? extends Object> taskList, String taskName);

Call the map method to distribute a batch of subtasks across multiple machines for execution. This method can be called multiple times. If taskList is empty, the operation fails. After execution is complete, return a ProcessResult.

Yes

public void kill(JobContext context);

Killing a job in the console triggers this method. You must implement the logic to interrupt your business process.

No

Extend the MapReduceJobProcessor class

API

Description

Required

public ProcessResult process(JobContext context) throws Exception;

The entry point for executing the business logic of each subtask. You must retrieve the task name from the context to handle the subtask accordingly. After the logic is executed, return a ProcessResult.

Yes

public ProcessResult map(List<? extends Object> taskList, String taskName);

Call the map method to distribute a batch of subtasks across multiple machines for execution. This method can be called multiple times. If taskList is empty, the operation fails. After execution is complete, return a ProcessResult.

Yes

public ProcessResult reduce(JobContext context);

After all subtasks on the worker nodes complete execution, the system calls the reduce method. The master node executes this method, which is typically used for data aggregation, notifying downstream services, or passing data within a workflow.

The reduce method can process the results of all subtasks.

  1. A subtask returns a result using return ProcessResult(true, result), for example, to return an order number.

  2. When you execute the reduce method, use context to obtain the statuses (context.getTaskStatuses()) and results (context.getTaskResults()) of all subtasks and perform the required logical processing.

Yes

public void kill(JobContext context);

Killing a job in the console triggers this method. You must implement the logic to interrupt your business process.

No

public boolean runReduceIfFail(JobContext context)

Specifies whether to execute the reduce method if any subtask fails. By default, the reduce method executes even if a subtask fails.

No

Procedure

  1. Log in to the MSE SchedulerX console. In the left-side navigation pane, click Task Management.

  2. On the Task Management page, click Add Task.

  3. In the Add Task panel, select MapReduce from the Execution Mode drop-down list and configure the parameters in the Advanced Configuration section.

    Parameter

    Description

    Distribution Policy

    Note

    Requires client version 1.10.3 or later.

    • Polling Policy (Default): Distributes an equal number of subtasks to each worker. This policy is suitable for scenarios where each subtask takes a similar amount of time to process.

    • Optimal Load Strategy: The master node automatically detects the load on each worker node. This policy is suitable for scenarios where processing times vary significantly across subtasks and worker machines.

    Subtask Concurrency per Node

    The number of concurrent execution threads on a single worker. The default is 5. Increase this value to speed up execution. If downstream systems or your database cannot handle the increased load, you can decrease this value.

    Subtask Failure Retry Count

    The number of times to automatically retry a failed subtask. The default is 0.

    Subtask Failure Retry Interval

    The interval, in seconds, between retry attempts for a failed subtask. The default is 0.

    Failover Policy

    Note

    Requires client version 1.8.12 or later.

    Specifies whether to redistribute subtasks from a failed node to other machines. If you enable this option, subtasks might be re-executed during failover. Your application must therefore be idempotent.

    Execute on Master Node

    Note

    Requires client version 1.8.12 or later.

    Specifies whether the master node participates in subtask execution. There must be at least two online workers. Disable this option when the number of subtasks is very large.

    Subtask Distribution Method

    • Push model: Subtasks are evenly distributed to each machine.

    • Pull model: Each machine actively pulls subtasks. This model avoids bottlenecks caused by slower workers and supports dynamic scaling. During this process, all subtasks are cached on the master node, increasing memory pressure. We recommend that the number of subtasks does not exceed 10,000.

    For information about other configuration items, see Advanced configuration parameters for job management.

Principles and best practices

How SchedulerX 2.0 distributed computing works and its best practices

Examples

Single table, continuous IDs

  1. The root task reads the minimum and maximum IDs.

    select min(id), max(id) from Tab1;
  2. Paginate the data based on the ID range. Each task contains a startId and an endId field.

  3. Each task retrieves data using its ID range.

    select * from Tab1 where id >= startId and id < endId;

The following is a code example:

class PageTask {
    private long startId;
    private long endId;

    public PageTask(long startId, long endId) {
        this.startId = startId;
        this.endId = endId;
    }

    public long getStartId() {
        return startId;
    }

    public long getEndId() {
        return endId;
    }
}
@Component
public class ScanSingleTableJobProcessor extends MapJobProcessor {

    @Autowired
    private XXXService xxxService;

    private final int PAGE_SIZE = 500;

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        // Multiple jobs can share the same backend code. Configure job parameters in the console to represent the table name.
        String tableName = context.getJobParameters(); 
        String taskName = context.getTaskName();
        Object task = context.getTask();
        if (isRootTask(context)) {
            Pair<Long, Long> idPair = queryMinAndMaxId(tableName);
            long minId = idPair.getFirst();
            long maxId = idPair.getSecond();
            List<PageTask> tasks = Lists.newArrayList();
            // Calculate the step size.
            int step = (int) ((maxId - minId) / PAGE_SIZE); 
            if (step > 0) {
                for (long i = minId; i < maxId; i+=step) {
                    tasks.add(new PageTask(i, (i+step > maxId ? maxId : i+step)));
                }
            } else {
                tasks.add(new PageTask(minId, maxId));
            }
            return map(tasks, "PageTask");
        } else if (taskName.equals("PageTask")) {
            PageTask pageTask = (PageTask)task;
            long startId = pageTask.getStartId();
            long endId = pageTask.getEndId();
            List<Record> records = queryRecord(tableName, startId, endId);
            //TODO handle records
            return new ProcessResult(true);
        }

        return new ProcessResult(false);
    }

    private Pair<Long, Long> queryMinAndMaxId(String tableName) {
        //TODO select min(id),max(id) from [tableName]
        return new Pair<Long, Long>(1L, 10000L);
    }

    private List<Record> queryRecord(String tableName, long startId, long endId) {
        List<Record> records = Lists.newArrayList();
        //TODO select * from [tableName] where id>=[startId] and id<[endId]
        return records;
    }

}

Single table, non-continuous IDs

  1. Use a bucketing policy for the database and add a bucket field as an index.

  2. For example, with 1,024 buckets, you can hash an order ID or another ID when a new record is added. The result of the hash, for example, order_id % 1024, determines the value for the bucket field.

  3. Data is typically distributed evenly across the buckets. You can query all data for a specific bucket using the following SQL statement:

    select * from Tab1 where bucket=xxx;

The following is a code example:

@Component
public class ScanSingleTableJobProcessor extends MapJobProcessor {

    @Autowired
    private XXXService xxxService;

    private final int PAGE_SIZE = 500;

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        // Multiple jobs can share the same backend code. Configure job parameters in the console to represent the table name.
        String tableName = context.getJobParameters(); 
        String taskName = context.getTaskName();
        Object task = context.getTask();
        if (isRootTask(context)) {
            List<Integer> tasks = Lists.newArrayList();
            for (int i = 0; i< 1024; i++) {
                tasks.add(i);
            }    
            return map(tasks, "BucketTask");
        } else if (taskName.equals("BucketTask")) {
            int bucketId = (int)task;
            List<Record> records = queryRecord(tableName, bucketId);
            //TODO handle records
            return new ProcessResult(true);
        }

        return new ProcessResult(false);
    }

    private List<Record> queryRecord(String tableName, int bucketId) {
        List<Record> records = Lists.newArrayList();
        //TODO select * from #{tableName} where bucket= #{bucketId}
        return records;
    }

}

Sharded databases and tables

class PageTask {
    private String tableName;
    private long startId;
    private long endId;

    public PageTask(String tableName, long startId, long endId) {
        this.tableName = tableName;
        this.startId = startId;
        this.endId = endId;
    }

    public String getTableName() {
        return tableName;
    }

    public long getStartId() {
        return startId;
    }

    public long getEndId() {
        return endId;
    }
}
@Component
public class ScanShardingTableJobProcessor extends MapJobProcessor {

    @Autowired
    private XXXService xxxService;

    private final int PAGE_SIZE = 500;

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        String taskName = context.getTaskName();
        Object task = context.getTask();
        if (isRootTask(context)) {
            // Create tasks for each database shard.
            List<String> dbList = getDbList();
            return map(dbList, "DbTask");
        } else if (taskName.equals("DbTask")) {
            // For each database shard, create tasks for each table shard.
            String dbName = (String)task;
            List<String> tableList = getTableList(dbName);
            return map(tableList, "TableTask");
        } else if (taskName.equals("TableTask")) {
            // If a table shard is large, create paginated tasks for it.
            String tableName = (String)task;
            Pair<Long, Long> idPair = queryMinAndMaxId(tableName);
            long minId = idPair.getFirst();
            long maxId = idPair.getSecond();
            List<PageTask> tasks = Lists.newArrayList();
            // Calculate the step size.
            int step = (int) ((maxId - minId) / PAGE_SIZE); 
            if (step > 0) {
                for (long i = minId; i < maxId; i+=step) {
                    tasks.add(new PageTask(tableName, i, (i+step > maxId ? maxId : i+step)));
                }
            } else {
                tasks.add(new PageTask(tableName, minId, maxId));
            }
            return map(tasks, "PageTask");
        } else if (taskName.equals("PageTask")) {
            PageTask pageTask = (PageTask)task;
            String tableName = pageTask.getTableName();
            long startId = pageTask.getStartId();
            long endId = pageTask.getEndId();
            List<Record> records = queryRecord(tableName, startId, endId);
            //TODO handle records
            return new ProcessResult(true);
        }

        return new ProcessResult(false);
    }

    private List<String> getDbList() {
        List<String> dbList = Lists.newArrayList();
        //TODO Return the list of sharded databases.
        return dbList;
    }

    private List<String> getTableList(String dbName) {
        List<String> tableList = Lists.newArrayList();
        //TODO Return the list of sharded tables.
        return tableList;
    }

    private Pair<Long, Long> queryMinAndMaxId(String tableName) {
        //TODO select min(id),max(id) from [tableName]
        return new Pair<Long, Long>(1L, 10000L);
    }

    private List<Record> queryRecord(String tableName, long startId, long endId) {
        List<Record> records = Lists.newArrayList();
        //TODO select * from [tableName] where id>=[startId] and id<[endId]
        return records;
    }

}

Process 50 messages and return a result from reduce

@Component
public class TestMapReduceJobProcessor extends MapReduceJobProcessor {

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        String taskName = context.getTaskName();
        int dispatchNum=50;
        if (isRootTask(context)) {
            System.out.println("start root task");
            List<String> msgList = Lists.newArrayList();
            for (int i = 0; i <= dispatchNum; i++) {
                msgList.add("msg_" + i);
            }
            return map(msgList, "Level1Dispatch");
        } else if (taskName.equals("Level1Dispatch")) {
            String task = (String)context.getTask();
            System.out.println(task);
            return new ProcessResult(true);
        }

        return new ProcessResult(false);
    }

    @Override
    public ProcessResult reduce(JobContext context) throws Exception {
        return new ProcessResult(true, "TestMapReduceJobProcessor.reduce");
    }

}

Process 50 messages and aggregate subtask results in reduce

@Component
public class TestMapReduceJobProcessor extends MapReduceJobProcessor {

    @Override
    public ProcessResult process(JobContext context) throws Exception {
        String taskName = context.getTaskName();
        int dispatchNum = 50; // The number of messages to dispatch.
        if (context.getJobParameters() != null) {
            dispatchNum = Integer.valueOf(context.getJobParameters());
        }
        if (isRootTask(context)) {
            System.out.println("start root task");
            List<String> msgList = Lists.newArrayList();
            for (int i = 0; i <= dispatchNum; i++) {
                msgList.add("msg_" + i);
            }
            return map(msgList, "Level1Dispatch");
        } else if (taskName.equals("Level1Dispatch")) {
            String task = (String)context.getTask();
            Thread.sleep(2000);
            return new ProcessResult(true, task);
        }

        return new ProcessResult(false);
    }

    @Override
    public ProcessResult reduce(JobContext context) throws Exception {
        for (Entry<Long, String> result : context.getTaskResults().entrySet()) {
            System.out.println("taskId:" + result.getKey() + ", result:" + result.getValue());
        }
        return new ProcessResult(true, "TestMapReduceJobProcessor.reduce");
    }
}