NODE.JS · WORKER BROKER

Build a worker system with RedLine

A practical walkthrough of the project structure shown in the examples: configure a broker, define the code that runs inside each worker, then subscribe to a message and consume its result.

1.1 Overview

RedLine is used here to move work out of the normal request-handling flow. Your application sends a message, the broker routes it to a worker, and the worker executes the task.

The key idea is to keep these responsibilities separate:

  • Your application / controller: decides when a job should be requested.
  • Broker: manages the worker group and message delivery.
  • Worker: runs the task logic and sends a result back.
Follow the order in this guide. First create the broker, then define the worker program, and finally connect the application code to the broker.

1.2 Requirements

  • Node.js with ES modules enabled.
  • A project that can install npm packages.
  • The nahdi-redline package used by the examples.
npm install nahdi-redline

These examples document the API names and usage visible in the supplied code. Check the package's current README for any version-specific options.

2. Architecture

2.1 Main components

ApplicationRoute / controller
subscribe / job
BrokerWorker manager
dispatch
WorkerExecutes task

When the worker finishes, it sends a message containing the original job data and its status. The broker-facing application code can receive that data through the consumer callback shown later.

2.2 Project structure

Create the following structure. The workers/ directory is generated by the worker-spawning method in this example; you do not need to write each generated worker file by hand.


my-app/
│
├── workers/ # generated at runtime
│   ├── worker-quee.js
│   ├── worker1.js
│   ├── worker2.js
│   └── ...
│
└── server1/
    │
    ├── worker-templates/
    │   └── templates.js
    │
    ├── controller/
    │   └── test.controller.js
    │
    ├── config-Broker/
    │   └── config.js
    │
    ├── routes/
    │   └── test.route.js
    │
    ├── package.json
    │
    └── server.js
Folder naming: keep worker-templates for the worker program/template, and config-Broker for the broker instance. The generated workers folder is an output of your setup.

2.3 Runtime lifecycle

  1. Broker setup: create one broker instance and tell it how many workers to start.
  2. Worker definition: type your logic inside templates.js and call MethodespawnWorkers() to create/start the worker processes, according to the package implementation.
  3. Message registration: register the message type with yourinstance.subscribe().
  4. Result handling: use yourinstance.consume() to receive worker responses.

3. Build the system step by step

Each step below tells you exactly which file to open and what belongs there.

01

Create the folders

Terminal · project root

Start with the server1 folder and create the three source folders used by this example:

mkdir -p my-application/server
cd my-application

After setting up your Node.js project...


my-app/
└── server1/
  ├── controller/
  │  └── test.controller.js
  ├── routes/
  │  └── test.route.js
  ├── package.json
  └── server.js
02

Configure the broker

File · server1/config-Broker/config.js

This file creates the broker instance. In this example, it is configured to manage five workers. The spawnWorkers value names the directory used for the worker files.

import  { Broker } from  "nahdi-redline"  ;

export   const   BrokersImage =  new  Broker({
  numberOfWorkers: 5,
  spawnWorkers: "workers",
  title:"worker"

});
What each option means in your example
  • numberOfWorkers: 5 — requests a group of five workers.
  • spawnWorkers: "workers" — supplies the worker directory name.
  • title: "worker" — supplies the worker title/prefix used by your package.
03

Define the worker logic

File · server1/worker-templates/templates.js

This is the important part: write the function that will run inside a worker. The imports array lists dependencies that the generated worker code needs. The worker listens for an IPC message, performs the task, and sends a completion or failure response to its parent process.

import { BrokersImage } from "../config-Broker/config.js";
let imports = [
  "import sendResponse from ./sendResponse.js"
  //.. import your lib here

]

function main() {

  process.on("message", async (stream) => {
    try {

      console.log(`ID operation: ${stream.id}`);
      // do  your logique here

      sendResponse(stream, {
        status: "Completed",
        result:{
          // send whatever you want data here the most important thing inside object  called result
          data : "hello",
          array : [12,4]
        }
      })

    } catch (err) {

      sendResponse(stream, {
        status: "failed",

      })


    }
  });
  process.on("disconnect", () => {
    console.log("Parent disconnected from worker");
  });

}
BrokersImage.MethodespawnWorkers(main.toString(), imports)

After writing or modifying the code, run the following command: node templates.js Whenever you make any changes to the code or update the logic, you must run node templates.js again to ensure that all changes are applied and the output is up to date.

Why is the function converted to a string? Your code passes main.toString() to the spawning method. This indicates that the package uses the function's source as part of preparing worker files. The imports array supplies imports needed by that worker code. Confirm the exact generated-file behavior against the package implementation.
04

Subscribe to a message and consume results

File · server1/controller/test.controller.js

Import the broker instance created in step 02. Register a consumer callback to handle data returned by workers, then subscribe to the message name that should be handled.

import { BrokersImage } from "../config-Broker/config.js";

BrokersImage.consume((data) => {
  console.log("Worker response:", data);
});

const testcontroller = (req, res) => {
  BrokersImage.subscribe({
    message: "foo:job"
  });

  res.status(200).json({
    message: "test ok"
  });
};

export default testcontroller;
Understand the two calls
  • consume(callback) — your callback receives data returned through the broker.
  • subscribe({ message: "foo:job" }) — registers the message name used by this example.
Important: the supplied example calls subscribe() inside the controller. If that controller runs for every HTTP request, it may register the same subscription repeatedly. If the package expects subscriptions to be registered once, move the subscription to application startup. Verify this behavior with the package's API before deploying.
05

Connect the controller to a route

File · server1/routes/test.routes.js (example)

The route connects an HTTP endpoint to the controller. This is the usual Express-style separation: route selects the controller; controller interacts with the broker.

import { Router } from "express";
import testcontroller from "../controller/test.controller.js";

const router = Router();

router.get("/test", testcontroller);

export default router;

Then mount that router in your server.js using your application's normal Express setup.

4. Reference

4.1 Message lifecycle

The worker receives a message object named stream. contain your data send it by BrokersImage.subscribe({ message: "foo:job" }) and do the operation and sends the fields back with a status and result.

// Example response sent by the worker
ID operation: #024113214
{
    id:  '#024113214' ,
    status: 'Completed'  ,
    result: {
    foo:  'ff',
    arr: [ 1, 24, 43 ],
    big: [ [Object] ],
    img: 'http://content.png'
   }
}

4.2 Important notes

  • Do not put task code in config-Broker. That file configures the broker.
  • Put task code in main(). This function is the worker-side logic.
  • Do not manually duplicate five worker files if MethodespawnWorkers() generates them for you.
  • Keep message names consistent. The name subscribed to by the application must match the message-routing convention expected by your package.
Remember the separation: config.js configures the broker → config-routes/config.js defines worker behavior → controller/ uses the broker → routes/ exposes the controller to HTTP.