揭秘 Linux 内核中隐藏的 TCP 限流
Uncovering Hidden TCP Throttling in the Linux Kernel

原始链接: https://www.cdn77.com/blog/debugging-nginx-linux-contribution

CDN 边缘服务器出现了仅影响 HTTP 缓存未命中时 nginx 下载的随机、可自愈的变慢。内核 TCP 设置、nginx 配置、CPU、内存和日志均正常;只有 rcv_ssthresh 塌缩到 4×MSS。这来自 tcp_under_memory_pressure(),它检查 socket cgroup pressure,而非仅全局 TCP pressure。Systemd 将 nginx 放入启用了内存控制器的 cgroup。内核的 vmpressure() 在约 2MB 窗口内回收释放的扫描页数不到约 40% 时,会将该 cgroup 的 socket 标记为 pressured,即使机器有大量空闲 RAM。这个 cgroup 范围的 flag 会至少限流每个 nginx socket 一秒,导致吞吐量塌陷直到 pressure 清除。问题不是 nginx 或全局 TCP 内存 pressure,而是缓存密集型服务器上低效 reclaim 触发的 cgroup 内存控制器 pressure。

Hacker News 用户讨论一篇博文,博文揭示了 Linux 内核中隐藏的 TCP 限流。该限流由 cgroup 内存压力检测引起:systemd 将服务放入 cgroup,即使未设置内存限制且空闲内存充足,内存控制器仍可根据页面扫描启发式算法对套接字进行限流。建议的绕过方法是启动参数 `cgroup.memory=nosocket`。评论者分享 Linux 性能调试资源,讨论内存压力和脏页行为,指出 cgroup 内存记账中的陷阱(例如文件系统缓存),并提到一个关于扩展扫描窗口的内核 TODO,该 TODO 部分因 LLM 生成的补丁垃圾而被移除。总体而言,该帖将此视为一个令人惊讶、长期存在的性能 bug,并欣赏详细的内核调试写作。
相关文章

原文


One day, a customer was complaining about slow download speeds from one of our edge servers. Since the internet is full of unpredictability, complaints like that occasionally happen, but this time, there were no error codes. We couldn't reproduce the issue. The only thing we could see was lower traffic on the network interface. The strangest part was that it happened randomly, recovered on its own, and it didn't affect all clients connected to that server.

CDNs are usually built in a multi-layer setup. When a client requests content, the closest edge node serves it from its cache. If the content isn't there, the edge fetches it from an upper layer. The request can travel further up until it reaches a shield node, which finally fetches the content from the customer's origin. At CDN77, all these layers run heavily modified nginx. As we would eventually discover, nginx was an important part of this story.

Here's what we could see internally about the complaint: The download speed would collapse for certain connections, stay low for hours, and then recover without anyone touching anything. In one instance, it dropped just before 3 a.m., stayed flat for five hours, and returned to normal around 8 a.m. Nothing told us why. 

So we started with the usual suspects: Maybe it was an ISP, peering, or transit issue; some network problem outside our infrastructure. Maybe one of the kernel's TCP settings was misconfigured - the well-known tcp_rmem, tcp_wmem, or tcp_mem. Or perhaps something in the nginx configuration, like proxy buffering. We also considered disk I/O stalling the cache, CPU or memory saturation, something hidden in the kernel logs, or a particular kernel version.

All reasonable possibilities. And every one of them led to a dead end. Over time, the issue appeared in multiple regions, ruling out a specific ISP or network path. The sysctl settings and nginx configuration were identical to those on healthy neighboring servers. So were the nginx and kernel versions. CPU utilization, memory usage, and kernel logs showed no discrepancies either.

But we noticed something interesting: The issue only appeared on HTTP cache misses. So, when the bug was happening and actively throttling, we launched a curl command on that server to test the download speed. But it was working; only nginx downloaded it slowly. We also noticed that rebooting the server fixed the issue for quite some time. Until, of course, it happened again. At this point, we had a pretty strange combination of symptoms. The problem was:

  • Dynamic,
  • Self-healing,
  • Affected only nginx processes,
  • Appeared on cache-miss connections.

Static config reviews weren't getting us anywhere. We needed to see what was actually happening.

Going further down the rabbit hole

Since only nginx seemed to be affected, we were suspicious of userspace. Maybe nginx was delaying its read syscalls. Maybe it wasn't reading enough bytes per call. We were even desperate enough to suspect that epoll itself was broken. We hooked into the entry and exit points of the read and epoll related syscalls, capturing function arguments, return codes, and syscall durations. If nginx was spending too much time waiting, or doing something strange while reading data, we should have been able to see it. But the experiments showed no anomalies whatsoever. Nginx wasn't delaying its read syscalls. It was issuing them as fast as possible. Was it reading too few bytes? No. It was reading everything available until it hit EAGAIN, exactly as expected.

So userspace probably wasn't the culprit.

Time to look into the kernel.

What if... the bug was in the kernel?

