# Go Networking Quick Reference

## HTTP Transport Defaults vs Tuned

| Setting | Default | Recommended (high-throughput) |
|---------|---------|-------------------------------|
| `MaxIdleConns` | 100 | 1000 |
| `MaxConnsPerHost` | 0 (unlimited) | 100 |
| `IdleConnTimeout` | 90s | 90s |
| `ExpectContinueTimeout` | 1s | 0 (skip) |
| `DialTimeout` | 30s | 5s |
| `KeepAlive` | 30s | 30s |

## OS Tuning for High Concurrency (Linux)

| Setting | Command | Purpose |
|---------|---------|---------|
| File descriptors | `ulimit -n 200000` | Allow more open sockets |
| Backlog | `sysctl -w net.core.somaxconn=65535` | Pending connection queue |
| Port range | `sysctl -w net.ipv4.ip_local_port_range="10000 65535"` | More ephemeral ports |
| Reuse | `sysctl -w net.ipv4.tcp_tw_reuse=1` | Reuse TIME_WAIT sockets |
| FIN timeout | `sysctl -w net.ipv4.tcp_fin_timeout=15` | Faster socket reclamation |

## Socket Options

| Option | API | When to Use |
|--------|-----|-------------|
| `TCP_NODELAY` | `conn.SetNoDelay(true)` | Latency-critical (gaming, trading) |
| `SO_REUSEPORT` | Raw syscall via `ListenConfig.Control` | Multi-process binding |
| `SO_RCVBUF/SO_SNDBUF` | `conn.SetReadBuffer(n)` | Buffer = bandwidth × RTT |
| `TCP_KEEPALIVE` | `conn.SetKeepAlive(true)` | Long-lived connections |
| Keepalive period | `conn.SetKeepAlivePeriod(30s)` | Controls TCP_KEEPIDLE only |

## TLS Performance Checklist

- [ ] Session tickets enabled (`SessionTicketsDisabled: false`)
- [ ] ECDHE cipher suites preferred (forward secrecy + performance)
- [ ] AES-GCM ciphers (hardware AES-NI acceleration)
- [ ] ECDSA certificates (shorter signatures than RSA)
- [ ] Curve preferences: P256, X25519
- [ ] ALPN configured (`NextProtos: []string{"h2", "http/1.1"}`)
- [ ] MinVersion set to TLS 1.2+
- [ ] Certificate verification cached for repeat connections

## Protocol Comparison

| | Raw TCP | HTTP/2 | gRPC | QUIC |
|-|---------|--------|------|------|
| **Transport** | TCP | TCP + TLS | TCP + TLS | UDP + TLS 1.3 |
| **Multiplexing** | No | Yes | Yes | Yes (no HOL blocking) |
| **Schema** | None | None | Protobuf | None |
| **0-RTT** | No | No | No | Yes |
| **Connection migration** | No | No | No | Yes |
| **Use case** | Ultra-low latency | Web APIs | Microservices | Mobile, unreliable networks |

## DNS Quick Reference

| Command/Setting | Purpose |
|----------------|---------|
| `GODEBUG=netdns=go` | Force pure-Go resolver (static binary) |
| `GODEBUG=netdns=cgo` | Force cgo resolver (LDAP/mDNS compat) |
| `GODEBUG=netdns=2` | Debug DNS query logging |
| `netgo` build tag | Compile with pure-Go resolver |

## Connection Lifecycle Phases to Instrument

| Phase | What to Measure | Alert Threshold |
|-------|----------------|-----------------|
| DNS resolution | Lookup latency | > 100ms |
| TCP dial | Connection establishment | > 500ms |
| TLS handshake | Crypto negotiation | > 200ms |
| First byte | Time to first response byte | Varies by service |
| Total request | End-to-end latency | p99 target |

## Load Testing Tools

```bash
# Vegeta: constant rate, latency distribution
echo "GET http://host/path" | vegeta attack -rate=100 -duration=30s | vegeta report
vegeta report -type='hist[0,10ms,50ms,100ms,200ms]' < results.bin

# wrk: max throughput
wrk -t4 -c100 -d30s http://host/path

# k6: scenario-based with ramp
k6 run --vus 50 --duration 30s script.js
```

## Resilience Pattern Summary

| Pattern | When | Implementation |
|---------|------|---------------|
| Circuit breaker | Remote service failures | Sliding window failure count → open → half-open → closed |
| Passive load shedding | Queue overflow | Bounded channel, drop on full |
| Active load shedding | CPU overload | Monitor CPU, return 503 with Retry-After |
| Backpressure | Slow consumers | Context timeout on enqueue |
| Rate limiting | Per-client fairness | Token bucket (refill periodically) |

## Scheduler Debugging

```bash
GODEBUG=schedtrace=1000 ./app        # Print scheduler state every 1s
GODEBUG=schedtrace=1000,scheddetail=1 ./app  # Detailed per-P/M/G state
GODEBUG=netpoll=1 ./app              # Log netpoller events
```

## Go Version Performance Notes

| Version | Networking Impact |
|---------|------------------|
| Go 1.24 | Swiss Tables hash map (faster map operations in connection tracking) |
| Go 1.25 | TLS handshake ~58% faster since 1.23 (TLS 1.3 fast path) |
| Go 1.26 | Small allocation specialization (sub-32-byte), `io.ReadAll` ~2× throughput |
