AlgoViz

Envoy

medium 28 min

Envoy is an open source network proxy that runs at the edge or beside every service.

Video lesson · Chapter 1 of 5

One request chooses a cluster

0:00 / 3:53

Envoy in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Envoy is a proxy written in C++. It accepts connections, runs them through a chain of filters, picks one server out of a group, and passes the request on. At its core it works on bytes and connections (layers 3 and 4); an HTTP layer on top understands requests, headers and gRPC.

It is built to be told what to do by another program. Addresses, routes, listeners and certificates can all arrive through streaming APIs called xDS, so a change needs no file edit and no restart.

It is a building block. Service meshes such as Istio and gateways such as Envoy Gateway are control planes that write Envoy configuration for you.

Why it exists

A company with many small services has the same network problems in every one of them: find the other service, balance, time out, retry, encrypt, measure. Solving these in a library means one library per programming language and a new release of every service for each upgrade.

Envoy moves that work into a separate process next to the service. The program calls its local proxy in plain HTTP, and the proxy does the hard part the same way for Java, Go, Python and PHP.

A short history

  1. 2015

    Work starts at Lyft in the summer. By late autumn it carries all of Lyft's edge traffic, as its author later described.

  2. September 2016

    Version 1.0.0: Lyft publishes Envoy as open source.

  3. September 2017

    Envoy joins the Cloud Native Computing Foundation as an incubating project.

  4. November 2018

    It becomes a graduated CNCF project.

  5. October 2026

    Version 1.40.0. Releases come once a quarter and are maintained for about a year.

Words to know

Downstream and upstream
Downstream is who called Envoy; upstream is whom Envoy calls.
Listener
An address and port that Envoy accepts connections on.
Filter
A small step in a chain that can read, change, answer or stop traffic.
Cluster
A named group of servers that can do the same job.
Endpoint
One server of a cluster.
Sidecar
A proxy that runs next to one copy of one service.
Data plane and control plane
The proxies that carry traffic, and the program that tells them how.
xDS
The family of discovery APIs through which configuration arrives.

How it works

Step through the idea, or press Play.

Step 1 of 3

Accept. A listener takes the connection and picks a filter chain

Understand it

Start here

The personal interpreter

Imagine a market where the traders speak many languages. You could learn all of them. Or somebody who already knows them could walk beside you all day.

Never travel alone
HELLO???Two people, two languages

The traveller stays simple. The interpreter is the same for every traveller.

The idea

A proxy beside every service

Two sidecars and a control plane

Pod A holds the shop service and a sidecar Envoy, pod B a sidecar Envoy and the stock service. Shop makes a local HTTP call to its sidecar, the sidecars talk over mutual TLS, and sidecar B passes plain HTTP to stock. A control plane sends hosts, routes, keys and rules to both sidecars.
Orange is configuration. No request ever passes through the control plane.
  • Any language

    The program makes a local call. Network rules live in the proxy.

  • Dynamic

    Endpoints, routes, listeners and secrets change over a stream, without a restart.

  • Resilient

    Timeouts, retries, circuit limits, health checks and ejection in one place.

  • HTTP/2 and gRPC

    Both sides, in any mix with HTTP/1.1. HTTP/3 is supported too.

  • Observable

    Counters and timings for every cluster, access logs and traces.

  • Extensible

    Filters in C++, Lua, WebAssembly, dynamic modules or an outside service.

The ideas have their own pages: service discovery, L4 and L7 balancers, circuit breaker, retries and microservice communication. This page is about how the product does them.

Placement

Where it stands

Three places for the same program

PlaceCarriesTypical control plane
Edge or gatewayTraffic from outside: TLS, routes, login checks, limitsEnvoy Gateway, or files
SidecarAll traffic of one copy of one service, in and outIstio, Consul
Shared proxy for one groupHTTP rules for many services, as in Istio's ambient mode (waypoints)Istio

Do you need it, and where?

Linkerd is a mesh that does not use Envoy but its own small proxy. That is a fair comparison point: less general, less to learn.

Inside

One main thread, many workers

Inside one process

A control plane sends configuration to the main thread of one Envoy process. Clients connect to two worker threads, each with its own event loop and its own connection pools, and both workers reach both endpoints of the upstream cluster.
A connection stays with the worker that accepted it, with all the streams on it.

The main thread loads configuration, gathers statistics and serves the admin page. Workers carry traffic, rarely share state, and take no locks for it. The number is set with --concurrency; by default, on Linux, it is the smallest of the hardware threads, the CPU affinity and the CPU limit of the container, so a two-core pod on a 64-core machine starts two workers. Without a CPU limit it would start 64.

Connections add up per worker

