Skip to content

API Gateway, Backend-for-Frontend & Service Mesh ​

"Implement an API gateway that is the single entry point for all clients." — Chris Richardson, Pattern: API Gateway / Backends for Frontends, microservices.io

Summary: Once a system is many services used by many kinds of clients, three pieces of infrastructure keep it sane: an API gateway at the edge for the concerns every request shares, a Backend-for-Frontend per client experience to shape and aggregate data, and (sometimes) a service mesh for service-to-service security, resilience and telemetry; each has a clear job, and most failures come from giving one of them the other's job. Focus: The problem (many services, many clients, cross-cutting concerns), gateway responsibilities and the "overambitious gateway", gateway topologies, BFF ownership and duplication, GraphQL as a BFF, aggregation and fan-out cost, API composition versus CQRS read models, the service mesh (data plane, control plane, sidecar versus ambient, mTLS identity, retries, canary), gateway versus mesh versus library, north-south versus east-west, Kubernetes Ingress versus Gateway API, edge concerns, auth patterns, trace propagation, failure modes, with Go (httputil.ReverseProxy) and Laravel 13 code, Traefik, Envoy, Kong, Istio and Gateway API configuration. Learning goal: Given a system with N services and M client types, decide which concerns go to the gateway, which to a BFF, which to a mesh or a library, draw the request path with its timeouts and retries per hop, and explain what each extra hop costs in latency, money and operational risk.

This chapter belongs to the Microservices in Practice group. It assumes Microservices Architecture and Service Communication (sync versus async, retries, idempotency). How callers find instances is in Service Discovery; the networking mechanics are in the System Design chapters on reverse proxies, load balancing, rate limiting algorithms and the deeper Service Mesh & the Sidecar Pattern. This page owns the architectural decision: who does what at which hop.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why these layers exist at allWhy it exists
Netflix Zuul, Richardson, Newman, Linkerd, Istio, Gateway APIWhere it comes from
What a gateway is and doesThe API gateway, Responsibilities
What a gateway must not doThe overambitious gateway
One gateway, per domain, per clientGateway topologies
Backend-for-Frontend, ownership, duplicationBFF, BFF duplication
GraphQL in front of servicesGraphQL as a BFF
Fan-out latency and partial failureAggregation and fan-out
API composition or a read modelComposition vs CQRS
Sidecars, ambient, control planeService mesh, Mesh features, Mesh costs
Inbound versus internal trafficNorth-south vs east-west
Ingress, Gateway API, GAMMAIngress vs Gateway API
CDN, WAF, DDoSEdge concerns
JWT at the edge, identity headers, token exchange, mTLSAuth patterns
traceparent through proxiesObservability
Kong, Envoy, NGINX, Traefik, Istio, Linkerd side by sidePer-product behaviour
Request path, retry multiplication, headers, xDS, status codesMechanics
Chatty clients, spoofed headers, canaries, retry storms, SPOFSolving the classic problems
Go gateway and BFF, Laravel BFF, proxy configsGo, Laravel, Configuration
Gateway or mesh or libraryChoosing
Monolith to distributedIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
API gatewayOne front door for all external calls; does the chores every request needsKong, Envoy, Traefik, NGINX in front of 30 servicesEvery service re-implements TLS, auth, limits, logging, each slightly differently
BFF (Backend-for-Frontend)A small server per client experience that speaks that client's languageMobile BFF returns one home payload instead of five callsThe phone makes many slow calls; one generic API bloats for every client
Service meshProxies next to (or under) every service, managed centrally, handling service-to-service trafficIstio, LinkerdEach team hand-rolls mTLS, retries and metrics in each language
Data planeThe proxies that actually carry requestsEnvoy sidecars, Istio ztunnel, linkerd2-proxyNo one between services to enforce policy
Control planeThe brain that configures the proxies and issues certificatesistiod, Linkerd control planeProxies with stale or inconsistent config
North-southTraffic entering or leaving the systemPhone to gatewayEdge controls applied to internal calls, or missing at the edge
East-westTraffic between internal servicesOrders calls PaymentsInternal calls treated as trusted because "they are inside"
Aggregation (API composition)Calling several services and merging the answersBFF joins user and ordersClient-side joins over a mobile network
Canary / traffic splitSending a small share of traffic to a new version90/10 weightsAll users hit a bad release at once
Identity headersHeaders the gateway sets after verifying a tokenX-User-Id: 42Services re-validate tokens, or trust a header a client forged

Who does what. The rule of thumb this page defends.

ConcernAPI gatewayBFFService meshLibrary in the service (Go, Laravel)
TLS from the internetYes (termination)NoNoNo
End-user authentication (JWT, OAuth2)Validate token, set identityUse identity; session for webCan validate JWT (Istio RequestAuthentication)Fine-grained authorization on the resource
Rate limitingPer client, per API key, coarsePer screen if neededPer destination, protectivePer resource, business limits
Routing and versioningYes, by path, host, headerIts own routesInternal routing, subsetsNo
Aggregation and response shapingOnly trivialYes, this is its jobNoDomain responses only
Retries, timeouts, circuit breakingEdge timeouts, careful retriesPer upstream callYes, uniform for all languagesYes, with domain knowledge (idempotency)
mTLS between servicesGateway to first hopClient of the meshYes, automaticPossible, painful at scale
Canary and traffic splittingEdge splitsNoInternal splitsFeature flags instead
Metrics, logs, tracesEdge viewScreen viewUniform golden signalsBusiness spans and trace propagation
Business rulesNeverPresentation logic onlyNeverYes, here and only here

What each layer costs.

LayerLatencyMoney and resourcesOperational risk
GatewayOne extra hop (sub-millisecond on a LAN plus TLS)A few replicasSingle point of failure if not replicated; config drift
BFFOne hop plus the slowest upstream callOne service per client experienceDuplication between BFFs
Sidecar meshTwo proxies per call (client and server side)Istio 1.24 measured about 0.20 vCPU and 60 MB per sidecar at 1000 rpsUpgrades touch every pod; complex debugging
Ambient meshTwo ztunnel hops, plus a waypoint for L7About 0.06 vCPU and 12 MB per ztunnel (Istio 1.24)Newer; feature gaps versus sidecar
LibraryNoneDeveloper time per languageInconsistent behaviour across teams and languages

Why it exists ​

Split a monolith into twenty services and put three kinds of clients in front of it (a web app, a mobile app, partners). Without any layer in between, every client must know twenty hostnames, every service must terminate TLS and validate tokens, every service implements rate limits and access logs in its own language, and the phone makes eight calls to draw one screen. Richardson's pattern page lists the forces precisely: microservices expose fine-grained APIs while clients need coarse ones, "Different clients need different data", mobile networks are slower, instance locations change, partitioning changes over time, and some internal protocols "might not be web friendly" (saved text: microservices-io-apigateway).

Without the layersWith gateway, BFF and (maybe) mesh
Clients know internal topology; a service split breaks the appClients see one stable host and a contract; topology is hidden
TLS, auth, limits, logging copied into every serviceDone once at the edge, uniformly
Phone does 8 round trips over 4G for one screenOne call to the BFF; the 8 calls happen inside the data centre
A generic API grows a flag for every client's needsEach client team shapes its own BFF
Service-to-service traffic is plaintext and unobservedmTLS identity and golden metrics for every call
Fewer moving partsMore hops, more config, more things to operate

The analogy we reuse: a large hotel. The front desk (gateway) checks every guest's ID once, hands out key cards, and points people to the right floor; it does not cook. The concierge for business guests and the concierge for families (BFFs) know what their guests want and assemble it from several departments: a business guest gets a meeting room, a taxi and a late checkout in one request. Behind the scenes, the internal phone system with badge readers (mesh) connects departments, checks that the caller really is the kitchen, retries busy lines and logs every call. Put the menu planning at the front desk and the queue stops (overambitious gateway); make one concierge serve everyone and they become a bottleneck (general-purpose BFF).

Three common misunderstandings, up front ​

  1. "A service mesh replaces the API gateway." No. A gateway faces untrusted clients, a public contract and end users (north-south). A mesh connects known workloads inside (east-west). Istio even ships an ingress gateway, but that is a gateway, configured as one.
  2. "The BFF is just a second gateway." No. A gateway is generic infrastructure owned by a platform team; a BFF is application code owned by a client team, shaped for one experience.
  3. "With a mesh, my code does not need to think about retries or tracing." No. The mesh cannot know whether a POST is idempotent, and it cannot join spans unless your code forwards the trace headers (Istio says so explicitly; see Observability).

Where it comes from ​

Netflix API and Zuul (2013). The Netflix tech blog announced Zuul on 12 June 2013 (saved text: netflix-zuul, archived copy):

"The Netflix API is the front door to that system, supporting over 1,000 different device types and handing over 50,000 requests per second during peak hours." — Netflix Technology Blog, Announcing Zuul: Edge Service in the Cloud, 2013

Zuul was a chain of filters by type: PRE filters for "request authentication, choosing origin servers, and logging debug info", ROUTING filters that send the request to an origin, POST filters that add headers, gather metrics and stream the response, and ERROR filters. Filters were Groovy, loaded at run time from disk. The post also describes client teams pushing "server-side client adapter scripts", which is the seed of the BFF idea: device-specific code living on the server side of the edge.

Richardson's pattern (microservices.io). Chris Richardson's API Gateway page names the problem ("How do the clients of a Microservices-based application access the individual services?"), the two ways of handling a request (proxy/route, or fan out to several services), and lists Backends for Frontends as a variation: "It defines a separate API gateway for each kind of client." It names the drawbacks too: "Increased complexity" and "Increased response time due to the additional network hop through the API gateway".

Sam Newman and the BFF. Newman's pattern article describes the general-purpose API backend becoming a bottleneck and the alternative he saw at REA and SoundCloud:

"... rather than have a general-purpose API backend, instead you have one backend per user experience - or as (ex-SoundClouder) Phil Calçado called it a Backend For Frontend (BFF)." — Sam Newman, Pattern: Backends For Frontends, samnewman.io (saved text: samnewman-bff)

The overambitious gateway warning (2017, 2018). The Thoughtworks Technology Radar put "Overambitious API gateways" on Hold in November 2017 and May 2018:

"This results in overambitious API gateway products whose functionality — on top of what is essentially a reverse proxy — encourages designs that continue to be difficult to test and deploy." — Thoughtworks Technology Radar, Overambitious API gateways (saved text: thoughtworks-overambitious)

Proxies and meshes. Envoy describes itself as "an L7 proxy and communication bus designed for large modern service oriented architectures", built on the belief that "The network should be transparent to applications", with an out-of-process architecture that "works with any application language" (saved text: envoy-what-is). Linkerd, "the first service mesh project, was admitted to the Cloud Native Computing Foundation in early 2017, rewritten to use Rust micro-proxies in 2018" (saved text: linkerd-what). Istio "has been built on the sidecar pattern from its first release in 2017"; ambient mode was "Launched in 2022" and, "As of Istio 1.22, it is production-ready for single cluster use cases" (saved text: istio-dataplane-modes).

Kubernetes Ingress to Gateway API. Kubernetes Ingress is stable since v1.19; the current docs say "The Kubernetes project recommends using Gateway instead of Ingress" and "The Ingress API has been frozen" (saved text: k8s-ingress). Gateway API describes itself as "the next generation of Kubernetes Ingress, Load Balancing, and Service Mesh APIs", with the GAMMA initiative using the same route resources for mesh (east-west) traffic (saved text: gateway-api-io).

text
     Year   Event                                                  What it changed
1    2013   Netflix announces Zuul (filters: PRE, ROUTING, POST)    Edge service as programmable gateway
2    2015   Newman's BFF article (REA, SoundCloud practice)         One backend per user experience
3    2016   Envoy open-sourced by Lyft                               Out-of-process L7 proxy, xDS APIs
4    2017   Linkerd joins CNCF; Istio 1st release (sidecars)         Service mesh becomes mainstream
5    2017   Radar: "Overambitious API gateways" on Hold              Logic in middleware called out
6    2018   Linkerd 2 rewritten with Rust micro-proxies              Lighter data plane
7    2020   Kubernetes Ingress GA in v1.19                           One standard edge resource
8    2022   Istio ambient mode launched (ztunnel + waypoint)         Sidecar-less mesh
9    2024   Istio 1.22: ambient production-ready (single cluster)    Mesh without per-pod proxies
10   now    Ingress frozen; Gateway API + GAMMA                      One API for north-south and east-west

The years in rows 2, 3, 7 and 9 come from secondary knowledge (the pages we saved print the BFF practice, Envoy, "Stable since Kubernetes v1.19" and "As of Istio 1.22" without those dates); the other rows are dated by the saved pages.

The concept catalogue ​

