Moleculer Documentation

repository·master·Indexed 27 days ago

https://github.com/moleculerjs/moleculer

A fast and powerful microservices framework for Node.js designed for building efficient, reliable, and scalable services. It features a master-less architecture, request-reply and event-driven patterns, built-in fault tolerance (Circuit Breaker, Bulkhead, Retry), and a pluggable ecosystem for transporters, serializers, loggers, and tracing exporters like Jaeger and Zipkin.

Tokens
19K
Snippets
58
Records
119
Agent score
86%

What's inside Moleculer

  1. Overview of Moleculer features

    master

    Moleculer is a fast, modern microservices framework for Node.js. Key features include:

    • Architecture: Request-reply concept, event-driven architecture with balancing, and a master-less architecture where all nodes are equal.
    • Service Management: Built-in service registry, dynamic service discovery, and support for versioned services and service mixins.
    • Fault Tolerance: Built-in Circuit Breaker, Bulkhead, Retry, Timeout, and Fallback.
    • Scalability: Load balanced requests & events (round-robin, random, cpu-usage, latency, sharding).
    • Pluggable Ecosystem:
      • Transporters: TCP, NATS, MQTT, Redis, Kafka, AMQP 0.9, AMQP 1.0.
      • Serializers: JSON, JSONExt, MsgPack, CBOR, Notepack.
      • Loggers: Console, File, Pino, Bunyan, Winston, Debug, Datadog, Log4js.
      • Caching: Memory, MemoryLRU, Redis.
      • Metrics Reporters: Console, CSV, Datadog, Event, Prometheus, StatsD.
      • Tracing Exporters: Console, Datadog, Event, Jaeger, Zipkin, NewRelic.
    • Other Features: Promise-based (async/await), built-in parameter validation (using fastest-validator), and support for Node.js Streams.
  2. Update event handler signature to use Context

    master

    The legacy event handler signature (payload, sender, eventName) has been removed. You must now use the Context based signature. Access payload via ctx.params, the sender via ctx.nodeID, metadata via ctx.meta, and the event name via ctx.eventName.

    module.exports = {
        name: "accounts",
        events: {
            "user.created"(
                ctx
            ) {
                console.log("Payload:", ctx.params);
                console.log("Sender:", ctx.nodeID);
                console.log("We have also metadata:", ctx.meta);
                console.log("The called event name:", ctx.eventName);
    
                // ...
            }
        }
    };
  3. Use the new Action Streaming API

    master

    Action streaming has been rewritten. The Stream instance is no longer passed in ctx.params.

    Sending a stream: Pass the stream in the calling options under the stream property. This allows ctx.params to be used for regular action parameters.

    Receiving a stream: Access the stream directly via ctx.stream instead of ctx.params.

    // Sending a stream
    ctx.call("file.save", { filename: "as.txt" }, { stream: fs.createReadStream() });
    
    // Receiving a stream
    // file.service.js
    module.exports = {
        name: "file",
        actions: {
            save(ctx) {
                const stream = ctx.stream;
                const s = fs.createWriteStream(ctx.params.filename);
                stream.pipe(s);
            }
        }
    };
  4. Register middlewares using the broker options

    master

    The broker.use method is deprecated and removed in version 0.14.x. Instead of calling broker.use(middleware), define middlewares within the middlewares array in your broker configuration object.

    // moleculer.config.js
    module.exports = {
        middlewares: [
            myMiddleware1,
            myMiddleware2,
        ]
    };
  5. Inspect and profile in Chrome

    master

    You can use the Chrome DevTools to inspect and profile your Node.js application by starting it with the --inspect flag. Adding --expose-gc allows you to manually trigger garbage collection from the inspector.

    node --inspect --expose-gc benchmark/perf-runner.js
  6. Profile NodeJS applications using built-in profiler

    master

    You can use the built-in Node.js profiler to identify performance bottlenecks. This involves running your application with the --prof flag to generate an isolate log file, and then processing that file into a human-readable text format.

    1. Run your application in profiler mode: node --prof main.js This generates a file named something like isolate-0xnnnnnnnnnnnn-v8.log.

    2. Convert the isolate file to text: node --prof-process isolate-0xnnnnnnnnnnnn-v8.log > processed.txt

    $ node --prof main.js
    $ node --prof-process isolate-0xnnnnnnnnnnnn-v8.log > processed.txt
  7. Use IR Hydra for V8 tracing

    master

    IR Hydra provides deep insights into V8's internal processes. You can run it using the following command structure to trace hydrogen, phases, and de-optimizations while redirecting code traces to an assembly file.

    $ node --trace-hydrogen --trace-phase=Z --trace-deopt --code-comments --hydrogen-track-positions --redirect-code-traces --redirect-code-traces-to=code.asm index.js
  8. Run Jaeger for trace exporting

    master

    To use Jaeger as a trace exporter for Moleculer, you can run the Jaeger all-in-one image using Docker. This exposes the necessary ports for receiving traces and provides a web UI for visualization.

    UI Access: http://<docker-ip>:16686/

    docker run -d --name jaeger -p 5775:5775/udp -p 6831:6831/udp -p 6832:6832/udp -p 5778:5778 -p 16686:16686 -p 14250:14250 -p 14268:14268 -p 14269:14269 jaegertracing/all-in-one:latest