AlgoViz

API gateway

medium 24 min

An 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

Our systemGET /api/cartMobile appAPI gatewayUsersProductsCartOrders

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 clientben
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

    major

    Every team then waits for the gateway, and one mistake breaks all products.

    Wrong
    if cart.total > 50:    cart.shipping = 0          # in the gateway
    Right
    return forward("cart-service", request)
  • Forwarding identity headers from clients

    critical

    Anyone could claim to be anyone.

    Wrong
    forward(request.headers)
    Right
    h = without(request.headers, "x-user-id")h["x-user-id"] = verified.subforward(h)
  • No timeout on an upstream

    critical

    One slow service holds all connections, and every route fails.

    Wrong
    get(service_url)
    Right
    get(service_url, timeout=2.0)# and a cap on calls in flight per service
  • Counting limits on each copy

    major

    With four copies a client gets up to four times the limit.

    Wrong
    counts = {}                    # in each gateway
    Right
    counts = 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?