The API gateway {#gateway} Must-know ​

In plain words: A reverse proxy that every external request passes through, configured to do the boring but critical chores once: terminate TLS, check who you are, count how often you call, send you to the right service, and record what happened.

Common misunderstanding: "An API gateway is a product category you buy." It is a role. Kong describes itself honestly: "An API gateway is a reverse proxy that lets you manage, configure, and route requests to your APIs" (saved text: kong-gateway). NGINX with a few modules, Envoy, Traefik, or 200 lines of Go with httputil.ReverseProxy can all play it.

Definition: A server-side component at the boundary of a system that exposes one entry point (host, port, contract) for external clients, routes each request to an internal service, and applies cross-cutting policies (security, traffic, observability) before and after routing. It is a Facade at network level (Structural Patterns).

text
     Client (phone)                 Gateway                                   Orders service
1    GET /orders  Bearer eyJ...  ->
2                                   TLS handshake terminated here
3                                   validate JWT (signature, exp, aud)  -> 401 if bad
4                                   rate limit: user 42 has 3 tokens left -> 429 if empty
5                                   route: /orders -> orders-v1 (90) or orders-v2 (10)
6                                   strip client X-User-Id, set X-User-Id: 42, traceparent
7                                   forward with 1 s deadline           ->
8                                                                            handle, 200
9                                <- add X-Request-Id, drop Server header <-
10                                  access log: route, status, latency, trace id

Real scenarios: a marketplace with 40 services behind one api.example.com; a bank exposing a partner API with per-partner quotas and API keys; a SaaS that moved from a monolith and uses the gateway to route /billing to the new service while everything else still hits the monolith (strangler fig); a mobile game routing by X-App-Version header to old and new backends.

ProductHow it is configuredWhere it shines
Kong GatewayAdmin API, or DB-less declarative YAML; plugins (Lua, others)Plugin catalogue (auth, rate limiting, transformations), API management
Envoy (and Envoy Gateway)Static YAML or dynamic xDS APIs from a control planePerformance, observability, the engine under Istio and many gateways
NGINXnginx.conf (proxy_pass, limit_req)Ubiquitous, fast, well understood
TraefikProviders (Docker labels, Kubernetes, files); middlewaresAuto-discovery in Docker and Kubernetes, simple canaries via the file provider
Zuul (Netflix)Filters in JVM languagesHistorical reference for filter-based gateways
Your own (Go httputil.ReverseProxy)CodeFull control, tiny surface, only what you need

How to use it: keep the gateway thin and declarative; review its config like code; replicate it; measure its added latency. Go: the minimal gateway. Products: configuration excerpts.

Gateway responsibilities {#responsibilities} Must-know ​

In plain words: The jobs that are the same for every request regardless of which service answers.

Common misunderstanding: "If the gateway can do it, the gateway should do it." Modern gateways can run scripts, call databases and orchestrate flows. Capability is not responsibility; see the overambitious gateway.

Definition: The responsibilities below are cross-cutting (they apply to many routes) and policy-like (configured, not programmed).

ResponsibilityWhat it meansExample knob (product)Pitfall
RoutingMap host, path, method or header to a backendEnvoy routes[].match.prefix; Traefik PathPrefix; Gateway API HTTPRouteOrder of rules; overlapping prefixes
Authentication offloadValidate the token once, pass identity onEnvoy jwt_authn with remote_jwks and claim_to_headers; Kong jwt pluginForgetting to strip client-sent identity headers
Coarse authorizationIs this client allowed to call this API at all? (scopes)Istio AuthorizationPolicy; Kong ACLPutting per-record rules here
Rate limiting and quotasProtect services; enforce plansNGINX limit_req; Kong rate-limiting (policy: local, cluster, redis); Envoy local and global rate limit; Traefik rateLimitPer-node counters that multiply with replicas
TLS terminationHandle certificates and HTTPS at the edgeGateway API listeners[].tls.mode: TerminatePlaintext behind the gateway on a shared network
Request and response transformationAdd, remove, rename headers; small body rewritesKong request-transformer; Envoy header manipulationBusiness mapping creeping in
AggregationCombine several calls into one responsePossible in Kong or Envoy with scriptingBelongs in a BFF, see below
CachingCache idempotent GETs at the edgeNGINX proxy_cache; CDN in frontCaching per-user data without Vary/private
Protocol translationREST/JSON outside, gRPC insidegrpc-gateway (Go), Envoy gRPC-JSON transcoderLeaking internal message shapes as public contract
VersioningRoute /v1 and /v2, or by headerPath or header matchKeeping dead versions forever
ObservabilityAccess logs, RED metrics, start or continue tracesEnvoy x-request-id, traceparent; Traefik access logLogging tokens or PII
Resilience at the edgeTimeouts, limited retries, circuit breakersEnvoy retry_policy, circuit_breakers; Traefik retryRetrying non-idempotent requests

Rate limiting algorithms (token bucket, leaky bucket, fixed and sliding windows) are taught in Rate Limiting; this page only decides where the limiter sits.

Protocol translation with grpc-gateway (Go). The grpc-gateway project "reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC" (saved text: grpc-gateway-readme). You annotate the proto:

proto
import "google/api/annotations.proto";

service OrderService {
  rpc GetOrder(GetOrderRequest) returns (Order) {
    option (google.api.http) = { get: "/v1/orders/{id}" };
  }
}

The generated handler turns GET /v1/orders/42 into a GetOrder gRPC call. Deep dive: gRPC & Protobuf in Go and gRPC.

The overambitious gateway (anti-responsibilities) {#overambitious} Important ​

In plain words: A gateway that has started to contain business logic: price calculations, order workflows, data joins that know domain rules. It becomes the new monolith, owned by one team that every other team waits for.

Common misunderstanding: "Putting logic in the gateway saves a service." It moves the logic to the one place that every request crosses, that is hardest to test, that is usually written in a configuration language or a plugin system, and whose deploys affect everyone. The Radar's words: "business logic and process orchestration implemented in middleware ... creating single points of scaling and control".

Definition: An anti-pattern in which a gateway product's extensibility (scripts, plugins, workflow engines) is used for domain behaviour, recreating the Enterprise Service Bus problems of the SOA era (Service-Oriented Architecture). Fowler and Lewis contrasted that with "smart endpoints and dumb pipes" (saved text: fowler-microservices).

text
     Week   Change request                               Where it went          Result
1    1      "Add 10% VAT for EU users"                    gateway Lua plugin     works
2    3      "Hide out-of-stock items for mobile"          gateway transform      works
3    6      "Apply loyalty discount before VAT"           gateway plugin v2      plugin order matters
4    9      Pricing service changes field names           gateway breaks         every route redeployed
5    12     Gateway team has a 3-week backlog             all teams blocked      gateway = monolith

Real scenarios: promotion rules inside an API management product; a gateway that calls the database to enrich tokens with roles; "orchestration policies" chaining five backend calls with error handling in XML.

Rule: the gateway may know who is calling and where to send it; it must not know what the business does. Presentation shaping belongs to a BFF; domain rules belong to the owning service.

Gateway topologies: single, per-domain, per-client {#topologies} Important ​

In plain words: You can have one gateway for everything, one per business area, or one per kind of client (which is the BFF idea).

Common misunderstanding: "Exactly one gateway per company." Large systems usually run several: an edge gateway for TLS and auth, then per-domain or per-client gateways behind it.

Definition:

TopologyShapeGood forWatch out for
Single gatewayAll clients, all routes, one configSmall and medium systems, one platform teamConfig becomes a shared hot spot; one team bottleneck
Per-domain gatewaypayments-gw, catalog-gw, each owned by the domainMany teams, clear domains, different SLAsDuplicate edge policy; clients see several hosts unless an edge router sits in front
Per-client gateway (BFF)Web, mobile, partnerDifferent client needs and release cyclesDuplication between BFFs
LayeredEdge gateway (TLS, WAF, auth) then BFFs or domain gatewaysMost large platformsExtra hop; who owns which policy must be written down
ClientsEdgeGatewayBFFs (client teams)Domain servicesWeb SPAiOS / Androidslow networkPartnerCDNWAFDDoSAPI gatewayTLS terminationJWT validationrate limitingrouting, canarytrace id, logsno business logicWeb BFFMobile BFFPublic APIversionedUsersOrdersCatalogPaymentsservice mesh: mTLS, retries, telemetryReading the picture1. One gateway owns cross-cutting edge concerns for every client; it routes, it does not compose screens.2. Each BFF is owned by the team that owns its client and fans out to several services (aggregation).3. Inside the dashed box, service-to-service calls (east-west) go through the mesh, not the gateway.Arrows show the request direction; responses travel back along the same path.

The picture is the layered topology: one edge layer and gateway for all clients, one BFF per client experience behind it, and domain services connected by the mesh.

Backend-for-Frontend (BFF) {#bff} Must-know ​

In plain words: A small backend written for one front end. It calls the domain services, picks the fields that screen needs, formats them, and answers in one round trip.

Common misunderstanding: "BFF means one per platform (iOS, Android, web)." Newman's rule is about experiences, and he reports both models: one BFF per client type (REA) and one per user-interface type shared by iOS and Android (SoundCloud), with the guideline "one experience, one BFF".

Definition: A server-side component dedicated to one user experience, "tightly coupled to a specific user experience, and will typically be maintained by the same team as the user interface" (Newman). It sits inside the perimeter, behind the edge gateway, and is the right place for screen-specific aggregation, formatting, pagination shape and client-specific caching.

text
     Mobile app                 Mobile BFF (owned by the mobile team)         Users     Orders    Catalog
1    GET /bff/mobile/home  ->
2                               start 800 ms budget
3                               GET /users/42 (400 ms)              ->
4                               GET /orders?user=42&limit=5 (600 ms)          ->
5                                                                     <- 200
6                                                                               <- 200 (12 ms)
7                               pick 3 fields of user, 5 orders, format money
8                          <-   one 2 KB JSON tailored to the home screen

Real scenarios: a mobile home screen (profile, recent orders, recommendations) in one call; a TV app with a tiny payload and different image sizes; a partner API kept stable for years while internal services change; a web BFF that renders server-side HTML (Client-Server rendering models).

ModelWho uses it (Newman's examples)ProsCons
One BFF per client type (iOS BFF, Android BFF, web BFF)REAEach team fully autonomousMost duplication
One BFF per experience (mobile BFF shared by iOS and Android)SoundCloudLess duplicationRisk of bloat as concerns accumulate
General-purpose API backend for allMany companies before BFFOne codebaseBottleneck, every client's flags in one place

How to use it: the client team owns the BFF; the BFF owns no domain data and no domain rules (it may cache); it degrades when optional upstreams fail. Go: BFF with concurrency and timeouts. Laravel: BFF with Http::pool.

BFF duplication and ownership {#bff-duplication} Important ​

In plain words: Several BFFs end up writing the same "get user plus orders" code. That is acceptable up to a point; shared code is not free either.

Common misunderstanding: "Duplication between BFFs is a design failure; merge them." Newman says the opposite: merging into "a general-purpose aggregating Edge API service" "has proven time and again to lead to highly bloated code with multiple concerns squashed together", and he is "fairly relaxed about duplicated code across services".

Definition: When duplication hurts, Newman lists the options: a shared library (cheap, but "shared libraries are a prime source of coupling"), or a new downstream service modelled on the domain (for example, the Wishlist service doing the joins itself). His rule of thumb: create the abstraction when you are about to implement something for the third time.

text
     Step   Situation                                                Action
1           Web BFF and mobile BFF both join wishlist + catalog + stock   tolerate (2 copies)
2           Partner BFF needs the same join                            third copy: extract
3a          Join is pure plumbing (HTTP client, retries, auth headers)  shared library, versioned
3b          Join is a domain concept ("wishlist with prices")           push into Wishlist service

Real scenarios: error mapping and auth header propagation code (library); "order summary with shipping status" needed by web, mobile and email (domain service or read model, see composition vs CQRS).

GraphQL as a BFF {#graphql-bff} Good to know ​

In plain words: Instead of a hand-written endpoint per screen, expose a GraphQL schema; each client asks for exactly the fields it needs, and resolvers call the services.

Common misunderstanding: "GraphQL removes the need for BFFs." It replaces hand-written endpoints with a schema and resolvers, but someone still owns that schema, its performance (N+1 resolver calls), its authorization per field and its caching (no plain HTTP caching for POST queries). Federated GraphQL moves aggregation to a router that is, architecturally, a gateway.

Definition: A GraphQL server used as the aggregation layer for one or more clients. The GraphQL learning pages describe it as enabling "flexible, versionless APIs powered by a strong type system", where queries "request exactly the data you need" (graphql.org, saved text: graphql-learn).

ChoiceWhen it winsWhen it hurts
REST BFF per experienceFew screens, strong caching, simple opsMany screens, many clients with different field needs
GraphQL BFFMany clients and screens, fast UI iterationQuery cost control, N+1, per-field auth, caching
Federated GraphQL (router + subgraphs)Many teams each owning part of the graphThe router becomes critical infrastructure

Details: GraphQL, GraphQL in Go.

Aggregation and the fan-out cost {#fan-out} Must-know ​

In plain words: When one request becomes several upstream calls, the response is as slow as the slowest call (if parallel) or the sum (if sequential), and it fails if any essential call fails.

Common misunderstanding: "Parallel calls make aggregation free." Parallel removes the sum, not the tail. If each of 10 upstreams is slow 1% of the time, the chance that at least one is slow is 1 − 0.99^10, about 9.6%: the BFF's p90 now looks like each service's p99. This is the "tail at scale" effect (Latency Budgets & Tail Latency).

Definition: Fan-out is the number of downstream calls per incoming request. Latency of a parallel fan-out ≈ max of the calls; of a sequential chain ≈ sum. Availability of "all must succeed" ≈ product of availabilities.

text
     Upstreams   Each p99 slow   P(at least one slow) = 1 - 0.99^N   Availability if each is 99.9% and all required
1    1           1%              1.0%                                 99.9%
2    5           1%              4.9%                                 99.5%
3    10          1%              9.6%                                 99.0%
4    20          1%              18.2%                                98.0%

Real scenarios: Newman's wishlist (wishlist first, then catalog and inventory in parallel); a product page calling price, stock, reviews, recommendations; a dashboard fanning out to 30 widgets.

What to do: run independent calls concurrently; give each call a timeout inside one overall deadline; mark calls essential or optional and degrade on optional ones (Newman: "if only the Inventory service was down, wouldn't it be better to just degrade the functionality"); cap concurrency; consider hedged requests for idempotent reads (Envoy supports "request hedging" on per-try timeout, saved text: envoy-retries); if the same join is needed on every request, build a read model instead.

API composition vs CQRS read models {#composition-vs-cqrs} Important ​

In plain words: To show data owned by several services, you either ask them all at request time and join in memory (composition), or you keep a pre-joined copy updated by events and read it with one query (read model).

Common misunderstanding: "Composition is the microservices way; read models are over-engineering." Richardson lists both as patterns. Composition's own drawback, in his words: "Some queries would result in inefficient, in-memory joins of large datasets" (saved text: microservices-io-api-composition).

Definition: API Composition: "Implement a query by defining an API Composer, which invoking the services that own the data and performs an in-memory join of the results." CQRS view: "Define a view database, which is a read-only 'replica' that is designed specifically to support that query" (saved text: microservices-io-cqrs). The BFF is a natural API composer; a read model is owned by the service (or BFF) that needs the query.

AspectAPI composition (in a BFF)CQRS read model
FreshnessLiveEventually consistent (lag of the event pipeline)
LatencyMax of upstream callsOne indexed query
AvailabilityNeeds every essential upstream upNeeds only the read store
Filtering, sorting across servicesHard (in-memory join of large sets)Easy (it is one table)
Build costLowEvents, projector, backfill, replay
Good forDetail pages, low fan-outLists, search, dashboards, "orders with customer name sorted by total"
text
     Composition                                         Read model
1    GET /bff/orders?sort=total                          GET /bff/orders?sort=total
2    -> orders: all 10,000 orders of user's company      -> SELECT ... FROM order_summary_view ORDER BY total_cents DESC LIMIT 20
3    -> customers: 10,000 names (or 10,000 calls)        <- 20 rows, 3 ms
4    join and sort in memory, return 20                   (view updated by OrderPlaced, CustomerRenamed events)

A read model owned by the BFF or a reporting service (PostgreSQL):

sql
-- One row per order, pre-joined with the data the screen needs.
CREATE TABLE order_summary_view (
    order_id       bigint PRIMARY KEY,
    company_id     bigint      NOT NULL,
    customer_name  text        NOT NULL,
    status         text        NOT NULL,
    total_cents    bigint      NOT NULL,
    placed_at      timestamptz NOT NULL,
    source_version bigint      NOT NULL   -- last event version applied, for idempotent replays
);
CREATE INDEX order_summary_company_total ON order_summary_view (company_id, total_cents DESC);

-- Projector: apply OrderPlaced idempotently (at-least-once delivery).
INSERT INTO order_summary_view (order_id, company_id, customer_name, status, total_cents, placed_at, source_version)
VALUES ($1, $2, $3, 'placed', $4, $5, $6)
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status, total_cents = EXCLUDED.total_cents, source_version = EXCLUDED.source_version
WHERE order_summary_view.source_version < EXCLUDED.source_version;

-- Projector: CustomerRenamed touches many rows; that is the price of denormalising.
UPDATE order_summary_view SET customer_name = $2 WHERE company_id = $1;

-- The screen's query: one index range scan instead of a cross-service join.
SELECT order_id, customer_name, status, total_cents
FROM order_summary_view
WHERE company_id = $1
ORDER BY total_cents DESC
LIMIT 20;

The event plumbing (outbox, idempotent consumers) is in Transactional Outbox, Idempotent Consumers and Event Sourcing & CQRS; data ownership rules are in Data Ownership in Microservices.

Service mesh {#mesh} Must-know ​

In plain words: Put a smart proxy in the path of every service-to-service call, and have one central brain configure all of them. Your services then get encryption, identity, retries, traffic splitting and metrics without code changes.

Common misunderstanding: "A mesh is a product you install, then you are done." It is a second distributed system in your cluster with its own upgrades, certificate authority, failure modes and learning curve. And it is not magic: it cannot propagate trace context or decide idempotency for you.

Definition: Richardson's pattern: "Use a service mesh that mediates all communication in and out of each service" (saved text: microservices-io-mesh). Istio's docs split it in two: "The data plane is the set of proxies that mediate and control all network communication between microservices", and "The control plane manages and configures the proxies in the data plane" (saved text: istio-dataplane-modes). The control plane's job in one sentence:

"The control plane takes your desired configuration, and its view of the services, and dynamically programs the proxy servers, updating them as the rules or the environment changes." — Istio, What is Istio? (saved text: istio-what)

Control plane (istiod, Linkerd control plane)service discovery · routing and policy config · CA issuing workload certificatesconfig (xDS) + certs pushed down; requests never pass through the control planeData plane: sidecar modePod AappEnvoyPod BEnvoyappmTLSL7 work on both sides: 2 proxies per hopone proxy per pod: memory x replicasData plane: ambient modeNode 1appztunnelNode 2ztunnelappHBONE mTLS (L4)waypointEnvoy, optional L7per-node L4 proxy; L7 only where a waypoint is addedBoth modes give mTLS identity, telemetry and policy without code changes; retries, timeouts, canary splitsand header-based routing are L7 features: sidecar Envoy in sidecar mode, a waypoint in ambient mode.

The picture shows the control plane pushing configuration and certificates (never carrying requests), and the two Istio data plane modes. In sidecar mode, Istio "deploys an Envoy proxy along with each pod"; in ambient mode, it "uses a per-node Layer 4 proxy, and optionally a per-namespace Envoy proxy for Layer 7 features". The per-node proxy is ztunnel, written in Rust and "intentionally scoped to handle L3 and L4 functions such as mTLS, authentication, L4 authorization and telemetry"; the optional L7 proxy is the waypoint, "a deployment of the Envoy proxy" (saved text: istio-ambient). The tunnel between ztunnels is HBONE, an HTTP CONNECT-based tunnelling protocol.

text
     Sidecar mode, Orders -> Payments                      Ambient mode, Orders -> Payments
1    orders app writes plain HTTP to localhost              orders app writes plain HTTP
2    iptables redirects to the local Envoy sidecar          traffic redirected to the node's ztunnel
3    sidecar: route, retry policy, mTLS handshake           ztunnel: mTLS (HBONE), L4 policy
4    payments' sidecar: verify cert, authz policy, metrics  (waypoint Envoy here if L7 policy is needed)
5    payments' sidecar -> payments app on localhost         payments' ztunnel -> payments app
6    L7 processing happened twice                           L7 processing once (waypoint) or not at all
Aspect (Istio docs)Sidecar modeAmbient mode
Proxy placementEnvoy in every podztunnel per node; waypoint per namespace or service, optional
Adding workloads"Label a namespace and restart all pods""Label a namespace - no pod restart required"
L7 processing steps2 (source and destination sidecar)1 (destination waypoint)
ResourcesProvisioned per pod for worst caseWaypoints autoscale; ztunnel per node
Security model"Strongest: each workload has its own keys""Strong: each node agent has only the keys for workloads on that node"
Support"Stable, including multi-cluster""Stable, only single-cluster" (as listed on the page we read)
Kubernetes Jobs"Complicated by long life of sidecar""Transparent"

Linkerd uses its own Rust micro-proxy (linkerd2-proxy) as a sidecar; it "automatically enables mutually-authenticated Transport Layer Security (mTLS) for all TCP traffic between meshed pods" by default (saved text: linkerd-mtls), and does "latency-aware load balancing" (saved text: linkerd-what).

Mesh features: mTLS identity, resilience, traffic splitting, observability {#mesh-features} Must-know ​

In plain words: What you get from the mesh on day one is encryption with real service identity and uniform metrics; what you configure later is retries, timeouts, outlier ejection and canary weights.

Common misunderstanding: "mTLS in the mesh means authorization is done." mTLS proves which workload is calling. Whether that workload may call this path, and whether the end user behind it may see this record, are separate decisions (an AuthorizationPolicy, then your code).

Definition and per-product behaviour:

FeatureIstioLinkerdNotes
mTLSShort-lived X.509 certificates encoding the service account identity, SPIFFE format; PeerAuthentication mode: STRICT or PERMISSIVE ("Connection can be either plaintext or mTLS tunnel")On by default for meshed TCP trafficPERMISSIVE is for migration only
Service-to-service authorizationAuthorizationPolicy with principals (in ambient: L4 by ztunnel, L7 needs a waypoint)Server / AuthorizationPolicy resourcesIdentity comes from the certificate, not the IP
Retries"The default retry behavior for HTTP requests is to retry twice before returning the error"; retries.attempts, perTryTimeout, retryOnOpt-in via retry.linkerd.io/http annotations on HTTPRoute/ServiceDefaults differ: know yours
Timeouts"The Envoy timeout for HTTP requests is disabled in Istio by default"; set timeout on the routetimeout.linkerd.io/requestNo timeout means a hung upstream holds connections
Circuit breakingDestinationRule.trafficPolicy.connectionPool limits plus outlierDetection (consecutive5xxErrors, interval, baseEjectionTime)Failure accrual and latency-aware balancingEnvoy-style breakers limit concurrency; they are not Hystrix-style open/closed
Traffic splittingVirtualService route weight across DestinationRule subsetsHTTPRoute backendRefs weightsCanary, A/B, blue-green
Fault injectionDelays and aborts per routeNot a built-in route feature; done by splitting traffic to a failing backendFor chaos testing (Chaos Engineering)
TelemetryGolden metrics (rate, errors, duration), access logs, spansGolden metrics per route, linkerd vizSpans still need header propagation by the app

Envoy's own circuit breakers are "fully distributed (not coordinated)": cluster maximum connections, maximum pending requests, maximum requests and "Cluster maximum active retries" (saved text: envoy-cb).

Mesh costs and when you do not need one {#mesh-costs} Important ​

In plain words: A mesh adds proxies to every call and a control plane to operate. If you have a handful of services in one language with good libraries, it may cost more than it gives.

Common misunderstanding: "Proxies are free because they are fast." Each proxy is fast, but there are many of them: Istio's own measurements (1.24, 1000 rps of 1 KB requests) show "a single sidecar proxy with 2 worker threads consumes about 0.20 vCPU and 60 MB of memory", a waypoint about 0.25 vCPU and 60 MB, "a single ztunnel proxy consumes about 0.06 vCPU and 12 MB of memory" (saved text: istio-performance). Multiply by 500 pods. Latency: in sidecar mode "a request will pass through the client sidecar proxy and then the server sidecar proxy"; the actual numbers depend on your traffic, so measure.

Definition: The cost model has three parts: per-request latency (extra hops, extra TLS), per-pod or per-node resources, and operational complexity (CRDs, upgrades, certificate rotation, debugging through proxies).

SignalYou probably do not need a mesh yetYou probably do
Number of servicesUnder ~10Dozens or hundreds
LanguagesOne or two, with mature librariesMany, or legacy you cannot change
Security requirementTLS at the edge, private network acceptedZero trust, encryption and identity for every internal hop (compliance)
TeamNo platform teamA platform team that can own it
Traffic managementRolling deploys are enoughFrequent canaries, per-route policies, multi-cluster
RuntimeVMs or simple Docker ComposeKubernetes

Cheaper alternatives: TLS plus a resilience library (Timeouts, Retries & Jitter, Circuit Breaker); OpenTelemetry SDKs for telemetry; mTLS in code (HTTP/2, HTTPS, TLS & mTLS in Go); ambient mode for L4 encryption only.

North-south vs east-west {#north-south} Must-know ​

In plain words: North-south is traffic crossing the boundary of your system (users in, calls out to providers). East-west is traffic between your own services.

Common misunderstanding: "East-west is trusted because it is inside the network." Zero trust assumes the network is hostile: a compromised pod can call anything it can reach. East-west needs identity too, just a different kind (workload certificates instead of user tokens). See Authorization Models & Zero Trust.

Definition: Directional names from network diagrams: the internet on top (north), the data centre below (south), services side by side (east and west). Gateway API's documentation uses the same split: its routes serve "both North-South (Ingress) and East-West (Mesh) traffic" (saved text: gateway-api-io).

Internet clientsnorth-south (ingress)cluster / VPC (trust boundary)Ingress / API gatewayGateway API: GatewayMobile BFFOrdersPaymentseast-westeast-westservice mesh (or client libraries): mTLS, retries, timeouts, telemetryEgress gatewayto PSPNorth-south: untrusted callers, public contract, edge security, coarse rate limits. East-west: known workloads,internal contracts, identity by certificate, fine-grained resilience. The same proxy engine (Envoy) can serve both.

The picture shows ingress through the gateway, internal calls under the mesh, and egress through an egress gateway (for example to a payment provider), which gives one place to control and audit outbound traffic.

PropertyNorth-southEast-west
CallerUnknown, untrusted (users, partners, bots)Known workloads
IdentityUser token (JWT, OAuth2), API keyWorkload certificate (mTLS, SPIFFE)
ContractPublic, versioned, long-livedInternal, evolves faster
Typical controlsWAF, DDoS protection, TLS, auth, quotasmTLS, authz by service, retries, timeouts, outlier ejection
ToolAPI gateway, Ingress, Gateway API GatewayMesh, client libraries, Gateway API GAMMA routes
Rate limitsPer client and planPer destination to protect capacity

Kubernetes Ingress vs Gateway API {#ingress-vs-gateway-api} Important ​

In plain words: Ingress is the old, simple Kubernetes resource for HTTP routing into a cluster. Gateway API is its successor: richer, split by role, and usable for both edge and mesh routing.

Common misunderstanding: "Gateway API is an API gateway." The Gateway API FAQ answers this: an API gateway "aggregates unique application APIs, making them all available in one place"; Gateway API "is an interface, defined as a set of Kubernetes resources, that models service networking in Kubernetes". Many API gateways implement it.

Definition: Ingress is "An API object that manages external access to the services in a cluster, typically HTTP", which "may provide load balancing, SSL termination and name-based virtual hosting"; it is frozen: "The Ingress API is generally available ... The Kubernetes project has no plans to remove Ingress", but it "is no longer being developed" (saved text: k8s-ingress). Gateway API is "role-oriented": GatewayClass (which controller, owned by the infrastructure provider), Gateway (listeners, TLS, owned by cluster operators), HTTPRoute / GRPCRoute (routing rules, owned by application developers) (saved text: k8s-gateway-api).

AspectIngressGateway API
StatusStable since v1.19, frozenStandard channel: Gateway, GatewayClass, HTTPRoute stable
RolesOne object for everythingGatewayClass / Gateway / Routes per persona
ProtocolsHTTP(S)HTTP, gRPC (GRPCRoute), others in channels
Traffic weighting, header matchingController-specific annotationsIn the spec (backendRefs[].weight, header matches)
Mesh (east-west)NoGAMMA: routes attached to a Service
PortabilityLow (annotations differ per controller)Higher (same resources across implementations)

Config: Gateway API excerpt. Kubernetes basics: Containers & Kubernetes.

Edge concerns: CDN, WAF, DDoS {#edge} Good to know ​

In plain words: In front of the gateway there is usually a global edge network that caches static content, absorbs floods and filters known attack patterns, so your gateway only sees legitimate traffic.

Common misunderstanding: "The gateway's rate limiter protects us from DDoS." A volumetric attack saturates your links or load balancers before a per-user token bucket ever runs. Rate limiting is for fairness and protection from heavy clients; DDoS protection is a network-scale service.

Definition: CDN caches responses near users (CDNs). WAF (web application firewall) inspects HTTP requests for attack patterns; Cloudflare's WAF docs describe it as giving "automatic protection from vulnerabilities and the flexibility to create custom rules" (saved text: cloudflare-waf). DDoS protection absorbs volumetric and protocol attacks (DDoS Protection). The order is usually CDN/WAF/DDoS, then load balancer, then gateway.

LayerStopsDoes not stop
CDNLoad from cacheable GETs, distance latencyDynamic per-user traffic
WAFSQL injection and XSS patterns, bad bots (rules)Business-logic abuse, broken authorization
DDoS serviceFloods (L3/L4, L7 at scale)A slow, valid-looking abusive client
Gateway rate limiterPer client overuse, plan quotasFloods
Service-level limitsExpensive operations per userAnything before it reaches the service

Auth patterns at the gateway {#auth} Must-know ​

In plain words: Check the user's token once at the edge, then tell the services who the user is in a way they can trust; services still decide what that user may do with their data.

Common misunderstanding: "If the gateway authenticates, services can trust any X-User-Id header." Only if nobody else can reach the service or set that header. If a pod, a debug port-forward or a misrouted request reaches the service directly, a forged header is an instant account takeover. This is header spoofing.

Definition: Four patterns, often combined:

PatternHowStrengthCost
Gateway validates JWT, passes identity headersVerify signature with JWKS, exp, aud; strip inbound identity headers; set X-User-Id, scopesSimple, fastServices must only accept those headers from the gateway
Pass the JWT throughGateway validates, forwards the original AuthorizationServices can re-verify, no trust in headersEvery service verifies (cheap with cached JWKS)
Token exchange (RFC 8693)Gateway or BFF swaps the user token for a downstream token with narrower audience and scopesLeast privilege per hop, delegation is explicitAn STS call (cacheable); more moving parts
mTLS to servicesMesh or code presents a workload certificateProves the caller is the gateway or BFFCertificate management (a mesh automates it)

RFC 8693 (January 2020) "defines a protocol for an HTTP- and JSON-based Security Token Service (STS) by defining how to request and obtain security tokens from OAuth 2.0 authorization servers, including security tokens employing impersonation and delegation", with grant type urn:ietf:params:oauth:grant-type:token-exchange (saved text: rfc8693).

text
     Phone                 Gateway                          Orders (Laravel)                  Attacker pod in cluster
1    Bearer eyJ(sub=42) ->
2                          verify JWT, delete X-User-Id
3                          set X-User-Id: 42 + mTLS cert  ->
4                                                           accept: caller is gateway (cert)
5                                                                                              GET /orders  X-User-Id: 1
6                                                           reject: no gateway cert / token   (header ignored)

Laravel note: Laravel's docs say: "If your application absolutely needs to support OAuth2, then you should use Laravel Passport", while for "a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum" (saved text: laravel-passport). A Laravel BFF typically authenticates the phone with Sanctum; a Laravel downstream service trusts the gateway's identity only with proof (middleware). JWT details: JWT Deep Dive; OAuth2: OAuth 2.0 & OIDC; mTLS: Mutual TLS.

Observability through gateway and mesh {#observability} Important ​

In plain words: Every proxy can log and time requests, but to see one user request as one trace across gateway, BFF and services, the trace id must travel in a header through every hop, including through your code.

Common misunderstanding: "The mesh traces automatically." The proxies emit spans, but a proxy cannot tell which outbound call was caused by which inbound call inside your process:

"Applications must propagate this information in HTTP headers, so that when proxies send spans, the backend can join them together into a single trace." — Istio, Distributed Tracing Overview (saved text: istio-tracing)

Definition: Trace context propagation: the W3C traceparent header "identifies the incoming request in a tracing system" (saved text: w3c-tracecontext) as version-traceid-parentid-flags; tracestate carries vendor data. OpenTelemetry's "default propagator uses the headers specified by the W3C TraceContext specification" (saved text: otel-propagation). Envoy also generates and propagates x-request-id and understands B3 (x-b3-*) headers (saved text: envoy-xff).

text
     Hop             traceparent                                                 Span
1    phone           (none)
2    gateway         00-4bf92f3577b34da6a3ce929d0e0e4736-f25a82de12b91300-01     gateway span (new trace or continued)
3    mobile BFF      same trace id, BFF span id as parent of its two calls       BFF span
4    users           00-4bf92f35...-<users call span>-01                          users span
5    orders          00-4bf92f35...-<orders call span>-01                         orders span
     one trace id across all hops = one waterfall in Jaeger, Tempo or Zipkin

The lab shows the Go gateway keeping the caller's trace id (4bf92f35...) and replacing the parent span id. Full treatment: Observability and Messaging Observability.

Per-product behaviour ​

Gateways and edge proxies.

ProductConfig modelRetriesRate limitingAuthCanary
EnvoyStatic YAML or xDSretry_policy: retry_on, num_retries (defaults to 1), per_try_timeout; retry budgets; hedgingLocal and global (external rate limit service; "Per connection or per HTTP request")jwt_authn filter (remote_jwks, claim_to_headers), ext_authzweighted_clusters
Kong GatewayAdmin API, DB-less declarative, KonnectService retriesrate-limiting plugin, policy: local (in memory per node), cluster (data store), redisjwt, key-auth, oauth2, OIDC (Enterprise) pluginsCanary plugin, upstream target weights
NGINXnginx.confproxy_next_upstream (conditions and tries)limit_req (leaky bucket, burst, nodelay)auth_request subrequest, JWT in NGINX Plussplit_clients, upstream weight
TraefikProviders (Docker labels, Kubernetes, file) and middlewaresretry middleware: attempts, initialInterval; "As soon as the server answers, the middleware stops retrying, regardless of the response status" (newer versions add a status option)rateLimit middleware (average, burst)forwardAuth, pluginsweighted service ("only" via File provider or IngressRoute)
Netflix ZuulFilters (PRE, ROUTING, POST, ERROR)Via Ribbon and Hystrix (Zuul 1 era)FiltersFiltersFilters routing to clusters

Meshes.

ProductData planeControl planemTLS defaultRetries defaultNotes
Istio sidecarEnvoy per podistiodPermissive by default, STRICT per namespace/workloadRetry twice; HTTP timeout disabledFull feature set, heaviest
Istio ambientztunnel per node (Rust, L4) plus optional waypoint (Envoy, L7)istiodmTLS for all traffic via HBONEL7 retries need a waypointNo pod restarts to join
Linkerdlinkerd2-proxy (Rust) per podLinkerd control planeOn for all meshed TCPRetries opt-in; timeouts and retries compose since 2.16Small, opinionated

Version notes: Istio numbers and mode support are from the Istio 1.24 performance page and the data plane modes page as fetched for this chapter; Linkerd behaviour from the Linkerd 2 edge docs; Traefik from its v3 reference docs.

Mechanics ​

Life of a request through gateway, BFF and mesh ​

text
     Step  Where                     What happens                                                    Typical budget
1          DNS + edge (CDN, WAF)     resolve, TLS to edge, WAF rules, cache miss                       10-40 ms (internet)
2          load balancer (L4)        TCP to a gateway replica                                         < 1 ms
3          API gateway               TLS end, JWT verify (cached JWKS), rate limit, route, traceparent  0.2-1 ms
4          gateway -> BFF            new connection or pooled keep-alive; mesh mTLS if meshed         0.2-1 ms
5          mobile BFF                start 800 ms deadline, fan out to users and orders                -
6          BFF sidecar -> users      retry policy, mTLS, outlier detection                             400 ms timeout
7          BFF sidecar -> orders     same, in parallel                                                 600 ms timeout
8          BFF                       shape response, degrade if orders failed                           < 1 ms
9          back through gateway      add X-Request-Id, access log with trace id                         -
     User-perceived latency = edge + gateway + BFF + max(users, orders) + all proxy hops

Retries at three layers: the multiplication problem ​

If the gateway retries 3 times, the BFF retries 3 times and the mesh retries 3 times, one user click can become 3 × 3 × 3 = 27 attempts against a struggling service. That is how a small brownout becomes an outage (Cascading Failures).

text
     Layer      Attempts per incoming request    Cumulative attempts on Orders
1    gateway    3                                3
2    BFF        3 each                           9
3    mesh       3 each                           27
     Fix: retry at ONE layer (usually the one closest to the failing call), bound it by a budget

Envoy's guidance: "It is recommended to either configure retry budgets (preferred) or set maximum active retries circuit breaker to an appropriate value to avoid retry storms" (saved text: envoy-retries). Rules: only retry idempotent requests (or requests with an idempotency key, see API Idempotency); per-try timeout shorter than the overall timeout; exponential backoff with jitter; never retry a 429 without honouring Retry-After.

Timeouts and deadlines across hops ​

Each hop's timeout must be shorter than its caller's, or the caller gives up while the callee keeps working (wasted work, and retries pile on). With a 2 s gateway timeout, the BFF should finish in about 1.5 s, and each upstream call in less. Go carries this as a context.Context deadline; Laravel as per-request Guzzle timeout options. Istio's default (no HTTP timeout) means you must set one explicitly.

text
     Hop                Timeout     Rule
1    client app         5 s         user patience, includes retries
2    gateway route      2 s         < client
3    BFF overall        800 ms      < gateway, leaves room for one retry at the edge if idempotent
4    users call         400 ms      < BFF overall
5    orders call        600 ms      < BFF overall
6    mesh perTryTimeout 300 ms      < the call's timeout, so a retry fits

Headers the proxies add and trust ​

HeaderSet byMeaningTrust rule
X-Forwarded-ForEach proxy appends the peer IPClient IP chainTrust only entries added by your own proxies (Envoy xff_num_trusted_hops, use_remote_address)
X-Forwarded-Proto, X-Forwarded-HostEdge proxyOriginal scheme and hostSet by the edge, never taken from the client
Forwarded (RFC 7239)ProxiesStandard form of the aboveSame
X-Request-IdGateway (Envoy generate_request_id)Correlation id for logsGenerate if missing
traceparent, tracestateTracer, gateway, every serviceW3C trace contextPropagate; may start a new trace at the edge
X-User-Id, X-User-Scopes (your names)Gateway after JWT validationVerified identityStrip from client input; accept only from the gateway
x-forwarded-client-certEnvoy with mTLSClient certificate detailsOnly meaningful from your mesh

Go's httputil.ReverseProxy documents why its old Director hook is unsafe: "X-Forwarded-For, X-Forwarded-Host, and X-Forwarded-Proto headers in inbound requests are preserved by default, which can permit IP spoofing", and hop-by-hop removal can delete headers the director added. With Rewrite, "The Forwarded, X-Forwarded, X-Forwarded-Host, and X-Forwarded-Proto headers are removed from the outbound request before Rewrite is called" and ProxyRequest.SetXForwarded sets them correctly (saved text: go-httputil, from go doc).

Config distribution: xDS and control planes ​

Envoy's dynamic configuration APIs "are collectively known as 'xDS' (* discovery service)": LDS (listeners), RDS (routes), CDS (clusters), EDS (endpoints), SDS (secrets) (saved text: envoy-xds). Istio's istiod, Envoy Gateway and many gateways are xDS servers. Consequences:

  • A bad config pushed by the control plane reaches every proxy within seconds: validate before applying (istioctl analyze, CI checks on Gateway API manifests, kong config parse for declarative files).
  • If the control plane is down, proxies keep their last config and keep serving; you cannot change routing until it is back. The control plane is not in the request path.
  • Certificates are rotated by the control plane; an expired CA is a cluster-wide outage, so monitor expiry.

Status codes the edge returns ​

CodeWho usually returns itMeaning at the edgeRetry?
401 UnauthorizedGatewayMissing or invalid token (WWW-Authenticate header)No, refresh token first
403 ForbiddenGateway, mesh authz, serviceAuthenticated but not allowed (scope, policy)No
404 Not FoundGatewayNo route matchedNo
413 Content Too LargeGatewayBody over the configured limitNo
429 Too Many RequestsGateway, BFF, serviceRate limit; Retry-After says whenAfter Retry-After
502 Bad GatewayGateway, meshUpstream refused, reset or returned garbageIf idempotent, with backoff
503 Service UnavailableGateway, mesh, serviceNo healthy upstream, circuit open, overloadIf idempotent, with backoff
504 Gateway TimeoutGateway, meshUpstream did not answer within the timeoutCareful: the work may have happened

Solving the classic problems ​

Problem 1: the chatty mobile client ​

The home screen makes six calls over 4G; p95 is 3 s. Fix: a mobile BFF that makes the six calls concurrently inside the data centre and returns one screen-shaped payload, degrading optional parts.

SolutionHowAdvantageCost
BFF aggregationOne endpoint per screen, concurrent upstream callsOne mobile round tripOne more service, owned by the mobile team
GraphQLClient selects fields; resolvers fan outFlexible per screenQuery cost control, N+1
Read modelPre-joined view, one queryFastest and most availableEventual consistency, event plumbing
Gateway aggregationScripted in the gatewayNo new serviceOverambitious gateway

Code: Go BFF, Laravel BFF.

Problem 2: every service re-implements auth and limits ​

Fix: move token validation, coarse scopes, rate limits, TLS and access logs to the gateway; services keep fine-grained authorization. Code: Go gateway; products: Envoy jwt_authn, Kong plugins.

Problem 3: forged identity headers ​

Fix, in layers: (1) the gateway deletes every identity header from the client request before setting its own (the Go gateway does this in Rewrite); (2) services accept identity headers only from a caller that proves it is the gateway: mTLS identity via the mesh (AuthorizationPolicy with principals), or a shared internal token compared in constant time (Laravel TrustGatewayIdentity); (3) network policy so that only the gateway can reach the services' ports.

Problem 4: releasing a new version safely ​

Fix: weighted routing 90/10 at the gateway (north-south) or the mesh (east-west), watch error rate and latency per version, then shift. Same idea in four products: Traefik weighted, Envoy weighted_clusters, Istio VirtualService weights over DestinationRule subsets, Gateway API backendRefs[].weight. Automate with Argo Rollouts or Flagger if you do this often.

Problem 5: retry storms ​

Fix: pick one layer to retry (often the mesh or the client library closest to the call), limit by budget (Envoy retry budgets, Envoy max_retries circuit breaker), retry only idempotent requests, add jitter, and make every other layer fail fast. See Retries at three layers.

Problem 6: the gateway as single point of failure, and config drift ​

Fix: run at least three gateway replicas across zones behind an L4 load balancer; keep config in Git (declarative Kong, Gateway API manifests, Traefik files) and apply through CI with validation; canary gateway config changes too; keep a break-glass route; alert on gateway error rate and p99 separately from services. Drift: two gateways with hand-edited config disagree on a route; one source of truth plus a diff check in CI fixes it.

Problem 7: the trace stops at the BFF ​

Fix: forward traceparent, tracestate and X-Request-Id on every outbound call (the Go BFF and Laravel BFF do it explicitly), or use OpenTelemetry instrumentation (otelhttp in Go) that does it for you.

Go ​

Module academy/api-gateway-bff-service-mesh under docs/snippets/architecture/api-gateway-bff-service-mesh/go/, standard library only, gofmt and go vet clean. Four commands: a stub upstream, the gateway, the mobile BFF, and a latency benchmark used in the lab.

A minimal gateway with httputil.ReverseProxy ​

Routing with a 90/10 canary, HS256 JWT validation (production: RS256 or ES256 with a JWKS), identity headers set only after validation, a token bucket per user, traceparent continuation, per-route deadlines and 502/504 mapping. Note Rewrite, not the deprecated Director.

go
// Command gateway is a minimal API gateway built on net/http/httputil.ReverseProxy.
// It does edge work only: routing (with a weighted canary), JWT validation,
// identity headers, per-client rate limiting, trace propagation and timeouts.
// It deliberately contains no business logic.
package main

import (
	"context"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"math"
	mrand "math/rand/v2"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"sync"
	"time"
)

// ---------- routing ----------

type backend struct {
	url    *url.URL
	weight int
}

type route struct {
	prefix   string
	backends []backend // more than one: weighted canary
	timeout  time.Duration
	public   bool // no token required
}

func (rt route) pick() *url.URL {
	total := 0
	for _, b := range rt.backends {
		total += b.weight
	}
	n := mrand.IntN(total)
	for _, b := range rt.backends {
		if n < b.weight {
			return b.url
		}
		n -= b.weight
	}
	return rt.backends[0].url
}

func mustURL(s string) *url.URL {
	u, err := url.Parse(s)
	if err != nil {
		log.Fatal(err)
	}
	return u
}

// ---------- auth: HS256 JWT ----------

type claims struct {
	Sub   string `json:"sub"`
	Scope string `json:"scope"`
	Exp   int64  `json:"exp"`
}

var b64 = base64.RawURLEncoding

func sign(secret []byte, c claims) string {
	h := b64.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
	p, _ := json.Marshal(c)
	unsigned := h + "." + b64.EncodeToString(p)
	m := hmac.New(sha256.New, secret)
	m.Write([]byte(unsigned))
	return unsigned + "." + b64.EncodeToString(m.Sum(nil))
}

func verify(secret []byte, token string, now time.Time) (claims, error) {
	var c claims
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return c, errors.New("malformed token")
	}
	hdr, err := b64.DecodeString(parts[0])
	if err != nil || !strings.Contains(string(hdr), `"HS256"`) {
		return c, errors.New("unexpected alg") // never accept "none" or a switched alg
	}
	m := hmac.New(sha256.New, secret)
	m.Write([]byte(parts[0] + "." + parts[1]))
	sig, err := b64.DecodeString(parts[2])
	if err != nil || !hmac.Equal(sig, m.Sum(nil)) {
		return c, errors.New("bad signature")
	}
	payload, err := b64.DecodeString(parts[1])
	if err != nil || json.Unmarshal(payload, &c) != nil {
		return c, errors.New("bad payload")
	}
	if now.Unix() >= c.Exp {
		return c, errors.New("token expired")
	}
	return c, nil
}

// ---------- rate limiting: one token bucket per client ----------

type bucket struct {
	tokens float64
	last   time.Time
}

type limiter struct {
	mu      sync.Mutex
	rate    float64 // tokens per second
	burst   float64
	buckets map[string]*bucket
}

// allow returns whether the request may pass and, if not, how long to wait.
func (l *limiter) allow(key string, now time.Time) (bool, time.Duration) {
	l.mu.Lock()
	defer l.mu.Unlock()
	b, ok := l.buckets[key]
	if !ok {
		b = &bucket{tokens: l.burst, last: now}
		l.buckets[key] = b
	}
	b.tokens = math.Min(l.burst, b.tokens+now.Sub(b.last).Seconds()*l.rate)
	b.last = now
	if b.tokens >= 1 {
		b.tokens--
		return true, 0
	}
	wait := time.Duration((1 - b.tokens) / l.rate * float64(time.Second))
	return false, wait
}

// ---------- trace context (W3C traceparent) ----------

func randHex(n int) string {
	b := make([]byte, n)
	_, _ = rand.Read(b)
	return hex.EncodeToString(b)
}

// nextTraceparent keeps the caller's trace id when valid and starts a new span
// for the gateway hop; otherwise it starts a new trace.
func nextTraceparent(in string) string {
	p := strings.Split(in, "-")
	if len(p) == 4 && p[0] == "00" && len(p[1]) == 32 && len(p[2]) == 16 && len(p[3]) == 2 {
		return "00-" + p[1] + "-" + randHex(8) + "-" + p[3]
	}
	return "00-" + randHex(16) + "-" + randHex(8) + "-01"
}

// ---------- the gateway ----------

type ctxKey int

const (
	keyTarget ctxKey = iota
	keyClaims
)

// identity headers the gateway owns; anything a client sends with these names is dropped
var identityHeaders = []string{"X-User-Id", "X-User-Scopes", "X-Authenticated"}

type gateway struct {
	routes  []route
	secret  []byte
	limiter *limiter
	proxy   *httputil.ReverseProxy
}

func newGateway(routes []route, secret []byte, rate, burst float64) *gateway {
	g := &gateway{
		routes: routes, secret: secret,
		limiter: &limiter{rate: rate, burst: burst, buckets: map[string]*bucket{}},
	}
	g.proxy = &httputil.ReverseProxy{
		// Rewrite (not the deprecated Director): X-Forwarded-* from the client are
		// already removed before this runs, so SetXForwarded cannot be spoofed.
		Rewrite: func(pr *httputil.ProxyRequest) {
			target := pr.In.Context().Value(keyTarget).(*url.URL)
			pr.SetURL(target)
			pr.SetXForwarded()
			for _, h := range identityHeaders {
				pr.Out.Header.Del(h)
			}
			if c, ok := pr.In.Context().Value(keyClaims).(claims); ok {
				pr.Out.Header.Set("X-User-Id", c.Sub)
				pr.Out.Header.Set("X-User-Scopes", c.Scope)
				pr.Out.Header.Set("X-Authenticated", "gateway")
			}
		},
		Transport: &http.Transport{
			MaxIdleConnsPerHost:   100,
			IdleConnTimeout:       90 * time.Second,
			ResponseHeaderTimeout: 3 * time.Second,
		},
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			status := http.StatusBadGateway
			if errors.Is(err, context.DeadlineExceeded) {
				status = http.StatusGatewayTimeout
			}
			log.Printf("upstream error %s %s: %v", r.Method, r.URL.Path, err)
			http.Error(w, http.StatusText(status), status)
		},
		ModifyResponse: func(resp *http.Response) error {
			resp.Header.Del("Server") // do not leak upstream details
			return nil
		},
	}
	return g
}

func (g *gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	start := time.Now()

	// 1. trace context and request id
	tp := nextTraceparent(r.Header.Get("traceparent"))
	r.Header.Set("traceparent", tp)
	if r.Header.Get("X-Request-Id") == "" {
		r.Header.Set("X-Request-Id", randHex(8))
	}
	w.Header().Set("X-Request-Id", r.Header.Get("X-Request-Id"))

	// 2. route match (longest prefix wins because routes are ordered)
	var rt *route
	for i := range g.routes {
		if strings.HasPrefix(r.URL.Path, g.routes[i].prefix) {
			rt = &g.routes[i]
			break
		}
	}
	if rt == nil {
		http.NotFound(w, r)
		return
	}

	// 3. authentication: validate once at the edge
	ctx := r.Context()
	clientKey := r.RemoteAddr
	if !rt.public {
		tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
		if !ok {
			w.Header().Set("WWW-Authenticate", `Bearer realm="api"`)
			http.Error(w, "missing bearer token", http.StatusUnauthorized)
			return
		}
		c, err := verify(g.secret, tok, time.Now())
		if err != nil {
			w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
			http.Error(w, err.Error(), http.StatusUnauthorized)
			return
		}
		ctx = context.WithValue(ctx, keyClaims, c)
		clientKey = "user:" + c.Sub
	}

	// 4. rate limit per client
	if ok, wait := g.limiter.allow(clientKey, time.Now()); !ok {
		w.Header().Set("Retry-After", fmt.Sprint(int(math.Ceil(wait.Seconds()))))
		http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
		return
	}

	// 5. pick a backend (canary weights) and bound the whole upstream call
	ctx = context.WithValue(ctx, keyTarget, rt.pick())
	ctx, cancel := context.WithTimeout(ctx, rt.timeout)
	defer cancel()

	g.proxy.ServeHTTP(w, r.WithContext(ctx))
	log.Printf("%s %s trace=%s took=%s", r.Method, r.URL.Path, tp[3:35], time.Since(start).Round(time.Microsecond))
}

func main() {
	addr := flag.String("addr", ":8080", "listen address")
	secret := flag.String("secret", "dev-only-secret", "HS256 key (use a JWKS and RS256/ES256 in production)")
	mint := flag.String("mint", "", "print a token for this user id and exit")
	rate := flag.Float64("rate", 5, "rate limit: requests per second per client")
	burst := flag.Float64("burst", 10, "rate limit: bucket size per client")
	flag.Parse()

	if *mint != "" {
		fmt.Println(sign([]byte(*secret), claims{Sub: *mint, Scope: "orders:read", Exp: time.Now().Add(time.Hour).Unix()}))
		return
	}

	routes := []route{
		{prefix: "/bff/mobile/", backends: []backend{{mustURL("http://127.0.0.1:8090"), 1}}, timeout: 2 * time.Second},
		{prefix: "/orders", backends: []backend{
			{mustURL("http://127.0.0.1:9001"), 90}, // stable
			{mustURL("http://127.0.0.1:9002"), 10}, // canary
		}, timeout: 1 * time.Second},
		{prefix: "/users/", backends: []backend{{mustURL("http://127.0.0.1:9003"), 1}}, timeout: 1 * time.Second},
		{prefix: "/healthz", backends: []backend{{mustURL("http://127.0.0.1:9003"), 1}}, timeout: 500 * time.Millisecond, public: true},
	}

	srv := &http.Server{
		Addr:              *addr,
		Handler:           newGateway(routes, []byte(*secret), *rate, *burst),
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       120 * time.Second,
	}
	log.Printf("gateway listening on %s", *addr)
	log.Fatal(srv.ListenAndServe())
}

A BFF with concurrency and timeouts ​

Two upstream calls in parallel, each with its own timeout inside an 800 ms overall deadline; profile is essential (fail), orders are optional (degrade); trace and identity headers forwarded.

go
// Command bff is a Backend-for-Frontend for the mobile app. One call from the
// phone becomes two concurrent calls to the users and orders services, each
// with its own timeout inside an overall deadline. If orders fails, the BFF
// degrades (returns the profile without orders) instead of failing the screen.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"sync"
	"time"
)

type bff struct {
	client    *http.Client
	usersURL  string
	ordersURL string
}

// MobileHome is the screen-shaped response: only what the phone renders.
type MobileHome struct {
	UserName     string   `json:"user_name"`
	Tier         string   `json:"tier"`
	RecentOrders []Order  `json:"recent_orders"`
	Degraded     []string `json:"degraded,omitempty"`
}

type Order struct {
	ID     int    `json:"id"`
	Status string `json:"status"`
	Total  string `json:"total"`
}

// get calls one upstream with its own timeout and forwards the headers that
// must survive the hop: identity set by the gateway and the trace context.
func (b *bff) get(ctx context.Context, in *http.Request, url string, timeout time.Duration, out any) error {
	ctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	for _, h := range []string{"traceparent", "tracestate", "X-Request-Id", "X-User-Id", "X-User-Scopes"} {
		if v := in.Header.Get(h); v != "" {
			req.Header.Set(h, v)
		}
	}
	resp, err := b.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		_, _ = io.Copy(io.Discard, resp.Body)
		return fmt.Errorf("%s: status %d", url, resp.StatusCode)
	}
	return json.NewDecoder(resp.Body).Decode(out)
}

func (b *bff) home(w http.ResponseWriter, r *http.Request) {
	userID := r.Header.Get("X-User-Id") // trusted only because the network lets nothing but the gateway reach the BFF
	if userID == "" {
		http.Error(w, "no identity from gateway", http.StatusUnauthorized)
		return
	}
	// Overall budget for the screen; each call gets a slice of it.
	ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
	defer cancel()

	var (
		wg     sync.WaitGroup
		user   struct{ Data struct{ Name, Tier string } }
		orders struct {
			Data []struct {
				ID         int
				Status     string
				TotalCents int `json:"total_cents"`
			}
		}
		userErr  error
		orderErr error
	)
	wg.Add(2)
	go func() {
		defer wg.Done()
		userErr = b.get(ctx, r, b.usersURL+"/users/"+userID, 400*time.Millisecond, &user)
	}()
	go func() {
		defer wg.Done()
		orderErr = b.get(ctx, r, b.ordersURL+"/orders?user="+userID+"&limit=5", 600*time.Millisecond, &orders)
	}()
	wg.Wait()

	// The profile is essential: without it there is no screen.
	if userErr != nil {
		status := http.StatusBadGateway
		if errors.Is(userErr, context.DeadlineExceeded) {
			status = http.StatusGatewayTimeout
		}
		http.Error(w, "profile unavailable", status)
		return
	}
	out := MobileHome{UserName: user.Data.Name, Tier: user.Data.Tier, RecentOrders: []Order{}}
	// Orders are optional: degrade, tell the client, keep the screen working.
	if orderErr != nil {
		log.Printf("orders degraded: %v", orderErr)
		out.Degraded = append(out.Degraded, "recent_orders")
	} else {
		for _, o := range orders.Data {
			out.RecentOrders = append(out.RecentOrders, Order{
				ID: o.ID, Status: o.Status,
				Total: fmt.Sprintf("%.2f EUR", float64(o.TotalCents)/100), // formatting for this screen only
			})
		}
	}
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Cache-Control", "private, max-age=10")
	_ = json.NewEncoder(w).Encode(out)
}

func main() {
	addr := flag.String("addr", ":8090", "listen address")
	users := flag.String("users", "http://127.0.0.1:9003", "users service base URL")
	orders := flag.String("orders", "http://127.0.0.1:9001", "orders service base URL")
	flag.Parse()

	b := &bff{
		client:    &http.Client{Transport: &http.Transport{MaxIdleConnsPerHost: 50, IdleConnTimeout: 90 * time.Second}},
		usersURL:  *users,
		ordersURL: *orders,
	}
	mux := http.NewServeMux()
	mux.HandleFunc("GET /bff/mobile/home", b.home)

	srv := &http.Server{Addr: *addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	log.Printf("mobile BFF listening on %s", *addr)
	log.Fatal(srv.ListenAndServe())
}

Stub upstream and hop benchmark ​

go
// Command upstream is a stub service for the lab: it answers like a users or
// orders service, with configurable latency, failure rate and version label.
package main

import (
	"encoding/json"
	"flag"
	"log"
	"math/rand/v2"
	"net/http"
	"time"
)

func main() {
	addr := flag.String("addr", ":9001", "listen address")
	name := flag.String("name", "orders", "service name: users or orders")
	version := flag.String("version", "v1", "version label returned in X-Version")
	delay := flag.Duration("delay", 5*time.Millisecond, "artificial processing time")
	failRate := flag.Float64("fail", 0, "fraction of requests answered with 503")
	flag.Parse()

	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})
	handler := func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(*delay)
		w.Header().Set("X-Version", *version)
		// Echo what the proxy chain told us, so the lab can see propagation.
		w.Header().Set("X-Seen-Traceparent", r.Header.Get("traceparent"))
		w.Header().Set("X-Seen-User", r.Header.Get("X-User-Id"))
		if rand.Float64() < *failRate {
			http.Error(w, `{"error":"temporarily unavailable"}`, http.StatusServiceUnavailable)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		var body any
		switch *name {
		case "users":
			body = map[string]any{"id": r.PathValue("id"), "name": "Sara", "tier": "gold"}
		default:
			body = []map[string]any{
				{"id": 1001, "status": "shipped", "total_cents": 4599},
				{"id": 1002, "status": "placed", "total_cents": 1250},
			}
		}
		_ = json.NewEncoder(w).Encode(map[string]any{"service": *name, "version": *version, "data": body})
	}
	mux.HandleFunc("GET /users/{id}", handler)
	mux.HandleFunc("GET /orders", handler)

	srv := &http.Server{Addr: *addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	log.Printf("%s %s listening on %s (delay=%s fail=%.2f)", *name, *version, *addr, *delay, *failRate)
	log.Fatal(srv.ListenAndServe())
}
go
// Command hopbench measures what one extra proxy hop costs: it sends the same
// sequential requests directly to a service and through the gateway, then
// prints p50/p90/p99. It also counts which version answered (canary split).
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"slices"
	"time"
)

func run(client *http.Client, url, token string, n int) ([]time.Duration, map[string]int) {
	lat := make([]time.Duration, 0, n)
	versions := map[string]int{}
	for range n {
		req, _ := http.NewRequest(http.MethodGet, url, nil)
		if token != "" {
			req.Header.Set("Authorization", "Bearer "+token)
		}
		start := time.Now()
		resp, err := client.Do(req)
		if err != nil {
			log.Fatal(err)
		}
		_, _ = io.Copy(io.Discard, resp.Body)
		resp.Body.Close()
		lat = append(lat, time.Since(start))
		versions[resp.Header.Get("X-Version")+" "+resp.Status]++
	}
	slices.Sort(lat)
	return lat, versions
}

func pct(s []time.Duration, p float64) time.Duration {
	return s[int(float64(len(s)-1)*p)].Round(10 * time.Microsecond)
}

func main() {
	direct := flag.String("direct", "http://127.0.0.1:9001/orders", "service URL without the gateway")
	via := flag.String("via", "http://127.0.0.1:8080/orders", "same resource through the gateway")
	token := flag.String("token", "", "bearer token for the gateway (go run ./gateway -mint u1)")
	n := flag.Int("n", 2000, "requests per target")
	flag.Parse()

	client := &http.Client{Timeout: 5 * time.Second}
	for _, t := range []struct{ name, url, tok string }{{"direct", *direct, ""}, {"via-gateway", *via, *token}} {
		lat, versions := run(client, t.url, t.tok, *n)
		fmt.Printf("%-12s p50=%-8v p90=%-8v p99=%-8v versions=%v\n", t.name, pct(lat, .50), pct(lat, .90), pct(lat, .99), versions)
	}
}

The Go angle. httputil.ReverseProxy handles hop-by-hop headers, streaming, HTTP/2 and WebSocket upgrades; Rewrite plus SetURL and SetXForwarded is the safe configuration; the Transport (MaxIdleConnsPerHost, ResponseHeaderTimeout) decides connection reuse and timeouts to upstreams. For a BFF, context.WithTimeout gives each call a budget and errgroup (Worker Pools & errgroup) is the idiomatic alternative to the WaitGroup used here when every call is essential. For tracing, go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp wraps handlers and transports so propagation is automatic. Protocol translation: grpc-gateway.

Laravel ​

Laravel 13 is a good BFF: Sanctum for the phone's tokens, the HTTP client's pool for concurrent upstream calls, API resources for response shaping, named rate limiters, and Octane to keep the app in memory. Sources: HTTP Client, API Resources, Routing: rate limiting, Sanctum, Passport, Octane.

Routes. Sanctum authenticates; the named limiter throttles.

php
<?php

// routes/api.php of the Laravel mobile BFF (install with: php artisan install:api).
// Sanctum authenticates the phone; the named limiter protects the BFF and the services behind it.

use App\Http\Controllers\MobileHomeController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum', 'throttle:mobile-bff'])->group(function () {
    Route::get('/mobile/home', MobileHomeController::class);
});

The BFF controller. The docs: "The pool method cannot be chained with other HTTP client methods such as the withHeaders or middleware methods", so each pooled request is configured on its own; and "If a pooled request fails at the connection level (for example, a timeout or DNS failure), the corresponding entry in the $responses array will be an Illuminate\Http\Client\ConnectionException instance instead of a Response instance" (saved text: laravel-http-client). The default client timeout is 30 seconds, far too long for a BFF, so every call sets its own.

php
<?php

namespace App\Http\Controllers;

use App\Http\Resources\MobileHomeResource;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Backend-for-Frontend endpoint for the mobile home screen.
 * One request from the phone, two concurrent upstream calls, one screen-shaped response.
 */
final class MobileHomeController
{
    public function __invoke(Request $request): JsonResponse
    {
        $userId = (string) $request->user()->getAuthIdentifier();

        // Headers that must survive the hop: trace context and the verified identity.
        $headers = array_filter([
            'traceparent' => $request->header('traceparent'),
            'tracestate' => $request->header('tracestate'),
            'X-Request-Id' => $request->header('X-Request-Id'),
            'X-User-Id' => $userId,
            'X-Internal-Token' => config('services.internal.token'),
        ]);

        $usersUrl = config('services.users.url');
        $ordersUrl = config('services.orders.url');

        // pool() cannot be chained with withHeaders()/timeout(), so each request is configured on its own.
        // Guzzle options give explicit sub-second budgets per call.
        $responses = Http::pool(fn (Pool $pool) => [
            $pool->as('user')
                ->withHeaders($headers)
                ->acceptJson()
                ->withOptions(['connect_timeout' => 0.2, 'timeout' => 0.4])
                ->get("{$usersUrl}/users/{$userId}"),
            $pool->as('orders')
                ->withHeaders($headers)
                ->acceptJson()
                ->withOptions(['connect_timeout' => 0.2, 'timeout' => 0.6])
                ->get("{$ordersUrl}/orders", ['user' => $userId, 'limit' => 5]),
        ], concurrency: 2);

        // A pooled entry is a ConnectionException (Throwable) when the call never got an answer.
        $user = $responses['user'];
        if (! $user instanceof Response || $user->failed()) {
            Log::warning('mobile-home: profile unavailable', ['user' => $userId]);

            return response()->json(['message' => 'Profile unavailable'], 502);
        }

        $orders = $responses['orders'];
        $degraded = [];
        $orderRows = [];
        if ($orders instanceof Response && $orders->successful()) {
            $orderRows = $orders->json('data', []);
        } else {
            $degraded[] = 'recent_orders';   // optional data: degrade, do not fail the screen
            Log::info('mobile-home: orders degraded', ['user' => $userId]);
        }

        return (new MobileHomeResource([
            'user' => $user->json('data'),
            'orders' => $orderRows,
            'degraded' => $degraded,
        ]))->response()->header('Cache-Control', 'private, max-age=10');
    }
}

The API resource shapes the aggregate for one screen; $wrap = null returns a flat object.

php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * Shapes the aggregated upstream data for one screen of one client.
 * Presentation decisions (formatting, field names) live here, not in the domain services.
 */
final class MobileHomeResource extends JsonResource
{
    /** The phone expects a flat object, not {"data": {...}}. */
    public static $wrap = null;

    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'user_name' => $this->resource['user']['name'],
            'tier' => $this->resource['user']['tier'],
            'recent_orders' => array_map(fn (array $order) => [
                'id' => $order['id'],
                'status' => $order['status'],
                'total' => number_format($order['total_cents'] / 100, 2).' EUR',
            ], $this->resource['orders']),
            'degraded' => $this->when($this->resource['degraded'] !== [], $this->resource['degraded']),
        ];
    }
}

Rate limiter. "Rate limiters may be defined within the boot method of your application's App\Providers\AppServiceProvider class" and attached with the throttle middleware; with Redis as the cache, throttleWithRedis() maps it to ThrottleRequestsWithRedis (saved text: laravel-routing).

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Per-user limit for the BFF; anonymous callers are keyed by IP.
        // With several BFF replicas, use a shared cache store (Redis) so the count is global.
        RateLimiter::for('mobile-bff', function (Request $request) {
            return Limit::perMinute(120)
                ->by($request->user()?->id ?: $request->ip())
                ->response(fn (Request $request, array $headers) => response()->json(
                    ['message' => 'Too many requests'],
                    429,
                    $headers,   // includes Retry-After and X-RateLimit-* headers
                ));
        });
    }
}

A downstream Laravel service behind the gateway must not trust identity headers blindly:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\GenericUser;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * For a downstream Laravel service that sits behind the gateway or BFF.
 * It accepts the identity headers ONLY from a caller that proves it is the gateway.
 * Without such a check, anyone who reaches the service directly can send "X-User-Id: 1".
 * In a service mesh, replace the shared token with the mTLS peer identity
 * (for example an Istio AuthorizationPolicy that allows only the gateway's service account).
 */
final class TrustGatewayIdentity
{
    public function handle(Request $request, Closure $next): Response
    {
        $expected = (string) config('services.internal.token');
        $given = (string) $request->header('X-Internal-Token', '');

        if ($expected === '' || ! hash_equals($expected, $given)) {
            abort(401, 'Caller is not the gateway');
        }

        $userId = $request->header('X-User-Id');
        if ($userId === null || $userId === '') {
            abort(401, 'No identity from gateway');
        }

        $request->setUserResolver(fn () => new GenericUser([
            'id' => $userId,
            'scopes' => explode(' ', (string) $request->header('X-User-Scopes', '')),
        ]));

        return $next($request);
    }
}
php
<?php

// config/services.php (excerpt): upstream locations and the internal caller token.

return [
    'users' => [
        'url' => env('USERS_SERVICE_URL', 'http://users:9001'),
    ],
    'orders' => [
        'url' => env('ORDERS_SERVICE_URL', 'http://orders:9001'),
    ],
    'internal' => [
        // Shared secret between gateway/BFF and services; rotate it, or use mTLS instead.
        'token' => env('INTERNAL_CALLER_TOKEN'),
    ],
];

The Laravel angle. PHP-FPM handles one request per worker process, so a BFF waiting on upstreams holds a worker; Http::pool makes the waits concurrent within that request. Octane "boots your application once, keeps it in memory, and then feeds it requests" (saved text: laravel-octane), removing bootstrap cost per request; Octane::concurrently (Swoole only) runs closures in task workers. Never call Laravel from inside the gateway path for auth checks on every request; validate JWTs at the gateway or use Sanctum in the BFF.

Configuration excerpts ​

Traefik (lab): 90/10 weighted service, retry middleware, rate limit. File provider, because the weighted type "can be defined currently with the File provider or IngressRoute" (saved text: traefik-weighted).

yml
# Traefik dynamic configuration (file provider).
# The `weighted` service type is only available with the File provider or IngressRoute,
# not with Docker labels, which is why the lab uses this file.
http:
  routers:
    orders:
      rule: PathPrefix(`/orders`)
      entryPoints: [web]
      service: orders-canary
      middlewares: [orders-retry]
    mobile-bff-go:
      rule: PathPrefix(`/bff/mobile`)
      entryPoints: [web]
      service: bff-go
    mobile-bff-laravel:
      rule: PathPrefix(`/api/mobile`)
      entryPoints: [web]
      service: bff-laravel
      middlewares: [edge-ratelimit]

  middlewares:
    orders-retry:
      retry:
        attempts: 3            # retries only when the upstream does not answer (network error)
        initialInterval: 100ms # exponential backoff starts here
    edge-ratelimit:
      rateLimit:
        average: 50            # requests per second per source IP
        burst: 100

  services:
    orders-canary:
      weighted:
        services:
          - name: orders-v1
            weight: 9          # 90 %
          - name: orders-v2
            weight: 1          # 10 % canary
    orders-v1:
      loadBalancer:
        servers: [{ url: "http://orders-v1:9001" }]
        healthCheck: { path: /healthz, interval: 5s, timeout: 1s }
    orders-v2:
      loadBalancer:
        servers: [{ url: "http://orders-v2:9001" }]
        healthCheck: { path: /healthz, interval: 5s, timeout: 1s }
    bff-go:
      loadBalancer:
        servers: [{ url: "http://bff-go:8090" }]
    bff-laravel:
      loadBalancer:
        servers: [{ url: "http://bff-laravel:8000" }]

Envoy as edge gateway: jwt_authn with claim_to_headers, weighted_clusters, retry_policy with per_try_timeout, cluster circuit_breakers.

yaml
# Envoy as an edge gateway (excerpt): JWT validation, identity header from a claim,
# 90/10 weighted canary, retries with a per-try timeout, and circuit breakers.
static_resources:
  listeners:
    - name: edge
      address: { socket_address: { address: 0.0.0.0, port_value: 8080 } }
      filter_chains:
        - filters:
            - name: envoy.filters.network.http_connection_manager
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
                stat_prefix: edge
                use_remote_address: true         # trust the TCP peer, not a client-sent X-Forwarded-For
                generate_request_id: true        # x-request-id for every request
                route_config:
                  virtual_hosts:
                    - name: api
                      domains: ["*"]
                      routes:
                        - match: { prefix: "/orders" }
                          route:
                            timeout: 1s
                            retry_policy:
                              retry_on: "connect-failure,reset,retriable-status-codes"
                              retriable_status_codes: [503]
                              num_retries: 2
                              per_try_timeout: 0.4s
                            weighted_clusters:
                              clusters:
                                - { name: orders_v1, weight: 90 }
                                - { name: orders_v2, weight: 10 }
                http_filters:
                  - name: envoy.filters.http.jwt_authn
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
                      providers:
                        idp:
                          issuer: https://id.example.com/
                          audiences: [api.example.com]
                          remote_jwks:
                            http_uri: { uri: https://id.example.com/.well-known/jwks.json, cluster: idp, timeout: 2s }
                            cache_duration: 300s
                          claim_to_headers:
                            - { header_name: x-user-id, claim_name: sub }
                      rules:
                        - match: { prefix: "/" }
                          requires: { provider_name: idp }
                  - name: envoy.filters.http.router
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
  clusters:
    - name: orders_v1
      type: STRICT_DNS
      connect_timeout: 0.25s
      circuit_breakers:
        thresholds:
          - { max_connections: 1000, max_pending_requests: 200, max_requests: 1000, max_retries: 3 }
      load_assignment:
        cluster_name: orders_v1
        endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: orders-v1, port_value: 9001 } } } }] }]
    - name: orders_v2
      type: STRICT_DNS
      connect_timeout: 0.25s
      load_assignment:
        cluster_name: orders_v2
        endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: orders-v2, port_value: 9001 } } } }] }]
    # cluster "idp" (the JWKS host, with TLS) omitted for brevity

