한국어English日本語简体中文繁體中文DeutschไทยTiếng ViệtРусскийPortuguês (Brasil)EspañolBahasa Indonesia

Game Lag White Paper › L7 Server OS (kernel)

Too many threads and context switching Thread oversubscription, context switching

Cause ID so-context · Primary owner Game team (Server development) · Also Infra team (Server infrastructure)

Open the interactive card with figures and simulations →

Running far more threads than there are cores makes the OS spend CPU just switching between them.

Why Hundreds to thousands of threads, for example one thread per connection → Effect Higher context-switching cost (swapping out the running thread) and more cache misses → On screen CPU is busy but throughput is low and ticks are uneven: stutter, slow motion

Symptoms
Stutter, Slow motion
Factors
Stall, Jitter
Who’s affected
Whole server
When
When crowds gather
Owner
Primary owner Game team (Server development) · Also Infra team (Server infrastructure)
Game team action items
Match thread count to core count, use asynchronous I/O (epoll, IOCP).
Infra team action items
Monitor context switches and runnable threads (cs and r in vmstat).
Ballpark numbers
One context switch costs a few µs, and more once you add the cache misses that follow.
On the graph
Rises with load · Context switches per second, runnable threads
Where to look
cs (context switches per second) and r (running or waiting for CPU) from vmstat 1 compared with the core count; voluntary (cswch/s) and involuntary (nvcswch/s) context switches per game server thread from pidstat -w -t
Confirmed if
As concurrent users grow, r climbs far above the core count, cs spikes with it, and hundreds of threads show many involuntary context switches
Ruled out if
r stays at or below the core count: not this cause. Mostly voluntary switches: threads are waiting on locks or I/O (“Lock contention,” “Blocking I/O design”)
Check with
Infra tools (no game code needed)

Sources

  1. Quantifying The Cost of Context Switch (ExpCS 2007) ACM
    Direct cost of a context switch about 3.8 µs; indirect cost including cache effects ranges from a few µs to over 1,000 µs (in the measured setup)
  2. vmstat(8) — Linux manual page procps-ng
    The cs (context switches per second) and r (processes running or waiting to run) fields
  3. I/O Completion Ports Microsoft
    Handle many asynchronous I/Os with a pre-created thread pool and IOCP, and match the number of concurrently running threads to CPU concurrency
  4. pidstat(1) — Linux manual page sysstat
    In -w, cswch/s counts voluntary context switches (the task stopped on its own to wait for a resource) and nvcswch/s counts involuntary ones (forced out after using up its time slice); -t shows them per thread

See also

Same layer: L7 Server OS (kernel)

Same symptom (Stutter), other layers

View the interactive card with figures and simulations