API Gateway — Centrálny vstupný bod pre API
API Gateway je server, ktorý slúži ako jediný vstupný bod pre všetky API requesty. Prijíma requesty od klientov, smeruje ich na správne backend služby a aplikuje cross-cutting concerns — autentifikáciu, rate limiting, transformáciu, logging.
Prečo API Gateway?
Bez API gateway klient komunikuje priamo s každou mikroslužbou. To vytvára problémy:
- Klient musí poznať adresy všetkých služieb
- Cross-cutting concerns (auth, logging) sa duplikujú v každej službe
- Zmena API vyžaduje zmenu na klientoch
- Bezpečnosť — všetky služby sú exponované
Bez gateway: S API gateway:
Client ──► Service A Client ──► API Gateway ──► Service A
Client ──► Service B ──► Service B
Client ──► Service C ──► Service C
API Gateway vs Reverse Proxy
| Aspekt | Reverse Proxy | API Gateway |
|---|---|---|
| Účel | Load balancing, SSL termination | API management |
| Routing | URL/host-based | Path, header, method-based |
| Auth | Základné (basic auth) | OAuth2, JWT, API keys |
| Rate limiting | Jednoduché | Per-user, per-endpoint |
| Transformácia | Nie | Request/response rewriting |
| Analytics | Základné logy | Per-API metriky |
| Developer portal | Nie | Áno |
V praxi sa tieto role často prekrývajú — moderné reverse proxy (Traefik, Envoy) ponúkajú aj API gateway funkcie.
Kong — Enterprise API Gateway
Kong je najpoužívanejší open-source API gateway, postavený na Nginx a OpenResty (Lua). Ponúka bohatý plugin ekosystém.
Inštalácia Kong
# Docker
docker run -d --name kong-database \
-p 5432:5432 \
-e POSTGRES_USER=kong \
-e POSTGRES_DB=kong \
postgres:16
docker run --rm \
--link kong-database:kong-database \
-e KONG_DATABASE=postgres \
-e KONG_PG_HOST=kong-database \
kong:latest kong migrations bootstrap
docker run -d --name kong \
--link kong-database:kong-database \
-e KONG_DATABASE=postgres \
-e KONG_PG_HOST=kong-database \
-e KONG_PROXY_ACCESS_LOG=/dev/stdout \
-p 8000:8000 \
-p 8443:8443 \
-p 8001:8001 \
kong:latest
Kong konfigurácia (deklaratívna)
# kong.yml
_format_version: "3.0"
services:
- name: user-service
url: http://users:3000
routes:
- name: user-routes
paths:
- /api/users
strip_path: true
plugins:
- name: rate-limiting
config:
minute: 100
policy: local
- name: jwt
- name: order-service
url: http://orders:3000
routes:
- name: order-routes
paths:
- /api/orders
methods:
- GET
- POST
plugins:
- name: key-auth
- name: cors
config:
origins:
- "https://app.example.com"
methods:
- GET
- POST
headers:
- Authorization
- Content-Type
Kong pluginy
# Rate limiting
curl -X POST http://localhost:8001/services/user-service/plugins \
--data "name=rate-limiting" \
--data "config.minute=100" \
--data "config.hour=1000" \
--data "config.policy=redis" \
--data "config.redis_host=redis"
# JWT autentifikácia
curl -X POST http://localhost:8001/services/user-service/plugins \
--data "name=jwt"
# Request transformer
curl -X POST http://localhost:8001/services/user-service/plugins \
--data "name=request-transformer" \
--data "config.add.headers=X-Request-ID:$(uuidgen)"
Traefik — Cloud-native API Gateway
Traefik je moderný reverse proxy a API gateway s automatickou service discovery. Natívne integrovaný s Docker, Kubernetes a ďalšími orchestrátormi.
Traefik s Docker
# docker-compose.yml
services:
traefik:
image: traefik:v3.0
command:
- --api.dashboard=true
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
- --certificatesresolvers.letsencrypt.acme.email=admin@example.com
- --certificatesresolvers.letsencrypt.acme.storage=/acme.json
- --certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./acme.json:/acme.json
api:
image: my-api:latest
labels:
- traefik.enable=true
- traefik.http.routers.api.rule=Host(`api.example.com`)
- traefik.http.routers.api.tls.certresolver=letsencrypt
- traefik.http.services.api.loadbalancer.server.port=3000
# Rate limiting
- traefik.http.middlewares.api-ratelimit.ratelimit.average=100
- traefik.http.middlewares.api-ratelimit.ratelimit.burst=50
- traefik.http.routers.api.middlewares=api-ratelimit
Traefik s Kubernetes (IngressRoute)
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: api-route
spec:
entryPoints:
- websecure
routes:
- match: Host(`api.example.com`) && PathPrefix(`/v1`)
kind: Rule
services:
- name: api-v1
port: 8080
middlewares:
- name: rate-limit
- name: jwt-auth
- match: Host(`api.example.com`) && PathPrefix(`/v2`)
kind: Rule
services:
- name: api-v2
port: 8080
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: rate-limit
spec:
rateLimit:
average: 100
burst: 50
period: 1m
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: jwt-auth
spec:
plugin:
jwt:
source: Authorization
jwksUrl: https://auth.example.com/.well-known/jwks.json
Rate Limiting
Rate limiting chráni API pred preťažením. Existuje viacero stratégií:
Algoritmy
| Algoritmus | Popis | Use case |
|---|---|---|
| Fixed Window | X requestov za Y sekúnd | Jednoduchý, ale burst na hraniciach |
| Sliding Window | Priemer cez kĺzavé okno | Presnejší, menej burstu |
| Token Bucket | Tokeny sa dopĺňajú konštantnou rýchlosťou | Povolí burst, plynulý limit |
| Leaky Bucket | Requesty "vytekajú" konštantnou rýchlosťou | Vyrovnáva traffic |
Rate limit hlavičky
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1710421200
Retry-After: 30
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
Retry-After: 30
Autentifikácia na API Gateway
JWT validácia
Gateway validuje JWT token a prepošle claims na backend:
Client ──► Gateway ──► Backend
│ │ │
│ JWT token │ │
│──────────►│ │
│ │ Validate │
│ │ JWT │
│ │──────────►│
│ │ + X-User │
│ │ headers │
API Key autentifikácia
# Kong: Vytvorenie konzumenta a API kľúča
curl -X POST http://localhost:8001/consumers \
--data "username=mobile-app"
curl -X POST http://localhost:8001/consumers/mobile-app/key-auth \
--data "key=your-secret-api-key"
# Request s API kľúčom
curl -H "apikey: your-secret-api-key" \
https://api.example.com/users
Ďalšie API Gateway funkcie
Request/Response transformácia
# Kong: Pridanie headerov, odstránenie citlivých dát
plugins:
- name: response-transformer
config:
remove:
headers:
- X-Powered-By
- Server
add:
headers:
- X-Gateway: kong
Circuit breaker
# Traefik circuit breaker
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: circuit-breaker
spec:
circuitBreaker:
expression: ResponseCodeRatio(500, 600, 0, 600) > 0.30
checkPeriod: 10s
fallbackDuration: 30s
Caching
# Kong caching plugin
plugins:
- name: proxy-cache
config:
response_code:
- 200
request_method:
- GET
content_type:
- application/json
cache_ttl: 300
strategy: memory
Porovnanie API Gateway riešení
| Aspekt | Kong | Traefik | AWS API GW | Envoy |
|---|---|---|---|---|
| Typ | Traditional | Cloud-native | Managed | Proxy |
| Plugin systém | Lua | Middleware | AWS native | Filters |
| K8s integrácia | CRD | Natívna | Nie | CRD |
| Cena | Open-source + Enterprise | Open-source | Pay-per-use | Open-source |
| Dashboard | Kong Manager | Built-in | AWS Console | Nie |
| Service discovery | DNS, Consul | Docker, K8s | AWS native | xDS |
Best Practices
- Centralizujte cross-cutting concerns — auth, rate limiting, CORS na gateway
- Nevkladajte biznis logiku — gateway nie je miesto pre transformácie dát
- Monitorujte gateway — je to single point of entry, merajte latenciu
- HA konfigurácia — gateway musí byť vysoko dostupný (min. 2 inštancie)
- Verziovanie API —
/v1/,/v2/routing na gateway úrovni - Security first — TLS termination, WAF, IP whitelisting
API Gateway je esenciálny komponent mikroslužbovej architektúry. Centralizuje bezpečnosť, rate limiting a routing, čím zjednodušuje backend služby a poskytuje konzistentný vstupný bod pre klientov.