Let’s say we have a monolithic e-commerce application with multiple endpoints.
5 things initially:
- Client devices
- HTTP requests from clients
- The web server
- The endpoints (Business logic)
- Additional checks (authentication, authorization, SSL certificate)
To shift all the, non-business logic code we can utilise an API gateway. It will also result in a more modular code separating the core business logic and additional checks. The requests instead of hitting the web server will hit the API gateway instead.
Let’s say our app shifted to a microservices architecture later on. The logged-in user-related functions are in Microservice 1 and the product listings related to Microservice 2.
The API Gateway can now route the requests too based on the additional checks to MS1 or MS2.
Now our app has some more cool features, like discounts, personalised recommendations, hot products etc...
This will result in multiple HTTP requests back and forth between client and server. This results in a slow response for the full render of a page.
To solve this, we added a 4th Adapter component to our API gateway, to manage these 4 requests to the 4 microservices per device. The Adapter will receive now just one request and will forward the corresponding requests to each of the 4 Microservices and consolidate the response back to the client.
Additionally, we could streamline the MSs by serving the static files in the API gateway itself and this would respond if any request for these files hits the gateway by decommissioning the static files MS.
We can use the cache to not have recurring requests being sent for features like trending products if it is only updated at an hour periodically. Caching
User-agent related routing to different versions of a service
Let’s say we have this logic to serve slow and high-quality videos on the website and fast but low-quality video content when the request comes from a laptop and an outdated mobile device respectively. The API gateway can route to the respective microservice.
Load balancing round robin and canary deployment for updates
In addition, we can create multiple copies of a service if our app is viral to balance the HTTP requests to these copies in a round-robin fashion. Plus, we can employ a canary deployment technique through the API gateway too.
If our API is valuable and reliable truly it can be exposed to other parties and we can bill them for usage.