In microservice-based architectures, all microservices use the IP address and port as the location of each microservice, which the API gateway needs to know in order to communicate. You could hardcoded the IP address and port of the microservice, but this is not as easy in the case of multiple instances of the same microservice. Fortunately, service discovery is a mechanism that allows you to register your microservices with a service registry server, such as Netflix's Eureka.
There are two types of discovery mechanism: server-side discovery and client-side discovery. In the client-side discovery mechanism, the API gateway must be able to query the service registry server where all microservices are registered with their locations. In the server-side discovery mechanism, the client (such as an API gateway) requests the router deployed on another server, and that router then queries the service registry server.
The client-side discovery mechanism has less overhead because it has fewer moving parts and network hops in comparison to server-side discovery, and is therefore preferable. An API gateway must be aware of the service registry mechanism being used. As the API gateway application is also registered with a registry server, such as Netflix's Eureka, let's look at the code required to register the application as follows: