Cloud Native 11 min read

Service Registry in Microservices: Registration and Discovery Patterns

This article explains how a service registry works in microservice architectures, covering self‑registration and third‑party registration, client‑side and server‑side discovery, and provides practical Node.js code examples and a systemd unit for managing service registration.

Architects Research Society
Architects Research Society
Architects Research Society
Service Registry in Microservices: Registration and Discovery Patterns

Service Registry

A service registry is a database that stores information about how to route requests to microservice instances. Interaction with the registry can be grouped into two main categories, each with two sub‑categories.

Microservice‑to‑Registry Interaction (Registration)

Self‑registration

Third‑party registration

Client‑to‑Registry Interaction (Discovery)

Client‑side discovery

Server‑side discovery

Registration

In evolving microservice architectures, services are added, updated, deprecated, or removed, so the registry must stay in sync with endpoint changes. Registration is the process by which a service publishes or updates its contact information.

Self‑registration forces a microservice to interact directly with the registry when it starts or stops, reporting its availability and metadata. Although it may appear as an anti‑pattern for complex systems, it works well for simple deployments.

Third‑party registration is common in the industry. A dedicated process or service polls or watches running microservice instances and updates the registry automatically, often using tools such as Apache ZooKeeper or Netflix Eureka. Additional data can be supplied via per‑service configuration files, enabling policies like automatic fail‑over, load‑driven scaling, or VM provisioning.

Discovery

Discovery is the counterpart to registration from the client’s perspective: a client must locate the service’s address and related request metadata before invoking it.

Client‑side discovery requires the client to query a discovery service before each request, adding complexity such as load‑balancing, authentication, and endpoint management. However, it avoids embedding discovery logic in the API gateway.

Server‑side discovery lets the API gateway resolve the correct endpoint for a request, which is useful in larger architectures. The gateway can also cache discovery results to reduce latency, though cache invalidation logic is implementation‑specific.

Example: Registry Service

We extend a simple Node.js API‑gateway example with two registration approaches:

A lightweight registration library that microservices can embed for self‑registration.

A systemd unit that performs third‑party registration on service start/stop.

Registration Library (Node.js)

The core logic of the library is shown below.

module.exports.register = function(service, callback) {
  if (!validateService(service)) {
    callback(new Error("Invalid service"));
  }
  findExisting(service.name, function(err, found) {
    if (found) {
      callback(new Error("Existing service"));
      return;
    }
    var dbService = new Service({
      name: service.name,
      url: service.url,
      endpoints: service.endpoints,
      authorizedRoles: service.authorizedRoles
    });
    dbService.save(function(err) {
      callback(err);
    });
  });
};

module.exports.unregister = function(name, callback) {
  findExisting(name, function(err, found) {
    if (!found) {
      callback(new Error("Service not found"));
      return;
    }
    found.remove(function(err) {
      callback(err);
    });
  });
};

Microservices invoke registry.register(...) on start and registry.unregister(...) on graceful shutdown.

Startup Code

// Standalone server setup
var port = process.env.PORT || 3001;
http.createServer(app).listen(port, function (err) {
  if (err) {
    logger.error(err);
  } else {
    logger.info('Listening on http://localhost:' + port);
    if (process.env.SELF_REGISTRY) {
      registry.register({
        name: serviceName,
        url: '/tickets',
        endpoints: [{
          type: 'http',
          url: 'http://127.0.0.1:' + port + '/tickets'
        }],
        authorizedRoles: ['tickets-query']
      }, function(err) {
        if (err) {
          logger.error(err);
          process.exit();
        }
      });
    }
  }
});

Shutdown Code

function exitHandler() {
  if (process.env.SELF_REGISTRY) {
    registry.unregister(serviceName, function(err) {
      if (err) {
        logger.error(err);
      }
      process.exit();
    });
  } else {
    process.exit();
  }
}
process.on('exit', exitHandler);
process.on('SIGINT', exitHandler);
process.on('SIGTERM', exitHandler);
process.on('uncaughtException', exitHandler);

Third‑Party Registration with systemd

For the gateway example that reads service data from MongoDB, a systemd unit can insert and remove service records using the MongoDB CLI.

[Unit]
Description=Sample tickets query microservice
#After=network.target

[Service]
#User=seba
Environment="MONGO_URL=mongodb://127.0.0.1:27018/test"
ExecStart=/usr/bin/node /home/seba/Projects/Ingadv/Auth0/blog-code/microservices/server.js
ExecStartPost=/usr/bin/mongo --eval 'db.services.insert({"name":"Tickets Query Service","url":"/tickets","endpoints":[{"type":"http","url":"http://127.0.0.1:3001/tickets"}],"authorizedRoles":["tickets-query"]})' 127.0.0.1:27017/test
ExecStopPost=/usr/bin/mongo --eval 'db.services.remove({"name":"Tickets Query Service"})' 127.0.0.1:27017/test

[Install]
WantedBy=default.target

The ExecStartPost and ExecStopPost commands call the MongoDB client to add or remove the service entry.

Using Auth0 for Microservice Security

JWT‑based authentication with Auth0 can protect microservice endpoints. The following snippet shows how to configure Express with express‑jwt using Auth0 credentials.

var express = require('express');
var app = express();
var jwt = require('express-jwt');
var jwtCheck = jwt({
  secret: new Buffer('your-auth0-client-secret', 'base64'),
  audience: 'your-auth0-client-id'
});
app.use('/api/path-you-want-to-protect', jwtCheck);
// (...)

Developers can obtain the client ID and secret from the Auth0 dashboard.

Conclusion

The service registry is a critical component of microservice‑based architectures. Various registration and discovery strategies suit different levels of architectural complexity; consider their trade‑offs before committing. The next part will explore service dependencies and effective management techniques.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendMicroservicesservice discoveryNode.jsservice registrysystemd
Architects Research Society
Written by

Architects Research Society

A daily treasure trove for architects, expanding your view and depth. We share enterprise, business, application, data, technology, and security architecture, discuss frameworks, planning, governance, standards, and implementation, and explore emerging styles such as microservices, event‑driven, micro‑frontend, big data, data warehousing, IoT, and AI architecture.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.