# Measure network latency

> Measure pure TCP round-trip latency from your server to Supanode TPU Sender metros using a zero-dependency Rust tool — no API key, no transactions, no ICMP ping noise.

Measure the pure network round-trip time (RTT) from your trading box to any Supanode TPU Sender metro before picking a region. The zero-dependency Rust utility below measures a bare TCP handshake (`connect()`) directly against the sender's HTTP port — no API key, no HTTP request, and no transaction required.

Network distance depends entirely on where your machine sits: the same metro can be under 1 ms away from one data center and 10+ ms from another. Always run the measurement from the exact server that will submit transactions.

## What this measures — and what it doesn't

| Measured here | Not measured here |
| --- | --- |
| The network round trip from your machine to the sender's endpoint | How fast the sender ingests, validates, and forwards a transaction |
| Connection jitter (`min`, `median`, `p90`, `max`) across repeated handshakes | How fast it reaches the current leader (staked connections and routing) |
| | Whether and in which slot the transaction lands on-chain |

<Note>
**Closer over the network does not automatically mean faster landing.** This tool isolates the network distance leg precisely; always evaluate end-to-end landing speed on real transactions as well.
</Note>

## Why TCP connect, not `ping` or `/health`

- **ICMP `ping` is unreliable:** routers and firewalls frequently rate-limit, deprioritize, or block ICMP, and the reply may come from a front router or edge device rather than the host serving your transactions.
- **HTTP `/ping`, `/health`, or `getHealth` adds noise:** on top of network RTT it includes server request handling and connection-reuse effects, and many tools print whole milliseconds (`0 ms` inside one metro tells you nothing).
- **One sample is noise:** take at least 10 rounds and look at `min` (the network floor), `median` (typical RTT), and `p90` / `max` (jitter).

### How `tcp-latency` works

`TcpStream::connect_timeout()` returns the moment our TCP `SYN` receives its `SYN-ACK`: exactly one network round trip to the host listening on the port your transactions hit. Because the `SYN-ACK` is answered by the remote OS network stack, it contains zero application processing time. Nothing is sent over the socket and the connection closes immediately.

- DNS is resolved once before timing, so lookup latency is excluded (open connections do not pay DNS per transaction).
- TLS and QUIC handshakes are intentionally excluded because key exchange and certificate validation add protocol work that varies across endpoints and obscures pure network distance.

## Supanode TPU Sender metros

