Tiếng Việt · English
One way in for many services: the API gateway
The dine site calls six services: sign-in, orders, menu, payment, kitchen, reservations.
Yet the browser knows exactly one address: api.dinesaga.app. Standing at that address is a small service
called the gateway, the only way into the whole system. This article is about why it is needed, what it does,
and why dine wrote its own instead of using an existing tool.
Without a gateway
It works perfectly well. Each service opens an address to the internet, and the browser calls each one directly. But you soon notice the shared chores being repeated everywhere:
- Checking sign-in in six places. Every service that needs to know "who is calling" has to read the token itself, check the signature and expiry, and keep its own key for checking. Changing one rule means changing it six times.
- Configuring CORS in six places. The web page and the API have different addresses, so the browser requires each service to declare "which pages may call me". Forget one place and that page breaks.
- Six doors open to the internet. Each door is something to protect. Forget the sign-in check on one API and it becomes a hole.
- The browser has to know where each service lives. Splitting or merging services, moving machines, changing ports, all mean editing the web page too.
A gateway gathers those shared chores in one place. The services behind it only have to deal with their own business.
/order/... to order,
/payment/... to payment. The path is forwarded unchanged.What dine's gateway does
Every request passes through the gateway in exactly this order:
- Attach a request ID. Each request gets its own ID, which is passed down to the service behind and returned to the browser. When something fails, searching for that ID finds the logs of both the gateway and the service.
- Strip forged headers. If the browser sends a header saying "I am user X" by itself, the gateway removes it. Without that, anyone could impersonate anyone else.
- CORS. Only the
dinesaga.apppage may call across. The browser asks first with anOPTIONSrequest, and the gateway answers it directly without forwarding it to a service. - Pick the service by path. If no service matches, return 404.
- Check sign-in if that path requires it, for example creating an order or viewing your own orders. A missing or invalid token gets a 401. If it is valid, the gateway adds a header saying who the user is, and only then forwards the request.
- Forward and return the result. For live data streams (the home page updating every second), the gateway pushes each piece of data on immediately instead of batching it.
Sign-in: check in one place, trust everywhere
Of the six services behind the gateway, auth is the odd one out. In the figure at the top it is just a box like
order or payment, but requests go through auth almost only once: at sign-in.
After that, the gateway checks things by itself without asking auth again.
auth.When you sign in with Google, auth checks with Google and then gives the browser a signed token (JWT),
stored in the dine_token cookie. Only auth holds the key to sign. The gateway only holds the public key to
verify that signature: a public key cannot sign new tokens, so even if it leaks, nobody can forge a token.
Once verified, the gateway attaches "the user is usr_..." to the request.
The services behind it need to know nothing about tokens, keys or Google. order just reads that header to know
whose order this is. For this to be safe there is one condition: nobody can go around the gateway.
At dine, the services only open ports inside the server; from the internet, only the gateway is reachable. If a service accidentally opened
a port to the outside, an attacker could call it directly, fill in the header "I am user X" themselves, and be done.
Not asking auth: what you gain, what you lose
- Gain: auth is not on the path of every request. Creating an order or viewing your own orders only goes through the gateway to
order. Ifauthis slow or overloaded, those requests do not slow down with it. (dine's web pages still call/auth/meto show the user's name, so ifauthis down, the interface will think you are signed out. But the check at the gateway does not needauth.) - Loss: a token, once issued, cannot be taken back right away. The gateway only looks at the signature and the expiry; it asks nobody "may this token still be used?". Signing out deletes the cookie in the browser, but if someone copied the token earlier, it stays valid until it expires. That is why tokens should be short-lived. To block a token immediately you need a list of revoked tokens that the gateway checks on every request, which means going back to asking a central place, exactly what JWT helps you avoid.
What else a gateway can do
Because every request passes through one place, it is also the natural place for many other things. dine's gateway currently only does the jobs above, but it could add:
- Rate limiting: each person or IP address may only call so many times per minute, blocking spam and stopping a buggy client from hammering the system.
- Caching: things that rarely change, like the menu, are served straight from the gateway without asking the service behind it every time.
- Centralized metrics: counting requests, measuring response times and error rates for each service, all in one place.
- Gradual rollout of a new version: send 10% of requests to a new version of a service to try it, and switch everything over once it is stable.
There are also things that should not live in the gateway: business logic, or calling several services and merging their data. Do that, and the gateway slowly turns into a giant service that knows everything, exactly what splitting into services was meant to avoid. dine merges data from several services in the browser; the gateway only forwards.
Can you write your own gateway?
You can, and dine did. But it is one choice out of three:
| Approach | Fits when | Trade-off |
|---|---|---|
| Nginx configuration | All you need is routing requests by path | Very fast, very stable. But plain Nginx usually cannot verify a JWT by itself; you need an extra module or some Lua. |
| An off-the-shelf gateway (Kong, Traefik, Envoy, a cloud provider's gateway) | You need many features, many teams share it | Rate limiting, caching and plugins come built in. But it is one more large system to learn and operate. |
| Write your own | The needs are few and clear, and you want to understand and control every line | Flexible and lightweight. But you have to run into, and fix, every bug and every trap yourself. |
dine's gateway is written in Go, using only the standard library, with a core of a few hundred lines. Go already ships a request forwarder (reverse proxy), so the hard part is not the forwarding but the small traps. A few that dine ran into:
- Live data streams getting batched. By default the forwarder collects data into chunks before sending. The home page, which updates every second, would freeze and then jump all at once. You have to tell it to send each piece immediately.
- One hung service hangs the gateway too. By default there is no limit on how long to wait for a service to answer. A hung service would hold the gateway's resources forever. You have to set a limit and return a 502 once it is exceeded.
- An overall time limit cutting off live streams. Conversely, setting a limit on the whole response cuts connections that need to stay open for a long time in the middle. You have to pick the right kind of limit.
- Preflight being blocked. The browser's ask-first request (
OPTIONS) carries no cookie. Let it go through the sign-in check and it gets a 401, and the real request is never sent. - Forged tokens. A token that declares itself "no signature needed" (
alg: none) must be rejected. The gateway accepts exactly one signing algorithm.
This list is the reason to think twice before writing your own: most of those traps were hit and fixed long ago by off-the-shelf gateways. For dine, writing its own was still worth it, because the needs are small and every trap it hit was a lesson about HTTP that an off-the-shelf tool would have hidden.
The price
- One point of failure takes everything down. If the gateway dies, no service can be reached, even though they are all running fine. The gateway has to be simple and stable, and able to run several copies when needed.
- One more hop. Every request passes through one more step. With the gateway on the same machine as the services, this extra cost is tiny compared to the actual processing time.
- Easy to bloat. Every "it's convenient, just put it in the gateway" is one step towards turning it into a giant service. Keep it to the shared chores only.
One small but important detail: when the monitoring system asks the gateway "are you alive?", the gateway answers only for itself, without asking the services behind it. A dead service must not get the gateway marked as dead, dragging down the healthy services with it.
In short: things still work without a gateway, but every service has to handle sign-in and CORS itself and open its own door to the internet. A gateway gathers those shared chores in one place and is the only way in. You can write your own, as long as you know up front that you are also taking on the traps that off-the-shelf tools would have handled for you.
See it for yourself
Open your browser's developer tools (F12), go to the Network tab, and reload the home page: every data request goes to
api.dinesaga.app, differing only in the path. Each response has an X-Request-Id header, which is the ID
the gateway attached for searching the logs.
- Home page Orders running live through the data stream, passing straight through the gateway.
- What dine is The big picture of the whole system: where the gateway stands relative to the services.
Spotted a mistake, or have a question? Write to [email protected].
dine is a personal project about distributed systems, written in Go: orchestrated sagas, transactional outbox, Kafka. More articles.