connections≥workers×endpoints8×50=400\text{connections} \ge \text{workers} \times \text{endpoints} \qquad 8 \times 50 = 400
Assumed: 8 workers, one HTTP/2 connection from each worker to each of 50 endpoints. With HTTP/1.1 it is one connection per request in flight instead.

Objects

Listener, filter, route, cluster, endpoint

How the objects point at each other

Network filters handle connections. HTTP filters handle requests, and the router is the last of them.
YAML
static_resources:  listeners:    - name: web      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: web                route_config:                  name: main                  virtual_hosts:                    - name: all                      domains: ["*"]                      routes:                        - match: { prefix: "/stock/" }                          route:                            cluster: stock                            timeout: 2s                            retry_policy:                              retry_on: connect-failure,refused-stream,unavailable                              num_retries: 1                http_filters:                  - name: envoy.filters.http.router                    typed_config:                      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router  clusters:    - name: stock      type: STRICT_DNS      connect_timeout: 1s      lb_policy: LEAST_REQUEST      load_assignment:        cluster_name: stock        endpoints:          - lb_endpoints:              - endpoint:                  address: { socket_address: { address: stock, port_value: 9000 } }admin:  address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
A complete small file. Check any file with envoy --mode validate -c envoy.yaml.

Ways to find the endpoints of a cluster

TypeWhere addresses come fromUse it when
STATICWritten in the configurationTests, fixed machines
STRICT_DNSEvery address of a DNS answer is an endpointHeadless services, small setups
LOGICAL_DNSOnly the first address, used when a new connection is neededA large web service behind DNS
EDSA control plane streams them, with weights and zonesThe preferred way in a mesh

Request

The life of one request

Shop calls stock through two sidecars

  1. 1

    Accept

    A worker accepts. Listener filters may look at the first bytes, for example for the server name in the TLS hello, to choose a filter chain.

  2. 2

    Decode

    The HTTP connection manager turns bytes into requests, for HTTP/1.1, HTTP/2 or HTTP/3 alike.

  3. 3

    Filter

    Each HTTP filter sees the request in order: login check, rate limit, rewriting. Any of them may answer and stop the chain.

  4. 4

    Route and balance

    The router finds the cluster, the balancer an endpoint, the pool a connection.

  5. 5

    Answer

    The response passes the filters in reverse order. Statistics and the access log are written.

Control

xDS: configuration as a stream

The main discovery services

APIDeliversChanges how often
LDSListenersRarely
RDSRoute tablesWith each rollout
CDSClustersWhen services come and go
EDSEndpoints of a clusterAll the time
SDSCertificates and keysAt every rotation
ADSAll of them on one streamUsed to control the order

Envoy answers each update with an ACK, or with a NACK that carries the error. After a NACK it goes on with what it had. The incremental form sends only differences. Separate streams are only eventually consistent with each other, so the protocol describes a safe order.

Make before break

A route that names an unknown cluster answers 503. With ADS one server can keep this order.

Discovery says one thing, health checks another

DiscoveryHealth check passesHealth check fails
Host is listedSend trafficDo not send
Host is missingSend trafficDo not send, then delete it
With active health checks on, a host is only dropped when both agree. That is why a broken registry does not empty the pools.

Balancing

Choosing an endpoint

PolicyRuleUse it when
Round robin (default)In turn, by weightHosts and requests are alike
Least requestTwo random hosts, the one with fewer active requestsRequest times differ. A good default
Ring hashConsistent hashing on a ringCache servers; fewest keys move
MaglevConsistent hashing with a fixed table of 65,537 placesAs above, with faster lookups; about twice as many keys move
RandomAny hostBetter than round robin when there are no health checks

Around the policy: priorities (use level 1 only as level 0 gets weak), zone-aware routing (prefer the same zone) and subsets (only hosts with a label, such as a canary version). gRPC needs this kind of balancer, because a connection balancer would pin all calls of a long connection to one host.

Failure

Health checks, outliers and panic

  1. 1

    Active checks

    Envoy asks each endpoint on a timer, over HTTP, gRPC or TCP.

  2. 2

    Outlier detection

    Envoy watches real answers. By default five 5xx in a row eject a host for 30 seconds, then 60, then 90, up to 300.

  3. 3

    A limit on ejection

    max_ejection_percent is 10 by default, so a bad answer from a shared database cannot eject everybody. With 3 hosts, one host is already 33 percent, so nothing is ejected until you raise it.

  4. 4

    Panic

    If fewer than 50 percent of hosts are healthy, Envoy sends to all of them again, healthy or not.

How long is a host out?

tn=min⁡(30 s×n,;300 s)t1=30,;t2=60,;t10=300t_n = \min(30\,\text{s} \times n,; 300\,\text{s}) \qquad t_1 = 30,; t_2 = 60,; t_{10} = 300
n is how many times in a row it was ejected. A healthy period brings n down again.

