Hi Pythonistas!
You split your monolith. Now you have services.
user-service → 10.0.1.1:8001
order-service → 10.0.1.2:8002
payment-service → 10.0.1.3:8003
inventory-service → 10.0.1.4:8004
Two immediate problems.
Problem 1: Your mobile app needs to call all these services.
const user = await fetch('http://10.0.1.1:8001/users/123')
const orders = await fetch('http://10.0.1.2:8002/orders?user=123')
const payment = await fetch('http://10.0.1.3:8003/payments?user=123')
Client knows every service's IP.
Every service's port.
Service moves to new server?
New IP.
Every client breaks.
Problem 2:
Services need to call each other.
order-service needs payment-service
payment-service needs user-service
How does order-service know where payment-service is?
IPs change.
Services scale up and down.
Hardcoding IPs doesn't work.
Two solutions.
API Gateway solves Problem 1.
Service Discovery solves Problem 2.
API Gateway
Single entry point for all clients.
Mobile App ─┐
Web App ─┼──→ API Gateway → user-service
Third Party ─┘ → order-service
→ payment-service
Client talks to ONE thing.
Gateway routes to the right service.
Client never knows internal services exist.
What API Gateway Does
Routing:
GET /users/123 → user-service
GET /orders/456 → order-service
POST /payments → payment-service
Authentication:
Request arrives with JWT token.
Gateway verifies it.
Valid → passes to service.
Invalid → rejects immediately.
Services don't need auth logic.
Rate limiting:
100 requests/minute per user.
Gateway counts.
Gateway rejects when exceeded.
Services don't need rate limiting.
SSL termination:
Client → HTTPS → Gateway → HTTP → Services (internal)
Services don't need SSL certificates.
Logging:
Every request passes through gateway.
One place to monitor all traffic.
Simple API Gateway in Python
from flask import Flask, request, Response
import requests
import jwt
app = Flask(__name__)
SERVICES = {
'users': 'http://user-service:8001',
'orders': 'http://order-service:8002',
'payments': 'http://payment-service:8003',
}
def verify_token(token):
try:
return jwt.decode(token, 'secret_key', algorithms=['HS256'])
except jwt.InvalidTokenError:
return None
@app.route('/<service>/<path:path>', methods=['GET','POST','PUT','DELETE'])
def gateway(service, path):
# authentication
token = request.headers.get('Authorization', '').replace('Bearer ', '')
user = verify_token(token)
if not user:
return {'error': 'Unauthorized'}, 401
if service not in SERVICES:
return {'error': 'Service not found'}, 404
# forward request
response = requests.request(
method=request.method,
url=f"{SERVICES[service]}/{path}",
headers={
'X-User-Id': str(user['user_id']),
'X-User-Role': user['role']
},
json=request.get_json(),
params=request.args,
timeout=10
)
return Response(
response.content,
status=response.status_code,
content_type=response.headers.get('Content-Type')
)
Real API Gateway Tools
Don't build from scratch.
AWS API Gateway:
Managed.
Auto-scaling.
Built-in auth, rate limiting, logging.
API Gateway vs Load Balancer
Load Balancer:
→ routes to SAME type of server
→ distributes traffic
→ one service type behind it
API Gateway:
→ routes to DIFFERENT services
→ content-based routing
→ plus: auth, rate limiting, transformation
Used together:
Client → API Gateway → Load Balancer → Service instances
BFF - Backend for Frontend
Different clients need different data.
Mobile app → small screen, limited bandwidth, minimal data
Web app → large screen, rich data
Third party → specific format, different auth
One gateway for all?
Mobile gets too much data.
Separate gateway per client:
Mobile App → Mobile BFF → Services
Web App → Web BFF → Services
Third Party → API BFF → Services
Service Discovery
Services need to find each other.
Without hardcoding IPs.
Why hardcoding fails:
order-service hardcodes:
payment_url = 'http://10.0.3.1:8003'
payment-service moves to new server.
New IP: 10.0.2.5
order-service still calls: 10.0.3.1
Connection refused.
Broken.
In production:
services start and stop.
IPs change.
Instances scale.
Need dynamic discovery.
The Service Registry - Phone Book
Registry:
Name IP Port Status
payment-service 10.0.3.1 8003 healthy
payment-service 10.0.3.2 8003 healthy
order-service 10.0.2.1 8002 healthy
user-service 10.0.1.1 8001 healthy
Order service asks:
"Give me a healthy payment-service."
Registry returns: 10.0.3.1:8003
Order service calls that.
Three Things Every Service Does
1. Register on startup — once
2. Send heartbeat — every 10 seconds:
Registry receives heartbeat.
Updates timestamp.
No heartbeat for 30 seconds → marked unhealthy → removed.
3. Deregister on shutdown — once:
How Order Service Finds Payment Service
The Full Lifecycle
Payment service starts
↓
Registers: "I'm at 10.0.3.1:8003"
↓
Every 10 seconds: heartbeat
↓
Order service needs payment
↓
Asks registry → gets "10.0.3.1:8003"
↓
Calls payment service
↓
Payment service crashes
↓
Heartbeats stop
↓
Registry: "no heartbeat 30s → unhealthy"
↓
Removes from list
↓
Order service asks again
↓
No healthy instances
↓
Circuit breaker opens (Post 18)
What If Payment Service Doesn't Respond?
Timeout fires (3 seconds).
Retry with same idempotency key (Post 19).
All retries fail.
Circuit breaker opens (Post 18).
Fallback response returned.
DNS-Based Discovery
Simpler approach.
Each service gets a DNS name.
Kubernetes does this automatically:
No manual registry.
Kubernetes manages DNS.
Services start → DNS updated.
Services stop → DNS updated.
Automatic.
Popular Service Discovery Tools
Consul
AWS Cloud Map
Mental Model
API Gateway → single entry point for all clients
Routing → path-based to correct service
Auth → centralized at gateway
Rate limiting → centralized at gateway
SSL termination → gateway handles HTTPS
BFF → separate gateway per client type
Service registry → phone book of running services
Registration → once on startup
Heartbeat → every 10s, just a timestamp update
Deregistration → once on shutdown
Health check → registry removes dead services
DNS discovery → simplest, use service name as hostname
Consul → most popular standalone registry
Kubernetes DNS → automatic, built-in
Internal ALB → simplest AWS approach
Risky ops first → payment before order creation
What's Coming Next
Now your services can find each other.
But every service needs to share code.
Configuration.
Logging.
Authentication.
How do you avoid duplicating this across every service?
Sidecar Pattern and Service Mesh.
How Netflix, Uber and Googlehandle cross-cutting concerns at scale.