Every hosted Supanode TPU Sender metro listens on TCP port `80` (plaintext HTTP) alongside TCP `443` (HTTPS) and UDP `443` (QUIC) — see [Endpoints and transports](https://supanode.xyz/docs/solana/sender/endpoints#regions).

| Metro | Submission URL (example) | Measured host:port |
| --- | --- | --- |
| Frankfurt | `http://fra.tpu.supanode.xyz/binary` | `fra.tpu.supanode.xyz:80` |
| Amsterdam | `http://ams.tpu.supanode.xyz/binary` | `ams.tpu.supanode.xyz:80` |
| London | `http://lon.tpu.supanode.xyz/binary` | `lon.tpu.supanode.xyz:80` |
| New York | `http://ny.tpu.supanode.xyz/binary` | `ny.tpu.supanode.xyz:80` |
| Los Angeles | `http://la.tpu.supanode.xyz/binary` | `la.tpu.supanode.xyz:80` |
| Tokyo | `http://toy.tpu.supanode.xyz/binary` | `toy.tpu.supanode.xyz:80` |

You can pass any other HTTP/HTTPS endpoint (for example `http://other-sender.example.com/send`) on the same command line to compare network distance from your server side by side.

## Build

The program uses only the Rust standard library (zero external crates). Save the source code below as `tcp_latency.rs` and compile directly with `rustc`:

```bash
rustc -O tcp_latency.rs -o tcp-latency
```

Or drop it into a Cargo project as `src/main.rs`:

```bash
cargo build --release   # -> target/release/tcp-latency
cargo test              # runs URL parsing & secret-redaction tests
```

## Run

Pass endpoints in whatever form you send to them — a full URL or `host[:port]`:

```bash
./tcp-latency \
  http://fra.tpu.supanode.xyz/binary \
  http://ams.tpu.supanode.xyz/binary \
  http://lon.tpu.supanode.xyz/binary \
  http://ny.tpu.supanode.xyz/binary \
  http://la.tpu.supanode.xyz/binary \
  http://toy.tpu.supanode.xyz/binary
```

- `http://...` defaults to port `80`, `https://...` defaults to port `443`, and a bare host defaults to port `80` unless a port is specified.
- Path, query string, and `user:password@` are ignored and **never printed**, so passing a URL that contains an API key is safe: only `host:port` appears in output.

### Options

| Option | Default | Meaning |
| --- | --- | --- |
| `-n ROUNDS` | `10` | Number of TCP connects per endpoint |
| `-g GAP_MS` | `200` | Pause between connects, in milliseconds |
| `-t TIMEOUT_MS` | `3000` | Connects taking longer count as failed |
| `-6` | off | Measure the endpoint's IPv6 address instead of IPv4 |

## Example output

Measured from a European VPS across all six Supanode TPU Sender metros (`-n 10 -g 100`; your numbers will vary by data center):

```text
endpoint                 address                     ok       min    median       p90       max  (ms)
fra.tpu.supanode.xyz:80  198.13.139.100:80        10/10     6.123     6.283     6.443     6.628
ams.tpu.supanode.xyz:80  63.254.167.44:80         10/10    11.734    12.002    12.090    13.009
lon.tpu.supanode.xyz:80  64.130.46.0:80           10/10    17.161    17.364    18.010    23.444
ny.tpu.supanode.xyz:80   64.130.35.188:80         10/10    83.297    86.364    87.681    88.504
la.tpu.supanode.xyz:80   64.130.58.118:80         10/10   140.326   140.863   141.721   141.992
toy.tpu.supanode.xyz:80  63.254.178.240:80        10/10   235.200   238.531   240.944   242.014
```

- **`endpoint`** — the `host:port` connected to.
- **`address`** — the resolved IP actually measured.
- **`ok`** — successful connects out of total rounds. If any failed, the last error is printed at the end of the line (`Connection refused` means nothing listens on that port; `timed out` means no reply within `-t`).
- **`min`, `median`, `p90`, `max`** — TCP handshake time in milliseconds: fastest sample, middle sample, 90th percentile, and slowest sample.

In the example above, `fra.tpu.supanode.xyz` (`6.3 ms` median) is clearly the closest metro to that host, while cross-Atlantic (`ny` at `86 ms`, `la` at `141 ms`) and Asia-Pacific (`toy` at `239 ms`) reflect physical fiber distance.

## Pitfalls to watch for

<Warning>
**Watch out for CDN/proxy edges.** Any endpoint sitting behind a CDN or reverse proxy (common on generic HTTPS hostnames) terminates TCP at the nearest edge POP — so you end up measuring distance to the edge, not to the transaction sender itself. Always test the direct regional hostnames and confirm the port is actually open.
</Warning>

- **Cold first connect:** the very first handshake can be slightly slower due to route and neighbor caches. Rely on `min` and `median` over 10+ rounds rather than a single sample.
- **Persistent connections:** once a connection is open, each submitted transaction pays the one-way/round-trip network path without repeating the handshake — the RTT measured here is that same network leg.

## Source code (`tcp_latency.rs`)

```rust
//! TCP handshake time from this machine to HTTP endpoints, such as a transaction sender's URL.
//!
//! `connect()` returns when our SYN has got its SYN-ACK back: exactly one network round trip to the
//! box that serves the endpoint's port. The SYN-ACK comes from that box's network stack, so the time
//! holds no request handling. Nothing is sent over the connection (no request, no key), and the
//! connection is closed right away. DNS is resolved once, before timing.
//!
//!   tcp-latency http://fra.tpu.supanode.xyz/binary http://other-sender.example.com/send
//!   tcp-latency -n 30 -g 100 http://fra.tpu.supanode.xyz/binary
//!
//! Standard library only.

use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::process::ExitCode;
use std::thread::sleep;
use std::time::{Duration, Instant};

const USAGE: &str = "\
usage: tcp-latency [-n ROUNDS] [-g GAP_MS] [-t TIMEOUT_MS] [-6] ENDPOINT...

  ENDPOINT       http://host/path, https://host/path, host or host:port
                 (port 80 if none is given, 443 for https://; path and query are ignored)
  -n ROUNDS      connects per endpoint (default 10)
  -g GAP_MS      pause between connects, ms (default 200)
  -t TIMEOUT_MS  a connect that takes longer counts as failed (default 3000)
  -6             use the endpoint's IPv6 address (default: IPv4)";

struct Opts {
    rounds: usize,
    gap: Duration,
    timeout: Duration,
    ipv6: bool,
    endpoints: Vec<String>,
}

fn main() -> ExitCode {
    let opts = match parse_args() {
        Ok(o) => o,
        Err(e) => {
            if !e.is_empty() {
                eprintln!("error: {e}\n");
            }
            eprintln!("{USAGE}");
            return ExitCode::FAILURE;
        }
    };

    // Print host:port only — never path or query (they may hold a key)
    let mut rows = Vec::new();
    for e in &opts.endpoints {
        match host_port(e) {
            Ok((host, port)) => rows.push((format!("{host}:{port}"), Ok((host, port)))),
            Err(err) => rows.push((safe_label(e), Err(err))),
        }
    }
    let w = rows.iter().map(|(label, _)| label.len()).max().unwrap_or(8).max(8);
    println!(
        "{:<w$}  {:<22} {:>7} {:>9} {:>9} {:>9} {:>9}  (ms)",
        "endpoint", "address", "ok", "min", "median", "p90", "max"
    );

    for (label, hp) in rows {
        let (host, port) = match hp {
            Ok(hp) => hp,
            Err(err) => {
                println!("{label:<w$}  {err}");
                continue;
            }
        };
        let addr = match resolve(&host, port, opts.ipv6) {
            Ok(a) => a,
            Err(err) => {
                println!("{label:<w$}  {err}");
                continue;
            }
        };
        let mut times = Vec::with_capacity(opts.rounds);
        let mut last_error = None;
        for round in 0..opts.rounds {
            if round > 0 {
                sleep(opts.gap);
            }
            match handshake(&addr, opts.timeout) {
                Ok(t) => times.push(t),
                Err(err) => last_error = Some(err),
            }
        }
        times.sort_unstable();
        let ok = format!("{}/{}", times.len(), opts.rounds);
        let addr_s = addr.to_string();
        if times.is_empty() {
            println!("{label:<w$}  {addr_s:<22} {ok:>7}  {}", last_error.unwrap_or_default());
            continue;
        }
        let ms = |d: Duration| d.as_secs_f64() * 1000.0;
        // Nearest-rank quantile of the sorted times
        let q = |p: f64| times[((times.len() as f64 * p).ceil() as usize).clamp(1, times.len()) - 1];
        println!(
            "{label:<w$}  {addr_s:<22} {ok:>7} {:>9.3} {:>9.3} {:>9.3} {:>9.3}{}",
            ms(times[0]),
            ms(q(0.5)),
            ms(q(0.9)),
            ms(times[times.len() - 1]),
            last_error.map_or(String::new(), |e| format!("  last error: {e}"))
        );
    }
    ExitCode::SUCCESS
}

fn parse_args() -> Result<Opts, String> {
    let mut o = Opts {
        rounds: 10,
        gap: Duration::from_millis(200),
        timeout: Duration::from_millis(3000),
        ipv6: false,
        endpoints: Vec::new(),
    };
    let mut args = std::env::args().skip(1);
    while let Some(a) = args.next() {
        let mut value = |name: &str| -> Result<u64, String> {
            args.next()
                .ok_or_else(|| format!("{name} needs a value"))?
                .parse::<u64>()
                .map_err(|_| format!("{name} needs a whole number"))
        };
        match a.as_str() {
            "-n" => o.rounds = value("-n")?.max(1) as usize,
            "-g" => o.gap = Duration::from_millis(value("-g")?),
            "-t" => o.timeout = Duration::from_millis(value("-t")?.max(1)),
            "-6" => o.ipv6 = true,
            "-h" | "--help" => return Err(String::new()),
            _ if a.starts_with('-') => return Err(format!("unknown option {a}")),
            _ => o.endpoints.push(a),
        }
    }
    if o.endpoints.is_empty() {
        return Err("no endpoint given".into());
    }
    Ok(o)
}

/// Host and port of an endpoint: a URL (http:// -> 80, https:// -> 443 unless it names a port) or host[:port] (80).
fn host_port(e: &str) -> Result<(String, u16), String> {
    let (rest, default) = if let Some(r) = e.strip_prefix("http://") {
        (r, 80)
    } else if let Some(r) = e.strip_prefix("https://") {
        (r, 443)
    } else {
        (e, 80)
    };
    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let authority = authority.rsplit('@').next().unwrap_or(authority); // drop user:password@
    let bad_port = || "bad port".to_string();
    let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
        // [2001:db8::1]:8080
        let (h, after) = v6.split_once(']').ok_or("bad IPv6 address")?;
        let port = match after.strip_prefix(':') {
            Some(p) => p.parse().map_err(|_| bad_port())?,
            None => default,
        };
        (h.to_string(), port)
    } else {
        match authority.rsplit_once(':') {
            Some((h, p)) => (h.to_string(), p.parse().map_err(|_| bad_port())?),
            None => (authority.to_string(), default),
        }
    };
    if host.is_empty() {
        return Err("no host".into());
    }
    Ok((host, port))
}

/// An endpoint as printed when it can't be parsed: scheme and host only (no user:password@, path or query).
fn safe_label(e: &str) -> String {
    let e = e.split(['?', '#']).next().unwrap_or("");
    let (scheme, rest) = match e.split_once("://") {
        Some((s, r)) => (format!("{s}://"), r),
        None => (String::new(), e),
    };
    let authority = rest.split('/').next().unwrap_or("");
    format!("{scheme}{}", authority.rsplit('@').next().unwrap_or(authority))
}

/// The first address of the wanted family (IPv4, or IPv6 with -6), looked up before any timing.
fn resolve(host: &str, port: u16, ipv6: bool) -> Result<SocketAddr, String> {
    let addrs = (host, port)
        .to_socket_addrs()
        .map_err(|e| format!("can't resolve {host}: {e}"))?;
    let mut addrs = addrs.filter(|a| a.is_ipv6() == ipv6);
    addrs
        .next()
        .ok_or_else(|| format!("no {} address for {host}", if ipv6 { "IPv6" } else { "IPv4" }))
}

/// One TCP handshake: connect, take the time, close. Nothing is sent.
fn handshake(addr: &SocketAddr, timeout: Duration) -> Result<Duration, String> {
    let started = Instant::now();
    let stream = TcpStream::connect_timeout(addr, timeout).map_err(|e| e.to_string())?;
    let took = started.elapsed();
    drop(stream);
    Ok(took)
}

#[cfg(test)]
mod tests {
    use super::{host_port, safe_label};

    #[test]
    fn labels_hide_secrets() {
        assert_eq!(safe_label("http://u:p@fra.example.com:x/path?api-key=SECRET"), "http://fra.example.com:x");
        assert_eq!(safe_label("fra.example.com:x?api-key=SECRET"), "fra.example.com:x");
        assert_eq!(safe_label("fra.example.com:x/path#frag"), "fra.example.com:x");
    }

    #[test]
    fn endpoints() {
        let hp = |e: &str| host_port(e).unwrap();
        assert_eq!(hp("http://fra.example.com/api/send?api-key=SECRET"), ("fra.example.com".into(), 80));
        assert_eq!(hp("https://fra.example.com/fast"), ("fra.example.com".into(), 443));
        assert_eq!(hp("https://fra.example.com:8443/x"), ("fra.example.com".into(), 8443));
        assert_eq!(hp("http://user:pass@fra.example.com/x"), ("fra.example.com".into(), 80));
        assert_eq!(hp("fra.example.com"), ("fra.example.com".into(), 80));
        assert_eq!(hp("fra.example.com:8080"), ("fra.example.com".into(), 8080));
        assert_eq!(hp("10.0.0.1:81"), ("10.0.0.1".into(), 81));
        assert_eq!(hp("http://[2001:db8::1]:8080/x"), ("2001:db8::1".into(), 8080));
        assert_eq!(hp("[2001:db8::1]"), ("2001:db8::1".into(), 80));
        assert!(host_port("http://fra.example.com:x/").is_err());
        assert!(host_port("http:///path").is_err());
    }
}
```

## See also

- [Endpoints and transports](https://supanode.xyz/docs/solana/sender/endpoints) — all hosted metros and HTTP / QUIC transports
- [Quickstart](https://supanode.xyz/docs/solana/sender/start) — send your first transaction with an API key
- [Troubleshooting](https://supanode.xyz/docs/solana/sender/troubleshooting) — diagnose rate limits, refusals, and delivery issues
