API Gateway & Service Communication
What belongs at the edge, REST vs gRPC vs GraphQL, the BFF pattern, and how services should talk to each other without creating a distributed monolith.
#The edge tier
An API gateway is a single entry point in front of many backend services. It exists because certain concerns are needed by every service, and implementing them N times is both wasteful and inconsistent.
┌──────────────────────────────────┐
clients ──►│ API GATEWAY │
│ TLS · authN · rate limit · │
│ routing · aggregation · logging │
└──┬──────────┬─────────┬──────────┘
▼ ▼ ▼
users orders catalogWhat belongs here:
- TLS termination and certificate management, in one place.
- Authentication — check the caller's token once, then pass a verified "this is user 42" inward. Backend services trust that rather than each re-implementing token parsing. (Note this is authentication — who are you — not authorisation, what may you do, which usually stays with the service that owns the data.)
- Rate limiting — reject abusive traffic before it costs you anything.
- Routing — send each path or hostname to the right service, and split traffic by weight for gradual rollouts.
- Protocol translation — public REST/JSON outside, gRPC inside.
- Response aggregation — the client makes one call; the gateway calls several services behind it and stitches their answers into one response. A product page might need
catalog,pricingandreviews— one round trip from the phone instead of three. - Observability — consistent request IDs, latency, and status codes across everything.
**What does not belong here:** business logic — rules like "orders over £500 need a fraud check". The gateway is the most-shared and highest-risk component you own; every rule you put in it is a change that can break every service at once. The failure mode has a name — the "smart pipe", meaning the plumbing between services has started making product decisions. The symptom is that shipping a feature requires a gateway deploy: if the orders team can't release without changing the gateway, logic that belongs to orders has leaked into it.
#REST vs gRPC vs GraphQL
Pick by consumer and access pattern, and say why.
#REST / JSON over HTTP
Resources with standard verbs. Universally supported, cacheable by HTTP infrastructure, debuggable with curl, no code generation.
Weaknesses: over-fetching (the endpoint returns 40 fields, the client needs 3), under-fetching (rendering a screen requires 5 sequential calls), verbose JSON, and no schema enforcement unless you add OpenAPI.
Use for: public APIs, third-party integrations, anything where broad compatibility and cacheability matter most. Still the correct default for public surfaces.
#gRPC
You write down the shape of your messages once, in a schema file, and a tool generates matching client and server code in every language you use. Messages travel as compact binary (Protobuf) rather than text, over HTTP/2.
Strengths: compact binary payloads (often 3–10× smaller than JSON), a strict schema with generated types in every language, HTTP/2 multiplexing (many concurrent requests on one connection), native bidirectional streaming, and low latency.
Weaknesses: not human-readable, awkward from browsers (needs grpc-web and a proxy), harder to cache in standard HTTP infrastructure, and it requires the L7 load balancing discussion. An L4 balancer picks a backend once per connection, but gRPC sends all its requests down one long-lived connection — so every request from that client lands on the same backend. You need an L7 balancer that spreads individual requests.
Use for: internal service-to-service communication. This is the standard modern choice inside a datacenter, and saying "REST at the edge, gRPC internally" is a clean, defensible architecture statement.
#GraphQL
One endpoint; the client specifies exactly the shape it wants.
Strengths: eliminates over- and under-fetching, so a mobile client on a slow network fetches one precisely-shaped payload instead of five round trips. When a screen needs one more field, the client just asks for it — no new backend endpoint needed. Strong typing, and introspection: clients can ask the server for its schema, which powers autocomplete and generated types.
Weaknesses, all real:
- Caching is hard. Every query is a POST to the same URL, so HTTP caching doesn't apply. You need application-level caching keyed by query shape.
- The N+1 problem. A query for 50 posts with each post's author naively runs 1 query for the posts, then 1 query per post for its author — 51 database calls. You need batching (DataLoader-style: collect all 50 author IDs, then fetch them in one query) to make it viable. This is not optional — it's the defining operational hazard.
- Unbounded query cost. A client can request a deeply nested query (friends of friends of friends…) that's expensive to serve. You need depth limits, complexity scoring, and persisted queries — only allowing queries that were registered ahead of time.
Use for: mobile and rich web clients with diverse data needs, and aggregation across many backend services.
#Comparison
| REST | gRPC | GraphQL | |
|---|---|---|---|
| Payload | JSON | Protobuf (binary) | JSON |
| Schema | Optional (OpenAPI) | Required | Required |
| Browser support | Native | Needs proxy | Native |
| HTTP caching | Excellent | Poor | Poor |
| Streaming | SSE / chunked | Native bidirectional | Subscriptions |
| Best for | Public APIs | Internal RPC | Client-driven aggregation |
#Backend for Frontend (BFF)
When a mobile app, a web app, and a partner API all need different shapes of the same data, a single general-purpose API serves all three badly.
The BFF pattern gives each client its own thin aggregation layer:
iOS app ──► Mobile BFF ─┐
Web app ──► Web BFF ─┼──► users, orders, catalog, pricing
Partner ──► Public API ─┘Each BFF is owned by the team that owns its client, and it can aggregate, trim payloads, and change shape without coordinating with anyone else. The mobile BFF can return one compact response for a screen; the web BFF can return richer data.
Cost: duplicated aggregation logic across BFFs, and more services to run. Worth it when client needs genuinely diverge; unnecessary overhead when they don't.
#Service-to-service communication
Synchronous (request/response). Simple, immediately consistent, easy to debug — and it couples availability: if the service you call is down, you're down too. Every synchronous dependency multiplies into your availability calculation. A service that's 99.9% up and synchronously calls three others that are each 99.9% up is only about 99.6% up (see Availability). Use when the caller genuinely needs the result to respond.
Asynchronous (events). The caller publishes a message and moves on. The two services no longer need to be running at the same moment: the consumer can be down for an hour, and the producer keeps working while messages wait in the queue. Costs eventual consistency and harder debugging. Use for side effects, notifications, and fanout. See Message Queues.
The practical rule: synchronous for queries the user is waiting on, asynchronous for everything triggered by an action but not required to complete it. Placing an order: synchronously reserve inventory and charge the card; asynchronously send the email, update analytics, notify the warehouse, and recompute recommendations.
#Essentials for any service call
Every remote call should have all four. Naming them unprompted is a strong signal:
- Timeout, with deadline propagation down the chain.
- Retry with exponential backoff and jitter (a random extra delay, so thousands of clients don't all retry at the same instant). Retry at exactly one layer — if the gateway, the service and the client all retry 3 times, one failure becomes 27 calls. And cap retries with a budget (say, at most 10% extra traffic).
- Circuit breaker so a failing dependency stops consuming your resources.
- Idempotency key for anything that mutates state — because retries mean duplicates.
Plus, at the fleet level: service discovery (services register in a registry — Consul, etcd, Kubernetes DNS — rather than hardcoding addresses, since instances come and go constantly).
#Service mesh
Rather than every service implementing retries, mTLS, circuit breaking, and tracing in its own language, a sidecar proxy (Envoy, via Istio/Linkerd) is deployed alongside each service and intercepts all traffic.
┌──────────────────┐ ┌──────────────────┐
│ Service A │ proxy│◄──────►│ proxy │ Service B│
└──────────────────┘ mTLS └──────────────────┘
▲ ▲
└──── control plane ───────┘
(policy, certs, config)The control plane is the central component that tells every proxy what to do — routing rules, retry policies, and the certificates for mTLS (mutual TLS, where both sides of a call prove their identity, not just the server).
Gains: consistent behaviour across services written in different languages (polyglot), mTLS everywhere without code changes, fine-grained traffic control configured centrally (send 1% of traffic to a new version as a canary, deliberately inject failures to test resilience, set retries), and uniform observability.
Costs: a proxy hop on every call (~1 ms), significant memory per pod, and a genuinely complex control plane to operate. For a handful of services this is a bad trade — libraries are simpler. It pays off at dozens-to-hundreds of services, especially across multiple languages.
The mature interview position: "A mesh solves real problems, but it's a large operational commitment. Below ~20 services I'd use a shared client library; above that, and especially with multiple languages, the mesh earns its cost."
#API design details that get noticed
- Versioning —
/v1/in the path is blunt and clear; header-based versioning is cleaner and harder to debug. Whichever you pick, have a deprecation policy. - Pagination — use cursors, not offsets.
OFFSET 10000forces the database to scan and discard 10,000 rows, and results shift under concurrent inserts (a new row at the top pushes everything down, so the user sees one item twice). A cursor (after=<opaque_token>) encodes where the last page ended — say, "after created_at = 10:42, id = 9876" — so the database jumps straight there using an index. The cost doesn't grow with page number, and inserts don't shift the pages. - Idempotency keys on all mutating endpoints — the client generates a UUID, the server stores the result and returns the same response on retry.
- Consistent errors — a machine-readable code plus a human message, and never leak internals in messages.
- Field filtering / partial responses — cheap way to get much of GraphQL's benefit in REST.
- Never trust the client. Validate everything server-side, including things the UI already validated.
The same pattern now sits in front of model providers too. An LLM gateway adds the parts ordinary gateways don't know about — limits counted in tokens rather than requests, routing between models, fallback across providers, and caching that respects prompt prefixes. See LLM gateways.
#Check yourself
What belongs in an API gateway, and what doesn't?Show answer
How do you keep the gateway from amplifying a backend failure?Show answer
Why "REST at the edge, gRPC inside"?Show answer
What does GraphQL fix, and what three hazards come with it?Show answer
What is the Backend-for-Frontend pattern?Show answer
Synchronous call or event: what's the practical rule?Show answer
Name the four essentials every remote call needs.Show answer
Why use cursors instead of offsets for pagination?Show answer
#What to carry forward
- A gateway centralises cross-cutting edge concerns — and must stay free of business logic.
- Protect the gateway with timeouts, per-backend breakers and bulkheads; replicate it.
- REST for public APIs, gRPC inside, GraphQL for client-driven aggregation — with its caching, N+1 and cost hazards.
- Call synchronously only for what the user waits on; publish events for side effects.
- Every call needs a timeout, budgeted jittered retries, a breaker and idempotency; a service mesh earns its cost at dozens of services.