Elixir新手压测超时排查:如何获取Ranch连接与请求队列统计
Hey there, fellow Elixir newbie! I’ve been in your shoes dealing with load test timeouts and wondering how to dig into Ranch’s internals—let’s break this down step by step.
1. Getting Real-Time Connection & Queue Stats from Ranch
Absolutely, Ranch does expose built-in statistics for your listeners. Here’s how to access them:
Use the
ranch:get_stats/1function: This is your go-to for per-listener metrics. Pass in the name of your Ranch listener (you’ll find this in your app’s config, e.g.,:my_app_httpfor a Phoenix HTTP listener).
In an IEx shell, run:ranch:get_stats(:your_listener_name)The returned map will include key metrics:
- active_connections: The number of currently open, active connections
- waiting_connections: The number of requests sitting in the queue waiting to be processed
- total_connections: Total connections handled since the listener started
- max_connections: The configured maximum connections (matches your
max_connectionssetting)
For continuous monitoring: If you want to watch these numbers in real time, you can write a quick loop in IEx:
loop = fn -> stats = ranch:get_stats(:your_listener_name) IO.puts("Active: #{stats.active_connections}, Waiting: #{stats.waiting_connections}") :timer.sleep(1000) loop.() end loop.()
2. Deeper Erlang & Ranch Monitoring
Since you’ve hit CPU/memory limits, you’ll want to dig beyond just Ranch stats:
Erlang Observer: This is a built-in visual tool that’s incredibly helpful. Start it with:
observer:start()It shows you:
- A process list (look for Ranch worker processes—they’ll be named like
ranch_worker_*) - Memory usage breakdowns (heap, binary, etc.)
- Port activity (Ranch uses ports for network connections)
- CPU usage per process, so you can spot bottlenecks
- A process list (look for Ranch worker processes—they’ll be named like
System-level Erlang stats: Use these functions in IEx to get raw system data:
erlang:memory(): Detailed memory usage (total, processes, binaries, etc.)erlang:system_info(process_count): Total number of Erlang processes runningerlang:ports(): List of all open ports (each Ranch connection is a port)
3. Tuning Tips Based on Metrics
Once you have the stats, here’s what to look for:
- If
active_connectionshits yourmax_connectionsvalue andwaiting_connectionsstarts growing, that’s a sign you need to either increasemax_connections(if your server has resources) or optimize your request handling to free up connections faster. - If CPU is spiking but
active_connectionsis low, check if your request processing logic is slow (e.g., blocking calls, inefficient computations). Use:timer.tc(fn -> your_processing_function() end)to measure how long each request takes.
内容的提问来源于stack exchange,提问作者enamrik