We hooked a kprobe into tcp_rcv_established using bpftrace and started printing fields from struct tcp_sock that could plausibly explain a throughput collapse. Fields like rcv_ssthresh, the advertised maximum segment size, the send congestion window, app_limited, the receive window, etc. (Note: The receive window was our main suspect.)

struct tcp_sock {
...
    u32    window_clamp;   /* Maximal window to advertise */
    u32    rcv_ssthresh;    /* Current window clamp */
...
    u16    advmss;          /* Advertised MSS */
    u32    snd_cwnd;        /* Sending congestion window */
...
    u32    app_limited;     /* limited until "delivered" reaches this val */
...
    u32    rcv_wnd;         /* Current receiver window */
...
};

And finally, we started seeing a pattern. The value of rcv_ssthresh was tiny. Exactly four times the advertised maximum segment size. And that value is only ever written by tcp_adjust_rcv_ssthresh(). In our case, the only viable path leading to that function was through tcp_grow_window(), but only when tcp_under_memory_pressure() returned true.

/* Check #1 */
if (!tcp_under_memory_pressure(sk)) {
    unsigned int truesize = truesize_adjust(adjust, skb);
    int incr;

    /* Check #2. Increase window, if skb with such overhead
     * will fit to rcvbuf in future.
     */
    if (tcp_win_from_space(sk, truesize) <= skb->len)
        incr = 2 * tp->advmss;
    else
        incr = __tcp_grow_window(sk, skb, truesize);

    if (incr) {
        incr = max_t(int, incr, 2 * skb->len);
        tp->rcv_ssthresh += min(room, incr);
        inet_csk(sk)->icsk_ack.quick |= 1;
    }
} else {
    /* Under pressure:
     * Adjust rcv_ssthresh according to reserved mem
     */
    tcp_adjust_rcv_ssthresh(sk);
}

But that was suspicious. Earlier in our debugging, we'd checked the SNMP counters and they reported zero memory pressure, none whatsoever. And yet, tcp_under_memory_pressure() was returning true. Something didn't add up.

$ nstat -z | grep Pressure
TcpExtTCPMemoryPressures        0                  0.0
TcpExtTCPMemoryPressuresChrono  0                  0.0

It turns out that the TCP variant of the memory pressure check is implemented differently from others. Besides checking global TCP memory pressure, it also checks whether the socket's cgroup is under memory pressure. This additional check happens when the cgroup memory controller is loaded, which it is by default on most distributions.

/* optimized version of sk_under_memory_pressure() for TCP sockets */
static inline bool tcp_under_memory_pressure(const struct sock *sk)
{
    if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
        mem_cgroup_under_socket_pressure(sk->sk_memcg))
        return true;

    return READ_ONCE(tcp_memory_pressure);
}

And then it clicked. It was the cgroup memory controller all along. We launch nginx as a systemd service, and systemd places each service into its own cgroup and sets default controllers, like the already mentioned memory controller. The memory controller helps you set limits for the maximum memory consumption of a service, which we are actually not using. It's the well-known memory.high, memory.max, etc. But the memory controller has an undocumented feature, which activates when the controller is only loaded.

The next diagram summarises what was happening. There's a flag which is set per cgroup, not per socket. So one reclaim shortfall throttles every connection nginx owns. When there's memory pressure inside a cgroup, reclaim falls short, and it sets a pressure flag on the memcg, which is a cgroup-wide option that shrinks every socket buffer, basically collapsing all the throughput. Once the pressure clears, it gets back to the normal state.

The pressure is raised through the vmpressure() function, which returns immediately for the root cgroup. So it only does anything for non-root cgroups. If the level rises above low, it writes jiffies + HZ into the memcg socket pressure, and every socket in that cgroup is throttled for at least one second.

void vmpressure(gfp_t gfp, struct mem_cgroup *memcg, bool tree,
        unsigned long scanned, unsigned long reclaimed)
{
    ...
    if (!memcg || mem_cgroup_is_root(memcg))
        return;

    ...

    if (level > VMPRESSURE_LOW) {
        ...
        WRITE_ONCE(memcg->socket_pressure, jiffies + HZ);
    }
    ...
}

You might be asking, what actually raised that pressure?

Memory reclaim reports how many pages it scanned and how many it managed to free per cgroup. Once roughly two megabytes' worth of pages have been scanned, the kernel turns that into a ratio. If it freed less than about 40% of what it walked, that counts as memory pressure, and every socket in the cgroup gets throttled for that one second. What's NOT in the formula is how much free memory the machine has. It's purely a measure of reclaim efficiency over a tiny two-megabyte window. So a cache-heavy server where reclaim keeps walking pages fails constantly, even though it has hundreds of gigabytes of free RAM. The two-megabyte window was a hardcoded constant in the kernel version we were debugging, with a TODO: in the kernel asking it to scale with the machine size.

/*
* TODO: Make the window size depend on machine size, as we do for vmstat
* thresholds. Currently we set it to 512 pages (2MB for 4KB pages).
*/
static const unsigned long vmpressure_win = SWAP_CLUSTER_MAX * 16;
联系我们 contact @ memedata.com