
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
microstream-client
Advanced tools
The client library for Microstream, a lightweight, real-time communication library for microservices. Replace REST/gRPC with WebSockets for event-driven messaging. Simplifies inter-service communication with a request-response pattern and automatic reconnection.
Author: Arijit Banerjee
License: MIT
MicroStream simplifies communication between microservices using a centralized hub-and-spoke architecture, also known as a star network. In this model, the MicroStream Hub acts as the central communication point, and your microservices, equipped with the MicroStream Client, connect to the Hub and communicate through it.
Here's how it works:
Imagine a star:
In this setup:
Service Registration:
Request-Response Communication in Real-Time:
Auto-Discovery:
Heartbeat Mechanism:
Late Response Handling:
MicroStream is designed to make microservice communication simple, efficient, and scalable. Here’s why you’ll love it:
npm install microstream-client
const { MicrostreamClient } = require("microstream-client");
// Create a new MicrostreamClient instance with the necessary configuration
const client = new MicrostreamClient({
hubUrl: "http://localhost:3000", // URL of the Microstream Hub
serviceName: "auth-service", // Name of your service - it has to be unique
logLevel: "debug", // Enable debug logs
});
// Register a handler for incoming requests for event 'authenticate'
client.onRequest("authenticate", (data) => {
console.log("Received authentication request:", data);
return { success: true, token: "sample-token" }; // Respond to the request
});
// Register another handler for incoming request for another event
client.onRequest("another-event", (data) => {
console.log("Received another-event request:", data);
return { success: true, data: "sample-data" }; // Respond to the request
});
// Send a request to 'jwt-service' and handle the response
try {
const response = await client.sendRequest("jwt-service", "generate_jwt", {
userID: 123,
});
console.log("Received response:", response);
} catch (error) {
console.log("Error:", error.message);
}
// Send a request to 'profile-service' and handle the response
try {
const response = await client.sendRequest(
"profile-service",
"fetch-profile-by-userID",
{ userID: 123 }
);
console.log("Received response:", response);
} catch (error) {
console.log("Error:", error.message);
}
// Example of late response handling
try {
const response = await client.sendRequest(
"jwt-service",
"generate_jwt",
{ userId: 123 },
true, // Allow late responses
(error, res) => {
if (error) {
console.log("Late response error:", error.message);
} else {
console.log("Late response received:", res);
}
}
);
console.log("Received response:", response);
} catch (error) {
console.log("Error:", error.message);
}
MicrostreamClient is configured with the URL of the Microstream Hub, the unique registration name of your service, and the log level.onRequest method is used to register a handler for incoming requests. In this example, handlers respond to "authenticate" and "another-event" events.
event: The event name to listen for.handler: The function to handle the request. It receives the request data and returns the response.sendRequest method is used to send a request to another service. In this example, requests are sent to the "jwt-service" to generate a JWT and to the "profile-service" to fetch a profile by user ID.Parameters:
targetService: The name of the target service.event: The event name to trigger on the target service.data: Optional data to send with the request.allowLateResponseAfterTimeout: Whether to allow handling late responses after the request times out (default: false).onLateResponse: Optional callback to handle late responses. This callback is invoked if:
allowLateResponseAfterTimeout is true, andReturns: A promise that resolves with the response from the target service.
Error Handling: The sendRequest method is wrapped in a try-catch block to handle any errors that may occur during the request. For example, if a request is sent to an invalid service, the Hub will respond with an error, which will be received by the client and thrown accordingly. The catch block will catch the error, and the user can display it using the error.message property. For more error related info, please have a look at the Error Structure or the Error Handling Section
hubUrl: URL of the Microstream Hub.serviceName: A Unique Service Registation Name of the service connecting to the hub.timeout: Timeout for requests in milliseconds (default: 5000).heartbeatInterval: Interval for sending heartbeats in milliseconds (default: 5000).logLevel: Log level for the client (default: "info").DUPLICATE_SERVICE_REGISTRATIONdebug: Log everything (useful for development).info: Log info, warnings, and errors.warn: Log warnings and errors.error: Log only errors.silent: Disable all logs.MicroStream Client implements standardized error handling using a CustomError class. All errors follow a consistent structure to help with error management and debugging.
{
code: string; // Error identification code
message: string; // Human readable error message
errorData?: any; // Optional contextual data
}
The Client may throw the following error types:
| Error Code | Description |
|---|---|
INTERNAL_SERVER_ERROR | Occurs when an event handler fails during execution |
EVENT_NOT_FOUND | Thrown when no handler is registered for the requested event |
REQUEST_TIMEOUT | Occurs when a request exceeds the configured timeout period |
DUPLICATE_SERVICE_REGISTRATION | Thrown when attempting to register a service name that's already in use |
TARGET_SERVICE_NOT_FOUND | Thrown when attempting to send a request to a service that isn't registered with the hub |
// Example: Handling request errors
try {
const response = await client.sendRequest("auth-service", "validate-token", {
token: "xyz",
});
} catch (error) {
switch (error.code) {
case "REQUEST_TIMEOUT":
console.error(`Request timed out: ${error.message}`);
console.log("Request details:", error.errorData);
break;
case "EVENT_NOT_FOUND":
console.error(`Event handler not found: ${error.message}`);
break;
case "INTERNAL_SERVER_ERROR":
console.error(`Service error: ${error.message}`);
console.log("Error context:", error.errorData);
break;
}
}
try-catch blockserror.errorData for additional context in debuggingREQUEST_TIMEOUT errors with appropriate retry logicINTERNAL_SERVER_ERROR casesallowLateResponseAfterTimeout and onLateResponse to handle late responses gracefullyTimeout Errors
Event Not Found
Internal Server Errors
Service Registration Errors
Late Response Errors
onLateResponse to handle these scenarios gracefullyHere is the central hub for easy integration with the MicroStream Client SDK.
Author: Arijit Banerjee
About: Full Stack Web Developer | Cyber Security Enthusiast | Actor
Social Media:
Instagram
LinkedIn
GitHub
Website
Email: arijit.codes@gmail.com
We welcome contributions! Please see our CONTRIBUTING.md for guidelines on how to contribute to this project.
This project is licensed under the MIT License. See the LICENSE file for details.
FAQs
A lightweight client SDK for Microstream communication
We found that microstream-client demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.