AlgoViz

HashiCorp Consul

medium 32 min

Consul keeps a live list of services and their health across many machines, answers where a service is over DNS and HTTP, stores small settings and locks, and can decide which service may call which through a service mesh.

Video lesson · Chapter 1 of 5

Another payments till joins the market

0:00 / 4:25

Consul in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

When programs start and stop all day, their addresses change all day. Consul is a system that keeps the current list, called the catalog: which services exist, where each copy runs, and whether it is healthy. Callers ask by name. The general idea is explained in service discovery; this page is about the product.

Consul is one program that runs in two roles. A few servers hold all the data and agree on it. A client agent on each machine registers the services there, checks their health, and answers questions from local programs. On top of the catalog Consul offers a key/value store, locks, and a service mesh: proxies that encrypt calls between services and allow or deny them by name.

Why it exists

A settings file with addresses is wrong as soon as a machine is replaced. A load balancer in front of every service costs money and adds a hop. Consul makes the list automatic: a service registers when it starts, and a copy that fails its check leaves the answers.

Kubernetes has its own discovery inside one cluster. Consul is chosen when the estate is wider: virtual machines, bare machines, several clusters, several datacenters, all needing one set of names and one set of rules about who may call whom.

A short history

  1. 2014, April

    Version 0.1.0 is released on 17 April, according to the project's changelog.

  2. 2017, October

    Version 1.0.0 is released on 16 October.

  3. 2018, June

    Version 1.2.0 brings a beta of Connect, the service mesh: automatic TLS and permission by service identity.

  4. 2022, November

    Version 1.14.0 turns cluster peering and the mesh on by default. Consul on Kubernetes stops needing a client agent on every node and uses Consul Dataplane.

  5. 2023, August

    HashiCorp announces on 10 August that future releases move from the Mozilla Public License 2.0 to the Business Source License 1.1.

  6. 2025

    IBM completes the purchase of HashiCorp on 27 February. The hosted HCP Consul Dedicated service ends on 12 November.

  7. 2026

    Version 2.0 starts IBM's numbering, with a new major version in April and a feature update in October. 2.1.0 follows on 21 October.

Words to know

Agent
The Consul program running on a machine, as a server or as a client.
Catalog
The list of nodes, services, addresses and check results, kept by the servers.
Datacenter
One Consul cluster: a set of servers with their own catalog, and the agents that belong to it.
Gossip
Agents telling a few other agents what they know, so that news of members and failures spreads without a centre.
Raft
The agreement method the servers use. A change counts once a majority has stored it.
Blocking query
An HTTP request that waits until the answer changes or a time limit passes.
Intention
A rule that allows or denies calls from one named service to another.
Session
A contract tied to a node or a time limit. Locks belong to a session and are freed when it ends.

How it works

Step through the idea, or press Play.

Step 1 of 3

Register. The local agent adds the service and its checks

Understand it

Start here

The harbour board

Picture a harbour where ships come and go. Nobody can remember who lies at which berth, so the harbour keeps a board, and each ship's mate looks after their own line on it.

Who is in, and who may board?
FIGOAKBEE123In harbourFIG1OAK2BEE3

Knowing where a ship is and being allowed aboard are two separate questions. Consul can answer both.

The idea

Four jobs in one program

What Consul does

  • Discovery and health

    A live catalog, checks run beside the service, answers over DNS and HTTP.

  • Service mesh

    Envoy proxies beside each service: mutual TLS, intentions, traffic rules, metrics.

  • Settings and locks

    A small key/value store with watches, sessions and leader election.

  • Many datacenters

    Names and failover across places, through WAN federation or cluster peering.

Consul gives you

  • One catalog for VMs, containers and bare machines
  • Checks close to the program
  • Plain DNS, so old programs need no change
  • A choice between fast and strictly current reads
  • Permission by service identity

Consul does not

  • Start or place your programs (an orchestrator does)
  • Store application data: a value may be at most 512 KB
  • Copy its key/value store to other datacenters by itself
  • Turn on access control for you: ACLs are off by default
  • Replace timeouts and retries in the caller

Architecture

Servers, clients and two kinds of talk

One datacenter

Inside one Consul datacenter, machine A runs a web program and a client agent, machine B runs a payments program and a client agent that checks it. Both client agents talk to the leader of three Consul servers, and the leader replicates to two followers.
Three servers hold the catalog. Client agents hold only the services of their own machine. Gossip runs between all agents, servers included; it is not drawn.

Who does what

