Troubleshooting connectivity problems: SocketIO integration with microservices on a Kubernetes platform

I have organized my system using microservices architecture, with separate services for client interactions, orders, payments, and more. Each of these services runs on its own express server.

Now, I am looking to integrate real-time feedback functionality using socket.io. Currently, I am utilizing Kubernetes with Nginx to run these services within containers using Docker and Minikube.

My main query is regarding how to establish connections between the client service and other servers such as orders and payments in order to listen to events from various services.

In the order service section, I have set up a server in the following manner:

// * importing necessary modules for socketIO
import express from 'express';
import http from 'http';
import socketIO from 'socket.io';

// * declaring io globally
declare global {
  namespace NodeJS {
      interface Global {
          io: socketIO.Server 
      }
  }
}

// * creating an express app
const app = express();

// * creating a globally defined socket
const server = http.createServer(app);
global.io = new socketIO.Server(server);

// * handling connection with the server
global.io.on('connection', socket => {
  console.log(`New ${socket.client} client connected`);

  socket.emit('conn', 'connected');

  // * Handling client disconnection
  socket.on('disconnect', reason => {
    console.log(reason);
  })
});

I require assistance in establishing connections between these services and effectively integrating socketIO plugin.

On the client side, I am working with next.js but facing challenges in connecting with the backend.

Note: My setup includes Nginx service in Kubernetes with the following configuration file:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: 'true'
spec:
  rules:
    - host: test.dev
      http:
        paths:
          - path: /api/users/?(.*)
            backend:
              serviceName: auth-srv
              servicePort: 3000
          - path: /api/orders/?(.*)
            backend:
              serviceName: orders-srv
              servicePort: 3000
          - path: /api/payments/?(.*)
            backend:
              serviceName: payments-srv
              servicePort: 3000
          - path: /?(.*)
            backend:
              serviceName: client-srv
              servicePort: 3000

Below is the code snippet for the frontend client service where I am trying to establish a connection:

import Link from 'next/link'
import { useEffect, useState } from 'react';

import { io } from "socket.io-client";

function useSocket(url) {
  const [socket, setSocket] = useState(null)

  useEffect(() => {
    const socketIo = io(url)

    setSocket(socketIo)

    function cleanup() {
      socketIo.disconnect()
    }
    return cleanup

    // this effect should only run once and not on every re-render,
    // thus passing an empty array
  }, [])

  return socket
}

const Home = ({ events, reqErr }) => {
  // Establishing connection to orders service
  const socket = useSocket('/api/orders');

  // * Error Handling
  if (events === undefined || reqErr) {
    return (
      <div className="handle-error">
        <center>
          <h1 style={{color: 'red', margin: '20rem auto'}}> Can't Load page <br /> Error {reqErr.message}</h1>
        </center>
      </div>
    );
  }

  useEffect(() => {
    if (socket) {
      socket.on('conn', data => {
        console.log(data);
      })
    }
  }, [socket]);
  

  // * Rendering the page
  return (
    <div>
      Rendered
    </div>
  )
}

Home.getInitialProps = async (context, client, currentUser) => {
// Sending request to order service
};

export default Home; 

I am seeking guidance or suggestions on how to achieve this integration successfully.

Answer №1

Utilizing sticky sessions becomes crucial when incorporating socket io within a kubernetes environment. Failure to do so may result in a service within the kubernetes cluster sending requests to different pods with each request from the client machine, leading to potential issues for the client. For more information on this topic, refer to the following documentation:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with: getTotalBookListCost(bookList:string[]):number { let cost=0; bookList.forEach(el=>{ this.store.doc("Books/"+el).get().subscribe(data=>{ let temp=<Book>data.da ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

Mastering Typescript generics for accurate mapping between keys and values through indirection

I've been struggling to understand how to create a specialized mapper that can indirectly map methods based on one object's values corresponding to another object's keys. The mapper used in the code snippet below is not mine; it's an e ...

Issues with Next.js dynamic routing on Firebase hosting is not working as expected

After hosting on Firebase, my dynamic router job/[jobId] isn't working properly. I'm having trouble writing the necessary rewrites in the firebase.json file to fix this issue. Here is how my rewrites look: Currently, whenever I try to access a p ...

Trouble with image display in a next.js project hosted on Firebase

Exploring Next.js for the first time, I recently created a website and attempted to host it on Firebase hosting. Everything seems to be working well except for one issue - the images are not rendering on the hosted site. In my project structure, there are ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Implement a nested feature within the Accordion component

I am currently working on a project using Next.js and TypeScript. Within this project, I have implemented an accordion component as shown below: import React, { useEffect, useState } from 'react'; import classes from './Accordion.module.scss ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

The 'clientX' property is not recognized on the 'Event' type in Angular2 Directive

When attempting to retrieve the X position of my mouse in an Angular2 Directive using the following code: @HostListener('mousemove', ['$event']) onMousemove(event: Event): void { console.log(event.clientX) } I encountered an error ...

Updating the status to PUBLISHED upon adding a comment via GRAPHQL stage

I have developed a small blog website using Nextjs, GraphQL, and GraphCMS. Currently, the create comment feature is functional, but I need to manually set the status to PUBLISHED in the CMS after creating a comment. I want the comment to automatically be s ...

Encountered the error message "Uncaught (in promise) bad-precaching-response" while trying to deploy a Next.js app with next-pwa on Vercel

Encountered an error Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"https://myapp.vercel.app/_error","status":404}] with my next-pwa app, leading to the service worker not functioning when d ...

Unable to designate data types for a React Higher Order Component

In order to enhance a component with flattened props, I am working on creating a Higher Order Component (HOC). The goal is to take a component and return a new one that accepts flattened props using the flat package, then apply these unflattened props to t ...

Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included. I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted. https://i.stack.imgur.com/70thi.png Curr ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

Struggled to enable scroll functionality with Tailwind CSS in Next.js version 13

I am currently working on a project in next.js 13 where I attempted to incorporate a scroll bar using tailwind css. <div className="flex w-[1020px] p-4 overflow-x-scroll"> <div className={`w-[300px] h-[300px] self-center rela ...

I encountered a problem when trying to set up ngx-Spinner version 8.0.3

I need help implementing a spinner loader in my app. I have followed the instructions provided at [ https://www.npmjs.com/package/ngx-spinner ] and successfully installed it. However, when trying to import and add it to "imports", I encountered the follow ...

Troubleshooting: Next JS tab indicator does not work when using tabs with links

I have been experimenting with Next js and material UI, and here is what I've come up with so far <Tabs value={value} onChange={handleChange}> <Link href="/" passHref> <Tab label="Home"/> </Link> ... </Ta ...

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...