Moleculer Microservices Framework

0.15.0 · active · verified Sun Apr 19

Moleculer is a fast, modern, and powerful microservices framework for Node.js, designed to build efficient, reliable, and scalable distributed systems. It provides a comprehensive set of features including a promise-based request-reply mechanism, event-driven architecture, dynamic service discovery, load balancing, and fault tolerance capabilities like Circuit Breaker and Retry. The current stable version is 0.15.0, with frequent minor and patch releases, and major updates approximately annually, often introducing significant breaking changes. Key differentiators include its pluggable architecture for transporters (e.g., NATS, Redis, Kafka), serializers (e.g., MsgPack, CBOR), caching, loggers, and metrics/tracing reporters. It emphasizes a master-less architecture, making all nodes equal, and comes with built-in parameter validation and extensive TypeScript support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic Moleculer service, define actions and events, start the service broker, and then call an action and emit an event.

import { ServiceBroker, ServiceSchema } from 'moleculer';

// Create a ServiceBroker
const broker = new ServiceBroker({
  nodeID: 'node-greeter-1',
  logLevel: 'info',
  transporter: 'NATS' // Or 'Redis', 'TCP', etc.
});

// Define a Greeter Service
const GreeterService: ServiceSchema = {
  name: 'greeter',
  settings: {
    defaultName: 'World'
  },
  actions: {
    hello: {
      rest: 'GET /hello',
      async handler(ctx) {
        return `Hello ${ctx.params.name || this.settings.defaultName}`;
      }
    },
    welcome: {
      async handler(ctx) {
        this.logger.info(`Welcoming ${ctx.params.name}...`);
        return `Welcome, ${ctx.params.name}`;
      }
    }
  },
  events: {
    'user.created': {
      async handler(ctx) {
        this.logger.info(`User created event received for ${ctx.params.username}`);
      }
    }
  },
  async started() {
    this.logger.info(`Greeter service started on node ${broker.nodeID}`);
  },
  async stopped() {
    this.logger.info(`Greeter service stopped on node ${broker.nodeID}`);
  }
};

// Create a service from the schema
broker.createService(GreeterService);

// Start the broker
broker.start()
  .then(async () => {
    // Call an action
    const res = await broker.call('greeter.hello', { name: 'Moleculer' });
    console.log(res);

    // Emit an event
    await broker.emit('user.created', { username: 'Alice' });

    // Call an action from another node if available (assuming multiple nodes)
    const welcomeMsg = await broker.call('greeter.welcome', { name: 'Bob' });
    console.log(welcomeMsg);

    // Stop the broker after a delay or on signal
    setTimeout(() => broker.stop(), 5000);
  })
  .catch(err => {
    broker.logger.error('Error starting broker:', err);
  });

view raw JSON →