Reverse proxy and API gateway

Why you need it

Once an app is split into several services, each one has to do the same door-keeping: accept secure connections, check who is logging in, count requests, write logs. Doing it in every service is repeated work and repeated bugs. One front door can do it once for all of them.

Think of it like this

The reception desk of an office building. Visitors never wander the floors. They tell reception who they want, reception checks their ID once, and sends them to the right room.

Where you’ll find it

  • Netflix: Sends every request from every device through its own gateway, Zuul, before it reaches any service.
  • AWS: Amazon API Gateway is a ready-made front door that checks keys, limits callers and forwards to your code.
  • Open source: NGINX and Envoy are popular reverse proxies, and Kong is a popular gateway.

What to know first

Proxy. A go-between that passes messages on. A reverse proxy sits in front of the servers, so callers talk only to it.

Service. One small program with one job, like orders or payments. See Monolith vs microservices.

TLS. The encryption behind https. Setting it up is fiddly, so it is nice to do it in one place.

How it works

  1. One address for everything. Callers only know the front door. Behind it, the services can move, split or be renamed without callers noticing.
  2. Route by the request. The proxy reads the path and sends /orders to the orders service and /pay to payments. This is the reverse proxy in the animation.
  3. Do shared jobs once. Encryption, compression and caching common answers are handled at the door, so services do not each need them.
  4. A gateway also checks who you are. An API gateway adds the jobs that are about callers: checking logins or API keys, Rate limiting, and logging who called what. Services behind it can trust that the caller was already checked.
  5. Keep the door simple. Every request passes through it, so it must never be a Single points of failure: run several copies. And keep business rules out of it, or it slowly becomes a tangled monolith of its own.

An example

An app has three services: accounts, orders and payments. Each checks logins in its own code, in three slightly different ways, and one of them has a bug.

A gateway is put in front. It checks the login once, then forwards /orders/… to orders with a header saying "this is user 42".

The login code is deleted from all three services. The bug is gone, and a fourth service added next month gets login checks for free.

Further reading