API gateway
medium 24 minAn API gateway is the single front door for client requests.
See it run
Walk requests through the front door: checks, routing, combining answers, and what happens when the door fails.
Operations
One request, end to end
A phone reads the cart.
Step 1 of 9
Client request
The app sends GET /api/cart to the one public address.
Step 1: Client request
def handle(request): request = decrypt(request) # TLS ends here user = authenticate(request) # 401 check_limit(user) # 429 service = match(request) # 404 copy = choose_healthy(service) # 503 response = forward(copy, request) # 502, 504 return response- Extra hops
- One
- Client calls
- One
- No gateway
- client knows four addresses
Say the checks in order, cheap ones first.
In the real world
The same api gateway doing real jobs. Pick one and step through it.
Why identity headers are stripped.
Step 1 of 3
Someone pretends
| X-User-Id | |
|---|---|
| From client | ben |
| After strip | - |
| To service | - |
A request arrives with X-User-Id: ben, typed by the client.
Step 1: Someone pretends
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Business rules in the gateway
majorEvery team then waits for the gateway, and one mistake breaks all products.
Wrongif cart.total > 50: cart.shipping = 0 # in the gatewayRightreturn forward("cart-service", request)Forwarding identity headers from clients
criticalAnyone could claim to be anyone.
Wrongforward(request.headers)Righth = without(request.headers, "x-user-id")h["x-user-id"] = verified.subforward(h)No timeout on an upstream
criticalOne slow service holds all connections, and every route fails.
Wrongget(service_url)Rightget(service_url, timeout=2.0)# and a cap on calls in flight per serviceCounting limits on each copy
majorWith four copies a client gets up to four times the limit.
Wrongcounts = {} # in each gatewayRightcounts = redis # shared, atomic
Interview tips
Explain it in one line
- One address outside, many services inside.
- It checks and directs.
SALT RAMP
- Security, Aggregation, Load balance, Transform.
- Routing, Analytics, Management, Protocol.
Reach for it when
- Several services share one API.
- Checks are repeated in each service.
- Clients differ a lot: consider BFF.
Expect these questions
- Is it a single point of failure?
- Do services trust it?
- What if one service is slow?