> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# Go 单机百万连接不是梦：netpoll 与 epoll 的 3 个瓶颈
- URL: https://zyx322.xyz/csdn-2026-10-16-c2c70a0dcd6a/
- Published: 2026-10-16T04:00:00.000Z
- Updated: 2026-11-26T07:09:49.000Z
- Author: ZYX
- Tags: Golang

“单机百万连接"是一个被讲烂了的口号（C1000K）。但真正压到 20 万的时候，我遇到的不是"性能不够”，而是一条冷冰冰的报错：

```
accept: too many open files

```

那一刻我才意识到，**百万连接的第一道门槛不是 Go 的性能，是内核参数**。这篇从 epoll 讲到 Go netpoll，再拆 3 个真实的瓶颈和突破方法。

### 一、先看清：Go 为什么不用线程池

传统 C 服务处理并发连接，要么"一连接一线程"（内存爆炸），要么上 epoll + 线程池（复杂度高）。Go 的解法是把 epoll **封进 runtime**，让每个 goroutine 看起来像"阻塞在自己的连接上"，实际上底层是事件驱动。

![一、先看清：Go 为什么不用线程池](https://zyx322.xyz/content/images/csdn/08107f8f144b16a8c1840918da52.png)

关键点：**Go 把 epoll 的阻塞等待从"业务线程"里抽出来，交给 runtime 的 netpoller**。业务 goroutine 发起 `conn.Read()` 时，如果数据没到，它会被挂起（不是占着线程），fd 注册到 epoll，等 netpoller 通知再恢复。

这样，**10 万连接只需要很少的线程**，内存也不爆炸（每个阻塞在 Read 的 goroutine 只占一个初始栈 2KB）。

### 二、瓶颈 1：`ulimit -n`（文件描述符上限）

每个 socket 是一个文件描述符（fd）。默认 `ulimit -n` 往往是 1024 或 65535——**远不够百万连接**。

```bash
# 查看当前限制
ulimit -n
cat /proc/<pid>/limits | grep "open files"

# 查看系统级上限
cat /proc/sys/fs/file-max
cat /proc/sys/fs/file-nr      # 已分配 / 未使用 / 最大值

```

**修法分三层**（缺一层都不生效）：

| 层级         | 设置                                                 | 说明          |
| ---------- | -------------------------------------------------- | ----------- |
| 进程级（临时）    | ulimit -n 1000000                                  | 当前 shell 生效 |
| 进程级（永久）    | /etc/security/limits.conf 加 \* soft nofile 1000000 | 需重登录        |
| 系统级        | fs.file-max = 1000000（sysctl）                      | 整个系统的 fd 上限 |
| systemd 服务 | LimitNOFILE=1000000                                | 服务单元里单独配    |

systemd 是重灾区——**很多人在 limits.conf 配好了，但服务是 systemd 拉起的，读不到那个配置**。必须在 unit 文件里显式写。

### 三、瓶颈 2：内核参数（somaxconn / syn backlog）

即使 fd 够，TCP 的三次握手队列也会成为瓶颈：

```bash
cat /proc/sys/net/core/somaxconn              # accept 队列长度，默认 128/4096
cat /proc/sys/net/ipv4/tcp_max_syn_backlog    # SYN 半连接队列，默认 1024/2048
cat /proc/sys/net/ipv4/ip_local_port_range    # 本地端口范围

```

三者关系：

- **SYN 队列**：收到 SYN 但还没完成三次握手的连接；
- **accept 队列**：已完成握手、等应用 `accept()` 的连接（长度受 `somaxconn` 和 `listen()` 的 backlog 参数**两者取小**限制）。

**判据**：`ss -s` 看统计，或者

```bash
# 看是否有 SYN/accept 队列溢出
netstat -s | grep -E "SYNs to LISTEN|overflow|dropped"
# 或
nstat -az | grep -i -E "ListenOverflows|ListenDrops"

```

`ListenOverflows` 增长 = accept 队列满了，新连接被丢弃；`SYNs to LISTEN sockets dropped` \= SYN 队列满。

**调优清单**：

```bash
sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_max_syn_backlog=65535
sysctl -w net.ipv4.ip_local_port_range="1024 65535"
sysctl -w net.ipv4.tcp_tw_reuse=1          # 复用 TIME_WAIT（客户端侧）
sysctl -w net.ipv4.tcp_fin_timeout=15

```

### 四、瓶颈 3：Go runtime netpoll 的调度开销

这是唯一一个"代码层"的瓶颈。当连接数到几十万时，`netpoller` 本身的效率开始影响吞吐：

- **epoll 实例的 fd 数太大**：`epoll_wait` 返回的事件数组要够大，否则一次拿不完；
- **goroutine 唤醒风暴**：海量连接同时就绪时，netpoller 要把成千上万个 goroutine 挂到 runqueue，**调度器的 work stealing 会抢占 P**；
- **每个连接的 buffer 内存**：`conn.Read(buf)` 的 buf 通常是 4KB，10 万连接 = 400MB 只是读缓冲。

观测手段：

```bash
# 看 runtime 的调度情况（每秒输出）
GODEBUG=schedtrace=1000 ./server

# 看 netpoll 相关的运行时指标
go tool pprof -top http://localhost:6060/debug/pprof/profile
# 关注 net.(*netFD).Read / internal/poll.(*FD).Read / runtime.netpoll

```

**压测验证**（本地起 N 万连接，看内存与 fd）：

```go
package main

import (
	"fmt"
	"net"
	"runtime"
	"time"
)

func main() {
	addr := "127.0.0.1:9000"
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
	}

	// 服务端：accept 后只是挂着，不做 IO
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				return
			}
			go func(conn net.Conn) {
				buf := make([]byte, 1)
				conn.Read(buf) // 永久阻塞在这里，模拟空闲长连接
			}(c)
		}
	}()

	// 客户端：发起 N 条连接
	const n = 100000
	conns := make([]net.Conn, 0, n)
	start := time.Now()
	for i := 0; i < n; i++ {
		c, err := net.Dial("tcp", addr)
		if err != nil {
			fmt.Printf("第 %d 条失败: %v\n", i, err)
			break
		}
		conns = append(conns, c)
		if i%20000 == 0 && i > 0 {
			var m runtime.MemStats
			runtime.ReadMemStats(&m)
			fmt.Printf("已建立 %d 连接, HeapAlloc=%.1fMB, goroutines=%d\n",
				i, float64(m.HeapAlloc)/1024/1024, runtime.NumGoroutine())
		}
	}
	fmt.Printf("共建立 %d 条连接，耗时 %v\n", len(conns), time.Since(start))
	// 典型输出：10 万连接耗时几秒，HeapAlloc 约 200~400MB
	select {}
}

```

**注意 buf 大小**：上面每个连接只分配了 1 字节 buf。真实服务如果用 4KB 读缓冲，10 万连接就是 400MB——所以**连接数上不去，往往先撞的是内存，不是 CPU**。

### 五、内核参数清单（可直接抄）

```bash
# /etc/sysctl.d/99-millions.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
fs.file-max = 1000000

# /etc/security/limits.conf
* soft nofile 1000000
* hard nofile 1000000

```

### 六、总结

1. **百万连接的第一道门槛是 `ulimit -n`**，不是 Go 的性能；systemd 服务必须在 unit 里单独配；
2. 3 个瓶颈：**fd 上限、内核队列（somaxconn/syn backlog）、netpoll 调度开销**；
3. **连接数上不去，先撞的往往是内存**（4KB buf × 10 万 = 400MB），不是 CPU；
4. 排查用 `ss -s` / `nstat`（看队列溢出），调优用 `sysctl` \+ `limits.conf`；
5. Go 的 netpoll 让"每连接一个 goroutine"成为可能，但**它省的是线程，不是内存**。

**留个问题给你**：你们线上 `ulimit -n` 配的多少？65535 够吗？有没有遇到过 accept 队列溢出但 CPU 和内存都很闲的情况？