Microservices Architecture

Part 3

API Gateway & Request Routing

Building a robust API Gateway to manage routing, authentication, and rate limiting

Published:
Golang Kong Rate Limiting Authentication

Microservices Architecture - Part 3: API Gateway & Request Routing

The API Gateway serves as the single entry point for all client requests, providing routing, rate limiting, and authentication.

API Gateway Pattern

type Gateway struct {
    routes map[string]*ServiceRoute
    limiter RateLimiter
}

type ServiceRoute struct {
    Path       string
    Service    string
    Port       int
    Methods    []string
}

func (g *Gateway) HandleRequest(w http.ResponseWriter, r *http.Request) {
    route := g.findRoute(r.URL.Path, r.Method)
    if route == nil {
        http.NotFound(w, r)
        return
    }
    
    if !g.limiter.Allow(r.RemoteAddr) {
        http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
        return
    }
    
    g.forwardRequest(w, r, route)
}

Authentication & Authorization

type AuthMiddleware struct {
    jwtSecret string
}

func (am *AuthMiddleware) ValidateToken(token string) (Claims, error) {
    parsedToken, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(am.jwtSecret), nil
    })
    
    if err != nil {
        return Claims{}, err
    }
    
    return *parsedToken.Claims.(*Claims), nil
}

Rate Limiting Strategy

Implement token bucket algorithm for fair rate limiting:

  • Per-user limits
  • Per-IP limits
  • Global limits

Key Takeaways

  • Centralize cross-cutting concerns
  • Implement circuit breakers for fault tolerance
  • Monitor gateway performance
  • Use caching for frequently accessed endpoints

This completes our 3-part series on microservices architecture. You now have the foundation to build scalable, distributed systems!