Istio: VirtualService (weights, retries, timeout), DestinationRule (subsets, connection pool, outlier detection), PeerAuthentication (STRICT mTLS), AuthorizationPolicy (only the BFF's service account).

yaml
# Istio (sidecar mode, or ambient mode with a waypoint for L7):
# 90/10 canary, retries with a per-try timeout, an overall timeout,
# connection-pool limits and outlier detection (ejection of failing pods).
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: orders
spec:
  hosts: [orders]
  http:
    - route:
        - destination: { host: orders, subset: v1 }
          weight: 90
        - destination: { host: orders, subset: v2 }
          weight: 10
      timeout: 2s                      # the Envoy HTTP timeout is disabled in Istio by default
      retries:
        attempts: 3
        perTryTimeout: 500ms
        retryOn: connect-failure,refused-stream,503
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: orders
spec:
  host: orders
  trafficPolicy:
    connectionPool:
      tcp: { maxConnections: 100 }
      http: { http2MaxRequests: 1000, maxRequestsPerConnection: 10 }
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
  subsets:
    - name: v1
      labels: { version: v1 }
    - name: v2
      labels: { version: v2 }
---
# Require mTLS for every workload in the namespace (PERMISSIVE accepts plaintext too).
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
  name: default
  namespace: shop
spec:
  mtls:
    mode: STRICT
---
# Only the BFF's service account may call orders; identity comes from the mTLS certificate.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: orders-allow-bff
  namespace: shop
spec:
  selector:
    matchLabels: { app: orders }
  action: ALLOW
  rules:
    - from:
        - source:
            principals: ["cluster.local/ns/shop/sa/mobile-bff"]
      to:
        - operation: { methods: ["GET"], paths: ["/orders*"] }

Kubernetes Gateway API: the platform team's Gateway, the app team's HTTPRoute with weights.

yaml
# Kubernetes Gateway API: the platform team owns the Gateway, app teams own HTTPRoutes.
# The same HTTPRoute kind is used for north-south (parentRef: Gateway)
# and, in meshes that implement GAMMA, east-west (parentRef: Service).
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: public
  namespace: infra
spec:
  gatewayClassName: example-class      # Envoy Gateway, Istio, Traefik, NGINX Gateway Fabric, Kong...
  listeners:
    - name: https
      protocol: HTTPS
      port: 443
      hostname: api.example.com
      tls:
        mode: Terminate
        certificateRefs: [{ name: api-example-com-tls }]
      allowedRoutes:
        namespaces: { from: All }
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: orders
  namespace: shop
spec:
  parentRefs: [{ name: public, namespace: infra }]
  hostnames: [api.example.com]
  rules:
    - matches: [{ path: { type: PathPrefix, value: /orders } }]
      backendRefs:
        - { name: orders-v1, port: 9001, weight: 90 }
        - { name: orders-v2, port: 9001, weight: 10 }
    - matches: [{ path: { type: PathPrefix, value: /bff/mobile } }]
      backendRefs:
        - { name: mobile-bff, port: 8090 }

Kong (DB-less): services, routes, jwt and rate-limiting plugins. Kong's docs on policy: local: "Counters are stored in-memory on the node" and it "diverges when scaling the number of nodes" unless a consistent-hashing load balancer sits in front (saved text: kong-rate-limiting).

yaml
# Kong Gateway in DB-less mode (declarative config, excerpt):
# a service per upstream, routes, JWT auth and rate limiting as plugins.
_format_version: "3.0"
services:
  - name: orders
    url: http://orders-v1:9001
    connect_timeout: 250
    read_timeout: 1000
    retries: 2
    routes:
      - name: orders
        paths: [/orders]
        strip_path: false
    plugins:
      - name: jwt
      - name: rate-limiting
        config:
          minute: 300
          policy: local          # local | cluster | redis: local counts per Kong node only,
                                 # so N nodes allow up to N x 300; use redis for one shared count
  - name: mobile-bff
    url: http://bff-go:8090
    routes:
      - name: mobile
        paths: [/bff/mobile]
        strip_path: false

Choosing ​

Gateway vs mesh vs library: where should resilience and security live?

ConcernIn code (Go, Laravel library)In the gatewayIn the mesh
Knows business meaning (idempotency, which field is optional)YesNoNo
Same behaviour across languagesNo (one library per language)Only at the edgeYes
Change without redeploying servicesNoYesYes
Sees end-user identityYesYesOnly if JWT is configured in the mesh
Sees service identityOnly with mTLS in codeFirst hop onlyYes, every hop
Cost per callLowestOne hop per requestTwo proxies (sidecar) or ztunnel hops per call
DebuggabilityStack traces in your codeGateway logsProxy logs and config dumps
Best forRetries with idempotency keys, fallbacks, degrade logicEdge auth, quotas, TLS, routing, canary at the edgemTLS, uniform timeouts, outlier ejection, internal canaries, golden metrics

Decision table.

SituationRecommendationExtra techniqueReason
Monolith with web and mobile clientsReverse proxy (NGINX, Traefik) for TLS; no gateway productVersioned API in the appNothing to route to yet
5-15 services, one clientOne gateway (Kong, Traefik, Envoy Gateway)Libraries for retries and tracingEdge concerns once, no mesh tax
Several client types with different needsGateway plus one BFF per experienceClient team owns its BFFAutonomy, fewer mobile round trips
Many clients, fast-changing screensGraphQL BFF or federated GraphQLPersisted queries, cost limitsField selection per client
Heavy cross-service lists and searchCQRS read model behind the BFFOutbox and projectorComposition does not scale for joins
Dozens of services, many languages, compliance needs mTLSService mesh (Istio ambient for L4 first, or Linkerd)Add L7 (waypoints) where neededUniform identity and telemetry
Frequent canaries on internal servicesMesh traffic splitting or Gateway API weightsFlagger or Argo RolloutsSafe progressive delivery
Public partner API with plansGateway with API keys, quotas, developer portalSeparate partner BFFStable contract, per-partner limits
Kubernetes, new setupGateway API resourcesPick an implementation (Envoy Gateway, Istio, Traefik, Kong)Ingress is frozen

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Example (everyday). A Laravel monolith serving web pages and a mobile API from one codebase behind NGINX or Traefik. The "gateway" is the reverse proxy: TLS termination, limit_req or rateLimit, gzip, static files. The "BFF" is a set of controllers under routes/api.php returning API resources shaped for the app (/api/mobile/home), next to Blade or Inertia pages for the web. No mesh: there are no service-to-service calls. Simplest correct setup: rate limiting with Laravel's RateLimiter, Sanctum tokens for the app, a request id middleware.

Modular monolith and multiple databases ​

Example. Modules Catalog, Orders, Billing inside one deployable with clear interfaces (Modular Monolith). The mobile "BFF" is a presentation module that calls the other modules' public interfaces in process: it composes, formats and degrades exactly like a remote BFF, but a failure is an exception, not a timeout. Keep it shaped that way (an interface per module, DTOs, no reaching into other modules' tables) so that extracting it later only changes the transport. A gateway appears when the first module is extracted: route /billing/* to the new service, everything else to the monolith (strangler fig).

Microservices ​

Example (production). An e-commerce platform with 25 services. Edge: CDN and WAF, then an Envoy-based gateway (three replicas, two zones) that validates JWTs against the identity provider's JWKS, sets identity headers, enforces per-plan quotas with a global rate limit service, and routes to a web BFF (Node or Laravel, owned by the web team), a mobile BFF (Go, owned by the mobile team) and a partner API (versioned). Inside: Istio ambient for mTLS everywhere, waypoints only for orders and payments, which need L7 retries, outlier detection and canaries. Flow for "place order" from the phone: gateway (auth, 2 s timeout) → mobile BFF (POST /bff/mobile/orders with Idempotency-Key) → orders service (creates order, writes outbox) → event → payments. What survives the boundaries: identity (header from the gateway, workload identity from mTLS), trace context, idempotency keys. What does not: transactions (sagas, see Saga Pattern), and any assumption that the gateway will retry safely.

Distributed data: replicas, caches, multi-region ​

Example. The mobile BFF reads profile data from a cache and orders from a read replica; after "place order", the user's list may not show it yet (replica lag). Fixes at this layer: the BFF returns the created order in the write response and the app inserts it locally; or the BFF routes that user's next read to the primary for a few seconds (Replication & Failover). Caching at the edge: only for public, cacheable GETs; per-user BFF responses use Cache-Control: private. Multi-region: GeoDNS sends users to the nearest region's gateway; each region has its own gateway, BFFs and mesh; meshes can be multi-cluster (Istio sidecar mode supports it; ambient listed as single-cluster on the page we read); rate limits become per region unless you accept cross-region coordination cost. Read models are rebuilt per region from replicated events.

Scaling path: 1x, 10x, 100x ​

LoadShapeWhat changes in gateway, BFF and mesh
1x (one app, hundreds of users)Reverse proxy plus monolithTLS and basic limits at the proxy; API resources per client in the monolith
10x (first services extracted)One gateway, monolith plus 3-10 servicesGateway routes and authenticates; libraries for retries and tracing; no mesh
100x (dozens of services, several client teams)Edge layer, gateway replicas, BFF per experience, meshGlobal rate limiting (Redis or a rate limit service), read models for heavy lists, mesh for mTLS and uniform telemetry, retries at one layer only
Beyond (multi-region, many teams)Per-region stacks, per-domain gateways, federated GraphQL or many BFFsGateway config as code per team (Gateway API routes per namespace), cell-based isolation, budgets per hop (SLOs)

Lab ​

Goal. Run a gateway, a BFF and upstreams; see authentication, header-spoofing protection, trace propagation, degradation, timeouts, rate limiting, a 90/10 canary and the cost of the extra hop. Part A runs natively with Go (no Docker). Part B is the same with Traefik in Docker Compose.

Part A setup (five terminals, or background them):

bash
cd docs/snippets/architecture/api-gateway-bff-service-mesh/go
go run ./upstream -addr :9001 -name orders -version v1 -delay 2ms   # stable
go run ./upstream -addr :9002 -name orders -version v2 -delay 2ms   # canary
go run ./upstream -addr :9003 -name users  -version v1 -delay 2ms
go run ./bff                                                         # :8090
go run ./gateway -rate 1000 -burst 1000                               # :8080, limits relaxed for the benchmark
TOKEN=$(go run ./gateway -mint u1)
  1. No token, no entry.
    bash
    curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/orders     # 401
  2. Header spoofing is ignored; trace id is kept. Send a forged identity and a trace:
    bash
    curl -si -H "Authorization: Bearer $TOKEN" -H 'X-User-Id: admin' \
      -H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' \
      localhost:8080/orders | grep -i 'x-seen\|x-version'
    # X-Seen-Traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-f25a82de12b91300-01   (same trace, new parent span)
    # X-Seen-User: u1                                                                 (not "admin")
    # X-Version: v1
  3. The BFF aggregates.
    bash
    curl -s -H "Authorization: Bearer $TOKEN" localhost:8080/bff/mobile/home
    # {"user_name":"Sara","tier":"gold","recent_orders":[{"id":1001,"status":"shipped","total":"45.99 EUR"},{"id":1002,"status":"placed","total":"12.50 EUR"}]}
  4. Canary split and the cost of one hop.
    bash
    go run ./hopbench -token "$TOKEN" -n 2000
    # direct       p50=2.65ms   p90=2.76ms   p99=2.85ms   versions=map[v1 200 OK:2000]
    # via-gateway  p50=2.79ms   p90=3.03ms   p99=3.23ms   versions=map[v1 200 OK:1807 v2 200 OK:193]
    Measured on loopback (Go 1.27, Apple silicon): the gateway hop added about 0.14 ms at p50 and 0.38 ms at p99, and the canary received 193 of 2000 requests (9.65%). On a real network add one RTT and, with TLS, a handshake per new connection; keep-alive pooling matters more than proxy speed.
  5. Degradation. Restart orders v1 failing every request: go run ./upstream -addr :9001 -name orders -version v1 -fail 1, then call the BFF again:
    bash
    # {"user_name":"Sara","tier":"gold","recent_orders":[],"degraded":["recent_orders"]}
  6. Timeouts. Restart orders v1 with -delay 1500ms. Through the gateway (1 s route timeout) requests that land on v1 return 504 after about 1.00 s; the BFF returns the degraded payload in about 0.60 s (its orders call budget).
  7. Rate limiting. Restart the gateway with defaults (5 requests per second, burst 10) and fire 15 requests quickly:
    bash
    for i in $(seq 1 15); do curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $TOKEN" localhost:8080/users/u1; done | sort | uniq -c
    #   10 200
    #    5 429        (with Retry-After: 1)

Steps 1 to 7 were run for this chapter; the outputs above are the real ones.

Part B: Traefik in Docker Compose (not run for this chapter: no Docker daemon was available, so treat the expected output as illustrative).

yaml
# Lab: Traefik in front of the Go services and the Laravel BFF.
# Run from docs/snippets/architecture/api-gateway-bff-service-mesh/deploy/traefik
#   docker compose up -d
# Ports: 80 = through Traefik, 9001 = orders-v1 directly (for the latency comparison), 8081 = dashboard.
x-go: &go
  image: golang:1.24
  working_dir: /src
  volumes: ["../../go:/src:ro", "gocache:/root/.cache/go-build"]

services:
  traefik:
    image: traefik:v3.4
    command:
      - --entryPoints.web.address=:80
      - --providers.file.filename=/etc/traefik/dynamic.yml
      - --providers.file.watch=true
      - --api.insecure=true
      - --api.dashboard=true
      - --entryPoints.traefik.address=:8081
      - --accessLog=true
    ports: ["80:80", "8081:8081"]
    volumes: ["./dynamic.yml:/etc/traefik/dynamic.yml:ro"]

  orders-v1:
    <<: *go
    command: go run ./upstream -addr :9001 -name orders -version v1 -delay 2ms
    ports: ["9001:9001"]
  orders-v2:
    <<: *go
    command: go run ./upstream -addr :9001 -name orders -version v2 -delay 2ms
  users:
    <<: *go
    command: go run ./upstream -addr :9001 -name users -version v1 -delay 2ms
  bff-go:
    <<: *go
    command: go run ./bff -addr :8090 -users http://users:9001 -orders http://orders-v1:9001

  # Your Laravel 13 app with the php/ files of this chapter copied in.
  # Optional: started only with `docker compose --profile laravel up -d`.
  bff-laravel:
    profiles: ["laravel"]
    build: ./laravel-bff   # your Laravel app (Dockerfile with PHP 8.4 + FrankenPHP); adjust the path
    command: php artisan octane:start --server=frankenphp --host=0.0.0.0 --port=8000
    environment:
      USERS_SERVICE_URL: http://users:9001
      ORDERS_SERVICE_URL: http://orders-v1:9001

volumes:
  gocache: {}
  1. docker compose up -d in deploy/traefik; open the dashboard on :8081.
  2. Canary: for i in $(seq 1 1000); do curl -s -o /dev/null -D - localhost/orders | grep -i x-version; done | sort | uniq -c should show roughly 900 v1 and 100 v2.
  3. Retries at the proxy: docker compose stop orders-v2; without the retry middleware about 10% of requests fail with 502 until the health check removes v2; with orders-retry the failed attempts are retried with backoff and most succeed. Note that Traefik stops retrying as soon as the server answers, whatever the status.
  4. Latency with and without the hop: run hopbench from the host with -direct http://localhost:9001/orders -via http://localhost/orders (no token: Traefik does not check one here). Expect a fraction of a millisecond extra at p50, more at p99 because of Docker networking.
  5. Laravel BFF behind Traefik: put your app in deploy/traefik/laravel-bff, run docker compose --profile laravel up -d, then curl -H "Authorization: Bearer <sanctum token>" localhost/api/mobile/home; stop orders-v1 and confirm degraded appears instead of an error.

Common misconceptions ​

BeliefReality
"A service mesh replaces the API gateway"Different traffic (east-west vs north-south), different identity (workload vs user); most large systems use both
"Gateway API is an API gateway"It is a Kubernetes resource model that many gateways and meshes implement
"The gateway authenticated, so services can trust X-User-Id"Only from a caller proven to be the gateway (mTLS identity, internal token, network policy)
"Put the aggregation in the gateway, it is already there"That is the overambitious gateway; aggregation belongs in a BFF owned by the client team
"One BFF per platform is mandatory"One BFF per experience; iOS and Android may share one if the experience is the same
"Duplication between BFFs must be removed immediately"Tolerate it; extract on the third copy, as a library or a domain service
"Parallel fan-out makes aggregation cheap"It removes the sum, not the tail; more upstreams means a worse p99
"The mesh traces requests automatically"Proxies emit spans; the app must propagate traceparent between inbound and outbound calls
"mTLS means authorized"mTLS proves the workload's identity; authorization policies and app checks decide access
"Retries everywhere make the system more reliable"Retries at several layers multiply load (3 x 3 x 3 = 27) and cause retry storms
"Our gateway rate limiter protects us from DDoS"Floods need a network-scale DDoS service; rate limiting is for fairness
"Istio sets sensible HTTP timeouts for me"The Envoy HTTP timeout is disabled in Istio by default; set one
"Sidecars are free because Envoy is fast"About 0.2 vCPU and 60 MB per sidecar at 1000 rps (Istio 1.24), times every pod

Cheat sheet ​

TopicWhat to remember
Gateway jobTLS, auth, coarse authz, rate limits, routing, canary, observability: policies, not business logic
BFF jobOne experience; aggregate, shape, format, degrade; owned by the client team
Mesh jobmTLS identity, uniform retries and timeouts, outlier ejection, traffic splitting, telemetry for east-west calls
Library jobAnything that needs business meaning: idempotency, fallbacks, which data is optional
Overambitious gatewayBusiness logic in middleware; Radar "Hold" (2017-2018)
TopologiesSingle, per-domain, per-client (BFF), layered
Fan-outLatency = max of parallel calls; P(slow) = 1 - 0.99^N; degrade optional calls
Composition vs read modelLive and simple vs fast, available, eventually consistent
Sidecar vs ambientEnvoy per pod vs ztunnel per node + optional waypoint; L7 needs a proxy either way
Ingress vs Gateway APIIngress frozen; Gateway API role-oriented, weights in the spec, GAMMA for mesh
Identity headersStrip client copies, set after validation, accept only from the gateway
Token exchangeRFC 8693, narrower token per hop
Trace propagationW3C traceparent through every hop, including your code
RetriesOne layer, budgeted, idempotent only, jitter, honour Retry-After
TimeoutsEach hop shorter than its caller; set them explicitly in Istio
Gateway SPOF3+ replicas across zones, config in Git, validated in CI

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Name five responsibilities that belong in the API gateway and two that do not. Must-know ​

Answer

Answer: Belong: TLS termination, token validation, coarse authorization by scope, rate limiting and quotas, routing and canary weights, access logs and trace start. Do not belong: business rules (prices, discounts, workflows) and screen-specific aggregation (that is a BFF).

2 — What is the difference between a gateway and a BFF in terms of ownership? Must-know ​

Answer

Answer: The gateway is shared infrastructure owned by a platform team and configured declaratively. A BFF is application code owned by the team that owns the client experience, released together with that client.

3 — Your mobile BFF calls 10 services in parallel, each slow 1% of the time. How often is the BFF slow, and what do you do? Important ​

Answer

Answer: About 1 - 0.99^10, roughly 9.6% of requests. Give each call a timeout inside an overall deadline, degrade optional parts, consider hedging idempotent reads, and move heavy joins to a read model.

4 — When would you choose a CQRS read model over API composition? Important ​

Answer

Answer: When the query needs filtering, sorting or joining across services over many rows, or must stay available when an upstream is down, and the screen tolerates eventual consistency.

5 — What are the data plane and the control plane of a mesh, and does the control plane carry requests? Must-know ​

Answer

Answer: The data plane is the proxies that carry and control traffic (Envoy sidecars, ztunnel, waypoints, linkerd2-proxy). The control plane (istiod, Linkerd control plane) configures them and issues certificates. It does not carry requests; if it is down, proxies keep their last configuration.

6 — In Istio ambient mode, which component gives you L7 retries and header-based routing? Good to know ​

Answer

Answer: A waypoint proxy (an Envoy deployment). ztunnel only handles L3/L4: mTLS, L4 authorization and telemetry.

7 — A service receives X-User-Id: 1 from an attacker pod inside the cluster. Which three controls stop this? Important ​

Answer

Answer: The gateway strips client identity headers before setting its own; the service accepts identity only from a caller proven to be the gateway (mTLS principal or internal token); network policy restricts who can reach the service.

8 — Gateway, BFF and mesh each retry three times. What happens when Orders slows down, and how do you fix it? Must-know ​

Answer

Answer: Each user request can become 27 attempts on Orders, turning a slowdown into an outage. Retry at one layer, bounded by a budget, only for idempotent requests, with jitter; make other layers fail fast.

9 — Why does a mesh not give complete traces automatically? Important ​

Answer

Answer: A proxy cannot correlate an outbound call with the inbound request that caused it inside the application process. The application must copy traceparent (and related headers) from inbound to outbound requests.

10 — Kubernetes Ingress or Gateway API for a new cluster, and why? Important ​

Answer

Answer: Gateway API: Ingress is frozen, while Gateway API is role-oriented, has weights and header matching in the spec, supports gRPC routes and can describe mesh traffic through GAMMA.

11 — When do you not need a service mesh? Must-know ​

Answer

Answer: Few services, one or two languages with good libraries, no requirement for mTLS on every internal hop, no platform team to operate it, simple rolling deploys. TLS plus libraries and OpenTelemetry are cheaper.

12 — In the Laravel BFF, why is each pooled request configured separately, and what does a failed connection look like? Good to know ​

Answer

Answer: Http::pool cannot be chained with withHeaders or other client methods, so headers and timeouts are set per request. A connection-level failure appears as a ConnectionException (a Throwable) in the responses array instead of a Response.

Glossary ​

TermMeaning
API gatewayReverse proxy at the system edge applying cross-cutting policies and routing
Backend-for-Frontend (BFF)Backend dedicated to one user experience, owned by its client team
Service meshProxies on every service-to-service path plus a control plane that configures them
Data planeThe proxies carrying traffic (Envoy, ztunnel, waypoint, linkerd2-proxy)
Control planeComponent configuring proxies and issuing certificates (istiod)
SidecarProxy container deployed in the same pod as the application
Ambient modeIstio data plane without sidecars: ztunnel per node, optional waypoint
ztunnelIstio's per-node L4 proxy (Rust) for mTLS, L4 authz and telemetry
WaypointOptional Envoy proxy in ambient mode providing L7 features
HBONEHTTP CONNECT-based tunnel used between ztunnels
xDSEnvoy's discovery APIs (LDS, RDS, CDS, EDS, SDS) used by control planes
North-southTraffic entering or leaving the system
East-westTraffic between internal services
Egress gatewayControlled exit point for outbound traffic
IngressFrozen Kubernetes resource for HTTP routing into a cluster
Gateway APIRole-oriented Kubernetes routing resources (GatewayClass, Gateway, HTTPRoute, GRPCRoute)
GAMMAGateway API initiative for service mesh (east-west) routing
Overambitious gatewayAnti-pattern: business logic and orchestration in the gateway
API compositionQuery implemented by calling owning services and joining in memory
CQRS read modelPre-joined read-only view updated from events
Fan-outNumber of downstream calls per incoming request
Graceful degradationReturning a partial response when optional dependencies fail
Canary releaseSending a small share of traffic to a new version
Traffic splittingWeighted routing between versions or subsets
SubsetIstio DestinationRule group of instances (for example by version label)
Outlier detectionEjecting instances that return errors from the load-balancing pool
Circuit breaking (Envoy)Limits on connections, pending requests, requests and retries per cluster
Retry budgetCap on the share of requests that may be retries
HedgingSending a duplicate request after a per-try timeout and taking the first answer
mTLSTLS where both sides present certificates
SPIFFEStandard for workload identities encoded in certificates
PeerAuthenticationIstio resource setting mTLS mode (STRICT, PERMISSIVE)
AuthorizationPolicyIstio resource allowing or denying calls by identity and operation
JWTSigned token carrying claims; validated at the gateway
JWKSPublished set of public keys used to verify JWTs
Identity headersHeaders set by the gateway after validation (X-User-Id)
Header spoofingForging trusted headers to impersonate a user or proxy
Token exchangeRFC 8693 flow to obtain a new token for a downstream audience
TLS terminationEnding the client's TLS session at a proxy
Rate limitingRestricting request rate per key (token bucket and others)
WAFWeb application firewall filtering malicious HTTP patterns
CDNEdge cache network close to users
DDoS protectionNetwork-scale absorption of flood attacks
traceparentW3C header carrying trace id, parent span id and flags
X-Forwarded-ForHeader listing the client IP chain through proxies
X-Request-IdCorrelation id for one request across logs
Protocol translationConverting REST/JSON to gRPC and back (grpc-gateway)
GraphQLQuery language and runtime letting clients select fields
ReverseProxyGo net/http/httputil type implementing an HTTP reverse proxy
RewriteSafe ReverseProxy hook replacing the deprecated Director
Http::poolLaravel HTTP client method for concurrent requests
API resourceLaravel JsonResource class shaping JSON responses
SanctumLaravel package for SPA, mobile and API token authentication
PassportLaravel OAuth2 server package
OctaneLaravel package serving the app from long-lived workers
Config driftDivergence between intended and running proxy configuration
Single point of failure (SPOF)Component whose failure stops the whole system

References ​

Primary sources read and saved for this chapter (under scratchpad/sources/api-gateway-bff-service-mesh/):

Built by Morteza Negahi