PartJobIf it stops
Leader (one of the servers)Orders every write and copies it to the followersThe other servers elect a new leader; writes pause meanwhile
FollowersStore the log, forward requests, answer stale readsNothing visible while a majority remains
Majority of serversCommits writesNo registration, no change. Stale reads can still be answered
Client agentRegisters and checks local services, answers local DNS and HTTP, gossipsThat machine's services are seen as failed
Envoy proxy (mesh only)Encrypts, checks intentions, balancesThat copy loses its mesh traffic
Run three or five servers. More servers survive more failures and make every write slower.

Two protocols split the work. Raft gives the servers one agreed log; the method is described in etcd. Gossip spreads membership and failures among all agents, see failure detection. Because clients are not part of the Raft group, thousands of them do not slow down agreement.

How many servers may fail

quorum=⌊N2⌋+1N=3: 2, 1 may failN=5: 3, 2 may failquorum = \left\lfloor \tfrac{N}{2} \right\rfloor + 1 \qquad N = 3:\ 2,\ \text{1 may fail} \qquad N = 5:\ 3,\ \text{2 may fail}
Four servers need three votes and still survive only one failure, so even numbers buy nothing.

Registering

A service, its check and its exit

hcl
service {  name = "payments"  id   = "payments-1"  port = 8080  tags = ["v2"]  check {    http     = "http://localhost:8080/health"    interval = "10s"    timeout  = "2s"    deregister_critical_service_after = "30m"  }}
A definition for the local agent. Put it in the configuration directory and run consul reload, or use consul services register.

Check types

CheckHow it worksGood for
HTTP, gRPC, TCP, UDPThe agent calls the program. The default timeout is 10 sMost services
ScriptThe agent runs a command. The default timeout is 30 sSpecial tests; off unless you allow scripts
TTLThe program must report in before the time runs outJobs without a port
DockerRuns a command inside a containerContainers on a VM
AliasCopies the state of another service or nodeA sidecar that follows its service
A check starts as critical unless you set another status, so a copy that has not yet proved itself receives no traffic.

From a failed check to a clean list

DNS leaves out critical copies. Warning copies stay in the answer unless only_passing is on. Removal happens only if you set a time.

Finding

DNS, HTTP and waiting for change

A caller finds a service

Consul is not in the path of the call itself. If it stops later, open connections carry on.

Three ways to ask

WayExampleUse it when
DNSpayments.service.consul, agent port 8600Any program that can resolve a name; nothing to change
HTTP API/v1/health/service/payments with passingYou need ports, tags, or every copy
Blocking queryThe same call with index and waitA proxy or client must learn of changes quickly
An ordinary DNS lookup returns addresses only. Ask for SRV records when the port varies.

A blocking query hangs until the answer changes. The wait defaults to 5 minutes and is limited to 10. Consul adds up to one sixteenth of the wait at random, so that watchers do not all wake together. If the returned index goes backwards, start again from 0. A return does not prove that something changed.

Consistency

Three read modes

ModeWho answersWhat you can get
defaultThe leader, trusting its leaseAlmost always current; rarely stale around an election
consistentThe leader, after asking a majority whether it still leadsAlways current, slower, more traffic
staleAny serverFast, scales with servers, works without a leader, may be behind
HTTP uses default unless you choose. DNS allows stale answers by default, so names keep resolving in a long outage.

Which mode?

For discovery a slightly old list is fine, because the caller still needs a timeout and a second try. The theory is in consistency models.

Small data

Key/value, sessions and locks

The key/value store holds settings and flags. A value may be at most 512 KB, and one transaction may hold up to 64 operations. Each datacenter has its own store. Think of it as a notice board, with a database elsewhere.

Leader election with a session

The lock delay gives an old leader that is slow rather than dead time to notice.

Mesh

Who may call whom

The service mesh

Machine A holds the web program and its Envoy proxy; machine B holds the payments program and its Envoy proxy. The web program calls its own proxy, the proxies talk to each other over mutual TLS, and the second proxy passes the call to payments. Consul servers send certificates and rules to both proxies.
The programs speak plain HTTP on their own machine. The proxies add identity, encryption and the rule check.
hcl
Kind = "service-intentions"Name = "payments"Sources = [  {    Name   = "web"    Action = "allow"  },  {    Name   = "*"    Action = "deny"  }]
Only web may open connections to payments. Apply it with consul config write. The more exact name wins over the star.

Rules are kept in the proxies, so they keep working when Consul cannot be reached. For HTTP services a rule can also look at the path, the method and headers. Changing a rule for plain TCP affects new connections only; those already open are not cut. Envoy itself is covered in Envoy, and other meshes in Istio and Linkerd.

Wider

Several datacenters

