Skip to content

SSH connection multiplexing with ControlMaster — one session for every command

Set up SSH connection multiplexing with ControlMaster, a hashed ControlPath and ControlPersist so repeated ssh, scp, rsync, git and Ansible runs reuse one authenticated session instead of re-handshaking every time.

Every ssh invocation normally opens its own TCP connection, runs a full key exchange and re-authenticates you — and if the host asks for MFA, you type a code every single time. SSH connection multiplexing removes all of that after the first connection: ControlMaster auto makes the first ssh open a control socket, and every later ssh, scp, rsync, git push or Ansible task rides that already-authenticated session instead of building its own. Three lines in ~/.ssh/config take a repeated command from roughly 0.9 s to roughly 0.05 s and reduce MFA prompts to one per ControlPersist window. This guide covers the configuration, the control commands, the socket-path traps, and the failure mode where a dead master leaves new sessions hanging.

What you’ll accomplish

  • Configure ControlMaster auto, a %C-hashed ControlPath and ControlPersist 10m in ~/.ssh/config, scoped per host or globally.
  • Cut a repeated ssh host true from roughly 0.9 s to roughly 0.05 s, measured with time.
  • Make scp, rsync, git over SSH and Ansible reuse the same authenticated session with no extra flags.
  • Inspect and control running masters with ssh -O check, ssh -O stop, ssh -O exit and ssh -S.
  • Recognize and clear the stale-socket failure, and know where multiplexing does not belong.

Prerequisites

  • An OpenSSH client. ControlPersist needs 5.6 or newer, the %C token needs 6.7 or newer, and 8.4 or newer folds the ProxyJump destination into that hash. Check with ssh -V; every current Linux distribution and macOS ships 8.x or 9.x.
  • Microsoft’s Win32 OpenSSH client does not implement connection multiplexing. The options are accepted but no master is created, so use WSL or another client on Windows.
  • Write access to ~/.ssh on a local filesystem. UNIX domain sockets do not work on NFS-mounted home directories; there is a fix in Troubleshooting.
  • Server side, sshd allows several sessions inside one connection by default (MaxSessions 10). If an administrator lowered it, that value caps how many multiplexed sessions you can run at once.
  • Examples use a host alias web1 and a bastion alias bastion-prod. Substitute your own.

How it works

A normal ssh process owns everything: the TCP socket, the negotiated keys, and the session channel inside it. Multiplexing splits those responsibilities. The first connection becomes a master: it keeps the TCP connection and the encrypted transport, and it listens on a UNIX domain socket at the path you set in ControlPath. Every later ssh for the same user, host and port becomes a client of that master. Instead of dialing the network, it connects to the local socket and asks the master to open one more channel inside the connection that already exists. No TCP handshake, no key exchange, no authentication — which is why a multiplexed command completes in tens of milliseconds regardless of how slow the original login was.

Three ssh runs each paying a full handshake, compared with one master connection and a control socket that later runs attach to

Three options drive it. ControlMaster auto means “use the socket if one is usable, otherwise become the master” — that is the setting you almost always want; yes unconditionally tries to create a master and fails if the socket already exists. ControlPersist 10m tells the master to fork into the background and keep the connection alive for ten idle minutes after the last client leaves; with ControlPersist no the master exits as soon as the connection that created it does.

ControlPath is where the socket lives, and it is the option people get wrong. The traditional ~/.ssh/master-%r@%h:%p is readable, but the whole path has to fit in a sockaddr_un structure — 104 bytes on macOS and the BSDs, 108 on Linux. A long username, a fully qualified host name and a deep home directory blow that budget and ssh refuses with a “too long for Unix domain socket” error. %C sidesteps it entirely: it expands to a fixed-length hex digest of the local host, remote host, port and remote user, so the path length never depends on the host name. From OpenSSH 8.4 the %j (jump host) value is part of that digest too, so the same server reached directly and reached through a bastion get separate sockets instead of colliding.

Step-by-step

1. Create a private socket directory. The socket is an unauthenticated door into the remote session — anything that can open it gets a shell there without proving anything, because the master already authenticated. Keep the directory closed to other local accounts:

mkdir -p ~/.ssh/sockets
chmod 700 ~/.ssh/sockets
ls -ld ~/.ssh/sockets
drwx------  2 you  you  4096 Jul 28 09:12 /home/you/.ssh/sockets

2. Add the multiplexing block to ~/.ssh/config. ssh_config uses first-obtained-value-wins, so per-host overrides must appear above the Host * block, not below it:

Host bastion-prod
    HostName bastion.example.com
    User ops
    ControlPersist 4h

Host *
    ControlMaster auto
    ControlPath ~/.ssh/sockets/%C
    ControlPersist 10m

Verify the values that actually apply to a given host with ssh -G, which prints the effective configuration after all Host and Match blocks have been resolved:

ssh -G web1 | grep -E 'controlmaster|controlpersist'
controlmaster auto
controlpersist 600

ControlPersist 10m reports as 600 because it is stored in seconds. If you keep a larger config, SSH client config — host aliases and per-host settings covers how to organize the rest of it.

3. Measure a cold connection. Close any existing master first so you are timing the real handshake:

ssh -O exit web1 2>/dev/null
time ssh web1 true
real    0m0.912s
user    0m0.021s
sys     0m0.010s

4. Measure the multiplexed connection. The previous command left a master behind. Run exactly the same thing again:

time ssh web1 true
real    0m0.048s
user    0m0.006s
sys     0m0.004s

The absolute numbers depend on round-trip time and authentication method. Over a LAN with a key you might see 0.25 s dropping to 0.03 s; across a continent with a hardware token the first number can be several seconds while the second stays near 0.05 s.

5. Confirm the master exists and find its socket.

ssh -O check web1
ls -l ~/.ssh/sockets/
Master running (pid=41207)
srw-------  1 you  you  0 Jul 28 09:14 8f3c1d0a2b9e47c5f1

The leading s marks a socket, and 600 is the mode ssh creates it with. That plus a 700 directory is the whole access control story.

6. Use it from everything else. Nothing here takes a multiplexing flag — scp, rsync and git all shell out to ssh, which finds the socket on its own:

scp ./app.tar.gz web1:/tmp/
rsync -az ./dist/ web1:/srv/app/
git -C ~/src/app push origin main

To see the reuse rather than infer it from the speed, ask for one level of verbosity:

ssh -v web1 true 2>&1 | grep -i mux
debug1: mux_client_hello_exchange: master version 4
debug1: mux_client_request_session: entering

Those mux_client_ lines only appear when the invocation attached to a master. Their absence means you built a fresh connection.

7. Control the master’s lifetime. -O sends a command to a running master instead of opening a session:

ssh -O stop web1
ssh -O exit web1
Stop listening request sent.
Exit request sent.

stop makes the master refuse new multiplexed sessions while letting the ones already running finish — the right move before an OpenSSH upgrade or a maintenance window, so nothing new attaches to a connection you are about to drop. exit terminates the master and every session on it immediately. When you need to address one socket explicitly rather than resolving it from the config, ssh -S takes the path:

ssh -S ~/.ssh/sockets/8f3c1d0a2b9e47c5f1 -O check web1
Master running (pid=41207)

The reverse is ssh -o ControlPath=none web1, which forces a private connection for that one command.

8. Multiplex through a bastion. ProxyJump and multiplexing compose, and each hop gets its own master:

Host bastion-prod
    HostName bastion.example.com
    User ops

Host app-*
    ProxyJump bastion-prod
    User deploy

The first ssh app-01 builds two connections — one to the bastion, one to app-01 tunnelled through it — and leaves a master for each. The second ssh app-01 reuses both, so you skip two handshakes rather than one. Confirm each independently:

ssh -O check bastion-prod
ssh -O check app-01
Master running (pid=41320)
Master running (pid=41344)

See SSH ProxyJump — bastion access without exposing your agent for how the jump itself is set up and secured.

9. Turn it on for Ansible. Ansible spawns ssh per task, so multiplexing is where most of its wall-clock savings live. In ansible.cfg:

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
control_path_dir = ~/.ansible/cp
pipelining = True

Ansible already sets ssh_args to that by default; what is worth changing is ControlPersist, which should comfortably exceed the gap between plays, and pipelining, which stops Ansible from copying a module file over sftp for every single task. Pipelining needs requiretty disabled in the target’s sudoers, which is the default on current distributions. Ansible keeps its sockets in control_path_dir (~/.ansible/cp), separate from your interactive ones — so ssh -O exit on a host will not disturb a running play, and vice versa.

Validate it works

Time three runs back to back. The first pays for the handshake; the next two should be an order of magnitude faster:

ssh -O exit web1 2>/dev/null
time ssh web1 true
time ssh web1 true
time ssh web1 true
real    0m0.905s
real    0m0.051s
real    0m0.047s

Confirm there is exactly one TCP connection behind those three runs. On Linux:

ss -tnp state established '( dport = :22 )'
Recv-Q Send-Q  Local Address:Port   Peer Address:Port  Process
0      0       10.0.4.12:52344      10.0.9.31:22       users:(("ssh",pid=41207,fd=5))

On macOS, lsof -nP -iTCP:22 -sTCP:ESTABLISHED gives the equivalent. One row, one PID — that PID is the master.

Confirm the master goes away on its own. Wait past ControlPersist with no sessions, then check again:

ssh -O check web1
Control socket connect(/home/you/.ssh/sockets/8f3c1d0a2b9e47c5f1): No such file or directory

That message is the healthy end state: the idle timer fired, the master exited, and it removed its socket on the way out.

Troubleshooting

Lifecycle of a ControlMaster from cold connect to ControlPersist expiry, with the stale-socket failure branch and the -O check inspection path

  • “too long for Unix domain socket”. Your ControlPath expands past the 104/108-byte limit — usually a %r@%h:%p pattern with a long FQDN, or a home directory under a deep automount path. Replace the tokens with %C, which is fixed-length. If your home directory alone is already long, move the sockets out of it: ControlPath /run/user/%i/ssh-%C on systemd hosts, where %i is your local user ID.
  • New sessions hang after a network change. The master process is alive but its TCP connection is black-holed — a suspended laptop, a VPN reconnect, an expired NAT mapping. Clients block waiting on a master that will never answer, and even ssh -O check hangs. Kill the master by PID (from the ss/lsof output above) and delete the socket file. Prevent the recurrence with ServerAliveInterval 30 and ServerAliveCountMax 3 in the same config block, so the master notices the dead peer within about 90 seconds and exits by itself.
  • “ControlSocket … already exists, disabling multiplexing”. A master was killed without cleaning up, so the file is there but nothing is listening. ssh warns and falls back to a private connection rather than failing, which is why this often shows up only as unexplained slowness. Run ssh -O check to confirm nothing answers, then rm the socket file.
  • Everything breaks right after an OpenSSH upgrade. A master started by the old binary speaks an older multiplexing protocol than the new client, which refuses to attach. There is nothing to repair — close the stale masters (ssh -O exit per host, or remove the socket directory’s contents when no sessions are open) and reconnect. Worth adding to your workstation upgrade routine.
  • Agent forwarding is missing in the second session. Forwarding belongs to the master, not to the client that asks for it. If the first connection was made without ForwardAgent yes or -A, later multiplexed sessions have no SSH_AUTH_SOCK on the remote host even when they pass -A. The same applies to X11 and to port forwards, which must be requested through ssh -O forward on the master. Decide the forwarding policy in ~/.ssh/config so the master always starts with it, and ssh -O exit before changing your mind.
  • Sockets on an NFS home directory. Creating a UNIX socket on NFS fails outright or produces a file other hosts can see but not use, so masters silently never form. Point ControlPath at local storage instead — /run/user/%i/ssh-%C on a systemd login session, or a 700 directory you own under /tmp.

When this is the wrong approach

Multiplexing trades isolation for speed. That trade is wrong often enough to be worth naming.

  • Shared machines and CI runners. The control socket grants session access with no authentication. On a build agent where other jobs, other users, or a container runtime can reach your home directory, a persistent master is a credential sitting on disk. Use ControlPersist no, or skip multiplexing entirely, wherever the filesystem is not exclusively yours.
  • Per-session audit requirements. If your organization requires every administrative session to authenticate individually — a common MFA and privileged-access rule — multiplexing deliberately defeats it. Check the policy before rolling this out fleet-wide; a short ControlPersist such as 60s is sometimes an acceptable middle ground, and sometimes not.
  • Sustained bulk transfer alongside interactive work. All multiplexed sessions share one TCP connection and its congestion window. A long rsync and your shell compete for the same pipe, and one stalled channel can make the others feel sluggish. For large transfers, -o ControlPath=none gives the copy its own connection.
  • Hosts behind a load balancer or anycast address. Every session on a master lands on whichever backend the original connection reached. If you are relying on the balancer to spread you across nodes, or checking that several backends are healthy, multiplexing pins you to one.
  • Long-lived automation with weak failure handling. A hung master turns one dead connection into a stalled queue of every job that would have reused it. If your scheduler has no timeout, prefer a fresh connection per run.

The authoritative references are the OpenSSH ssh_config manual, which defines ControlMaster, ControlPath and ControlPersist and lists every % token, and the ssh manual for the -O, -S and -M flags.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.