How-To Guide

How to Implement Happy Eyeballs

Connect fast on dual-stack hosts with Happy Eyeballs: race IPv6 and IPv4, prefer IPv6 with a head start, and connect to whichever answers first.

On this page

  1. Introduction
  2. The Dual-Stack Dilemma
  3. The Algorithm
  4. Choosing the Head Start
  5. Racing and Cancelling
  6. Where It Lives
  7. Metrics and Failure Detection
  8. Common Pitfalls and Conclusion

Introduction

A dual-stack host has both AAAA (IPv6) and A (IPv4) addresses, and either path can be fast or broken. Connecting to IPv6 first and waiting can stall for seconds when IPv6 is unreachable; connecting only to IPv4 gives up the IPv6 benefit. Happy Eyeballs resolves the dilemma by racing both: start the IPv6 attempt and, after a short head start, start the IPv4 attempt in parallel, and use whichever connection completes first. It is a small amount of logic that removes a large latency cliff.

The Dual-Stack Dilemma

When a name resolves to both AAAA and A records, the client must choose. Preferring IPv6 fails painfully when IPv6 is advertised but broken (a common state during a rollout), because the client waits for a connection timeout before falling back. Preferring IPv4 always works but ignores IPv6 entirely, losing its benefits where it does work.

The worst case is a host that has an IPv6 route but no connectivity to the destination over IPv6: the connection attempt hangs until a timeout, adding seconds to the request. Happy Eyeballs was designed to avoid exactly this cliff.

The problem is not theoretical: during an IPv6 rollout, a network can advertise AAAA records before the connectivity is reliable, so clients that prefer IPv6 systematically wait and then fall back. Browsers and runtimes adopted Happy Eyeballs precisely because this failure mode caused real user-visible latency.

It is also a moving target: a path that works over IPv6 today can break tomorrow, so the client cannot assume a family is good and must measure the outcome of each attempt.

# the dual-stack problem
name -> AAAA (IPv6) + A (IPv4)
prefer IPv6 and it is broken -> wait for a timeout, then fall back (seconds)
prefer IPv4                  -> ignores IPv6, loses its benefit
# Happy Eyeballs: race both, IPv6 gets a head start, first to connect wins

The Algorithm

Sort the addresses with IPv6 first. Start a connection to the first (IPv6) address. After a short delay (the head start, typically around 250 milliseconds), if it has not connected, start a connection to the first IPv4 address in parallel. Whichever connects first wins; the others are cancelled. If neither connects, try the next addresses.

The head start gives IPv6 a chance to win when it works, favouring the better protocol, while the parallel IPv4 attempt bounds the worst case to the head start plus the connection time, rather than a full IPv6 timeout.

import { connect } from 'node:net';

function tryConnect(address: string, timeoutMs: number): Promise<{ address: string; socket: import('node:net').Socket }> {
  return new Promise((resolve, reject) => {
    const socket = connect({ host: address, port: 443 });
    const timer = setTimeout(() => { socket.destroy(); reject(new Error('timeout')); }, timeoutMs);
    socket.once('connect', () => { clearTimeout(timer); resolve({ address, socket }); });
    socket.once('error', (e) => { clearTimeout(timer); reject(e); });
  });
}

export async function happyEyeballs(v6: string[], v4: string[], headStartMs = 250) {
  const attempts: Promise<{ address: string; socket: import('node:net').Socket }>[] = [];
  attempts.push(tryConnect(v6[0], 10_000));                 // IPv6 first
  setTimeout(() => attempts.push(tryConnect(v4[0], 10_000)), headStartMs); // then IPv4
  const winner = await Promise.any(attempts);               // first to connect wins
  return winner;
}

Choosing the Head Start

The head start is a trade-off. Too long and a broken IPv6 connection costs the full head start before IPv4 even starts, defeating the point. Too short and IPv6 rarely wins even when it works, so you do not get its benefit. Around 250 milliseconds is the common value, since a working IPv6 connection usually completes well within it on most paths.

Some implementations use a shorter initial head start and increase it per attempt, or use the measured connection time of earlier attempts to order the remaining addresses. The goal is the same: give IPv6 a fair chance without letting a broken IPv6 path dominate.

# head start trade-off
too long  -> broken IPv6 costs the whole head start before IPv4 starts
too short -> IPv6 rarely wins even when it works (no IPv6 benefit)
~250ms    -> a working IPv6 connection usually completes within it
# variants: increase the head start per attempt, or order by measured times

Racing and Cancelling

When the first attempt connects, cancel the others: abort the in-flight connection attempts and close any sockets already opened. Leaving them open wastes resources and can confuse the connection pool. The race must cancel cleanly, not just ignore the losers.

Also bound each attempt with its own timeout, because an attempt that never resolves would otherwise keep the race open and hold resources. The overall operation should complete as soon as any attempt succeeds or all attempts fail.

# race discipline
[ ] on the first success: abort/close the other in-flight attempts
[ ] each attempt has its own timeout
[ ] the overall operation ends on first success OR all-fail
# not cancelling => wasted sockets and confusing pool state

Where It Lives

Happy Eyeballs belongs in the connection layer, not in application code repeated everywhere. Many runtimes and HTTP clients implement it natively; check whether yours does before adding your own. Where it is not built in, a connection helper that races the addresses is the right place.

It also matters for the connection pool: a pool keyed only by hostname should connect via Happy Eyeballs and cache the winning route, so subsequent pooled connections do not repeat the race unnecessarily.

# where it belongs
[ ] in the connection layer (helper or client library), not per call site
[ ] check whether your runtime/client already implements it
[ ] a pool keyed by hostname connects via Happy Eyeballs and reuses the route
# don't repeat the race on every pooled connection if the route is known-good

Metrics and Failure Detection

Measure which family won and how long each attempt took. A high rate of IPv4 wins with slow IPv6 attempts indicates a broken IPv6 path, which is worth alerting on: the network advertises IPv6 but cannot reach the destination, and every request pays a head start.

Track the connection failure rate per family. A family that consistently fails should be deprioritised or reported, because the DNS records advertise connectivity that does not work. Happy Eyeballs hides the latency but not the problem; the metrics reveal it.

# metrics worth emitting
happy_eyeballs_winner{family="ipv6|ipv4"}   which family won the race
connect_duration{family}                     per-family connect time
connect_failures_total{family}               a broken family shows here
# high ipv4 wins + slow ipv6 => broken IPv6 path: alert, don't just hide it

Common Pitfalls and Conclusion

Do not start IPv4 immediately with no head start; that is just racing and IPv6 will rarely win. Do not set a head start so long that a broken IPv6 path dominates. Do not forget to cancel the losing attempts. And do not implement it per call site when the runtime or the connection pool can do it once.

Happy Eyeballs connects fast on dual-stack hosts by racing IPv6 and IPv4 with a short head start and using whichever connects first. Sort IPv6 first, start IPv4 after the head start, cancel the losers, keep it in the connection layer, and measure which family wins. It removes a latency cliff without giving up IPv6 where it works.

Sources: RFC 8305: Happy Eyeballs v2, RFC 6555: Happy Eyeballs, Node.js: net.connect.

FAQ

Why not just always prefer IPv6?
Because an advertised but broken IPv6 path makes the client wait for a full connection timeout before falling back, adding seconds per request. Happy Eyeballs gives IPv6 a head start but starts IPv4 in parallel, bounding the worst case to the head start.
How long should the head start be?
Around 250 milliseconds is common: long enough that a working IPv6 connection usually completes within it, short enough that a broken IPv6 path costs only that much before IPv4 starts. Tune against your network's measured connect times.

Related Examples