WAN federationCluster peering
ShapeSeveral datacenters act as one, with a primaryIndependent clusters that trust each other pair by pair
SharedAccess rules and configuration come from the primaryOnly the services you export
SetupServers join a WAN gossip poolOne side makes a token, the other presents it
CouplingHigherLower; each side can be run by another team
The catalog is never copied to the other side by default. A question about a remote datacenter is sent there and fails if it is down.

A prepared query stores a lookup with a failover list: if no healthy copy exists here, ask the next datacenter. Callers use it through an ordinary DNS name. This is failover of names; moving the data is your job, see achieving high availability.

Operate

Ports, limits and the switches to turn on

Numbers to know

WhatValue
Servers3 or 5 for production
Client agents per datacenterAt most 5,000 recommended
Server RPC and RaftPort 8300
Gossip, local and widePorts 8301 and 8302
HTTP and DNSPorts 8500 and 8600
gRPC with TLSPort 8503
Server memory2 to 4 times the working set
Raft multiplier5 by default; lower means faster failure detection and more false alarms

Will the lookups fit?

q=callers×lookups per caller per secondservers answering2000×55=2000 per second eachq = \frac{\text{callers} \times \text{lookups per caller per second}}{\text{servers answering}} \qquad \frac{2000 \times 5}{5} = 2000 \text{ per second each}
Assumptions: 2,000 callers, five new connections per second each, peak already included, five servers with stale reads, no caching. A TTL of 5 s lowers it to at most 400 per second in total per looked-up name. The decision: use stale reads and a short TTL before you buy larger servers.

Before production

  1. 1

    Access control

    ACLs are off by default. Turn them on with a default of deny, and give each service its own token.

  2. 2

    Encryption

    TLS between agents is off by default. Set up the built-in authority, set a gossip key and rotate it.

  3. 3

    Fast disks

    Servers are limited by disk for writes and by CPU for reads.

  4. 4

    Snapshots

    Run consul snapshot save on a schedule, keep it elsewhere and practise the restore.

  5. 5

    Watch the leader

    Alert on the time to commit, on last contact, and on leadership changes.

Failure

What breaks, and what keeps working

FailureWhat you seePrepare
One of three serversNothing, after a possible electionReplace it soon: the next loss stops writes
Two of three serversNo registrations or lock changes; stale DNS goes onFive servers across zones; a rehearsed recovery
Client agent on one machineIts services leave the listRun the agent under a supervisor
A wrong health checkEvery copy becomes critical and the name is emptyShallow checks; see failure detection
Network splitThe side with the majority writes; the other is staleCallers with timeouts and retries

Roblox published a detailed report of a 73-hour outage in October 2021. Consul was the shared base for discovery, health checks, locks and Vault. A newly enabled streaming feature caused contention under very high read and write load, and the storage library under Raft behaved badly at the same time. Their lesson applies to every registry: know what depends on it, and make sure monitoring does not.

Decide

When to choose it, and when not

Choose Consul

  • Services on VMs, bare machines and containers together
  • Several datacenters or clouds with one naming scheme
  • Programs that can only use DNS
  • Permission between services by identity
  • You already run Nomad or Vault and have a platform team

Choose something simpler

  • One Kubernetes cluster: its Services are enough
  • One cloud with managed discovery
  • A handful of services behind load balancers
  • You only need a lock or a small store
  • You must ship it inside a competing product

Neighbours

OptionSameDifferentChoose it when
Kubernetes ServicesNames for healthy copiesInside one cluster, nothing more to runAll in one cluster
AWS Cloud MapRegistry with DNS and APIManaged, AWS only, no locks, no meshAll on AWS
etcdRaft, watches, leasesA store only: no DNS, no checksYou build the rest
ZooKeeperCoordination, locksOrdered tree of nodes, no DNSSoftware that already needs it
IstioMesh with mTLS and rulesCentred on Kubernetes, uses its registryRich traffic rules in clusters

Summary

The whole topic in one minute.

Consul servers agree on the catalog with Raft. Client agents register services, run checks next to the program, and use gossip to notice dead machines. Callers use DNS or HTTP, and long-lived watchers use blocking queries. A mesh of Envoy proxies can add encryption and permission by service name.

Choose it for many services on mixed platforms with people to run it. Inside one Kubernetes cluster or one cloud, the built-in discovery is usually enough. Check the licence: it is source-available under BUSL 1.1 and no longer open source.

  • Three or five servers agree with Raft; clients register, check and gossip.
  • The local agent is the authority; anti-entropy repairs the catalog.
  • DNS answers are uncached and may be stale; choose consistent reads for locks.
  • Locks are advisory: add a fencing number.
  • Intentions decide who may call whom, and live in the proxies.
  • ACLs and agent TLS are off until you turn them on. The licence is BUSL 1.1.

Sources