Thursday, 3 July 2025

API Gateway in microservices architecture

 

🔍 What is an API Gateway?

An API Gateway is a server that acts as a single entry point into a system, typically for microservices architecture.

It handles requests by:

  • Routing them to the appropriate microservice

  • Applying security, rate limiting, authentication

  • Performing load balancing, logging, caching, etc.


📦 Why Use an API Gateway?

FeaturePurpose
🔁 Request RoutingDirects incoming requests to appropriate backend services
🔐 SecurityCentralized authentication and authorization
⚖️ Load BalancingDistributes traffic among service instances
🔄 Protocol TranslationTranslates protocols (HTTP to WebSocket, etc.)
📉 Rate LimitingPrevents abuse by limiting requests per client
📄 AggregationCombines responses from multiple services into one
📊 MonitoringTracks usage, logs, and metrics
🌍 CORS HandlingCross-origin resource sharing setup

🧱 Architecture Diagram:

less
[Client App] | v [API Gateway] ---> [User Service] | [Order Service] | [Product Service] v [Auth Service]

🚀 Common API Gateway Tools

Tool    LanguageNotes
🔹 Spring Cloud Gateway  Java (Spring Boot)  Official Spring API Gateway
🔹 Zuul (Netflix)  Java  Older Netflix API Gateway (no longer maintained)
🔹 NGINX   C  Lightweight, powerful reverse proxy
🔹 Kong  Lua  Enterprise-grade open source API Gateway
🔹 Amazon API Gateway  Cloud  Managed gateway on AWS

🛠️ Example: Spring Cloud Gateway (Java)

1️⃣ Dependency (Maven):

xml
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>

2️⃣ application.yml config:

yaml
spring: cloud: gateway: routes: - id: user-service uri: http://localhost:8081 predicates: - Path=/users/** - id: order-service uri: http://localhost:8082 predicates: - Path=/orders/**

3️⃣ Main class:

java
@SpringBootApplication public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }

🔐 API Gateway with Security (JWT)

  • Intercepts incoming requests

  • Validates JWT token

  • Rejects unauthorized users before hitting backend microservices


📊 Advanced Features

  • Rate limiting (RequestRateLimiter)

  • Circuit breaker (resilience4j, Hystrix)

  • Path rewriting

  • Load balancing with service discovery (Eureka)


📌 Pros and Cons

✅ Advantages:

  • Centralized control

  • Simplified client code

  • Unified security

❌ Disadvantages:

  • Single point of failure (unless highly available)

  • Can become bottleneck if not scaled properly

  • Adds complexity

No comments:

Post a Comment