The state of one endpoint

Protection

Timeouts, retries and circuit limits

Defaults worth knowing

SettingDefaultNote
Route timeout15 sFor the whole answer. Set 0 for streams
Stream idle timeout5 minNo bytes in either direction
Connect timeout5 sPer cluster; too long inside one network
RetriesNoneMust be configured; then 1 by default, with jittered back-off from 25 ms to 250 ms
Connections, pending, requests1,024 eachPer cluster, shared by the workers
Retries in flight3Per cluster; a retry budget replaces it

Envoy's circuit breaking limits how much may be in flight. When the limit is reached it refuses at once, with 503 and the header x-envoy-overloaded. That protects a slow service from a queue. The classic open, half-open and closed states are closer to its outlier detection; see circuit breaker.

Why one layer retries

(1+r)h=(1+2)3=27budget: 0.20×200=40 retries(1 + r)^{h} = (1 + 2)^{3} = 27 \qquad \text{budget: } 0.20 \times 200 = 40 \text{ retries}
Two retries at each of three hops can make 27 calls at the bottom. A 20 percent budget allows 40 retries when 200 requests are in flight.
YAML
# part of a clustercircuit_breakers:  thresholds:    - max_connections: 2000      max_pending_requests: 200      max_requests: 2000      retry_budget:        budget_percent: { value: 20 }        min_retry_concurrency: 3outlier_detection:  consecutive_5xx: 5  interval: 10s  base_ejection_time: 30s  max_ejection_percent: 34
Twenty percent and three are also the defaults once a retry budget is set.

Rules

Rate limits, identity and the admin port

  • Local rate limit

    A token bucket in this process; refusals are 429. Ten proxies allow ten times the rate, unless the bucket is shared out over the cluster.

  • Global rate limit

    Envoy asks a separate rate limit service before passing on. One exact number, one more hop.

  • Mutual TLS

    Both sides show certificates. SDS delivers and rotates them without a restart.

  • JWT and external checks

    Filters verify tokens or ask your own service. failure_mode_allow decides what happens when it is down.

Operations

Running it

TaskHowWatch
See what is wrongResponse flags in the access log: UH no healthy host, UO overflow, UT upstream timeout, NR no routeShare of requests with a flag
Check configuration/config_dump, /clusters and /stats on the admin portupdate_rejected counters
Change configurationxDS; for files, a validated rolloutOld listeners drain their connections
Upgrade the binaryRolling restart, or hot restart on one machine: the new process takes over the listening socketsExisting connections are not moved, they drain
Stay supportedA release every quarter, fixes for about 12 monthsSecurity releases in between

What it costs. A sidecar per copy means memory, some CPU, and two proxy passes on every call. Measure both in your own system before and after; the number depends on request size, filters and TLS. Every copy also holds configuration, so limit what each one is sent: a sidecar that knows 2,000 clusters it never calls wastes memory 2,000 times over.

Decide

Envoy or something else

ProductStrong atChoose it instead when
NGINXFiles, cache, a small configurationOne front door, rare changes
HAProxyBalancing TCP and HTTP with fine controlYou want a balancer, not a platform
TraefikFinds containers by itself, certificates includedA small team on Docker or Kubernetes
KongAPI products: keys, consumers, pluginsYou publish APIs to customers
IstioA mesh on top of EnvoyYou want mesh features without writing xDS
A library such as gRPCNo extra process; gRPC itself can read xDSOne language, hard latency limits

Strengths

  • Same rules for every language
  • Everything can change while it runs
  • Deep statistics for every call
  • HTTP/2 and gRPC on both sides

Costs

  • Verbose configuration, hard to write by hand
  • A control plane to run and protect
  • One more process and hop per call
  • No response cache for general use out of the box

Summary

The whole topic in one minute.

Envoy is a proxy made of filters. A listener accepts, filters inspect, the router picks a cluster, and a balancer picks an endpoint. A main thread handles configuration while worker threads, each with its own event loop, carry the traffic.

Its strength is that everything can change at run time through xDS, and that every service gets the same timeouts, retries, limits, encryption and numbers. Its price is a second process per service and a control plane to run. Know the defaults, keep retries in one layer with a budget, and keep the admin port private.

  • Listener, filters, route, cluster, endpoint. The router is the last HTTP filter.
  • Main thread for configuration, workers for traffic; a connection stays with one worker.
  • xDS streams configuration. Add clusters first, move routes, remove last.
  • Outlier detection ejects, circuit limits refuse, panic below 50 percent sends to all.
  • Retries in one layer, with a budget. Route timeout is 15 seconds. Admin on localhost.

Sources