While a Rails ActionController::Live build-log stream stays open for twenty minutes, which threads and Active Record connections does it tie up?
answer
- a server thread iterating the body
- Concurrent::CachedThreadPool named action_controller.live
- SizedQueue of 10 chunks
- connections leased per thread
- live_streaming_excluded_keys (8.1.2)
basics
~20 sOne web server thread iterating the body and one live thread running the action. The live thread checks out its own Active Record connections; a transaction or sticky lease held across sleeps pins one for the whole stream.
solid answer
~40 s`ActionController::Live` runs the action on a thread from a `Concurrent::CachedThreadPool` named `action_controller.live`; the server thread waits for the first write, then spends the rest of the stream iterating the body, which is fed through a 10-slot `SizedQueue`. So each open stream costs a server thread and a live thread, and with the generated 3 Puma threads three viewers can starve a process. Connections are leased per thread, so the live thread checks out its own: plain queries return theirs after each query, but a `transaction` block, `lease_connection` or the soft-deprecated `ActiveRecord::Base.connection` pins one for as long as it is held, so a sleeping loop inside them drains the pool into `ConnectionTimeoutError`. Execution state is copied too, so `connected_to(role: :reading)` follows the stream unless `live_streaming_excluded_keys` (8.1.2) excludes `:active_record_connected_to_stack`.
code
ruby · 15 lines# Pins one connection per viewer for the whole stream
Build.transaction do
loop do
sse.write(build.log_lines.where("number > ?", last).pluck(:body))
sleep 1
end
end
# Holds a connection only while each query runs
loop do
bodies = build.log_lines.where("number > ?", last).pluck(:body)
sse.write(bodies) if bodies.any?
break if build.reload.finished?
sleep 1
endgo deeper
Recall that ActionController::Live runs the action on a separate thread and that every open stream keeps resources busy until it closes.
Explain the hand-off: the server thread waits for commit, then iterates the body while the live thread writes into a bounded queue.
Diagnose pool exhaustion from transactions or leases held across sleeps, budget server threads per viewer, and use live_streaming_excluded_keys when replica routing leaks into streams.
Decide how many held-open viewers a process should carry and when live fan-out belongs on a dedicated push channel instead of request threads.
## Two threads per open stream `ActionController::Live` overrides the controller's `process`. When a request arrives: 1. The **web server thread** that received it calls `process`, which posts the action to a thread pool and then waits until the response is committed (`await_commit`). 2. A **live thread** from that pool runs the action and its filters. It starts with copies of the request thread's thread-local variables and a copy of its Active Support execution state. 3. At the first write (or close) the response commits; the server thread wakes, returns status, headers and the body object up the Rack stack, and **starts iterating that body**, pulling chunks from a queue the live thread fills. So a build-log stream held open for twenty minutes occupies **one server thread and one live thread for twenty minutes**. The generated `config/puma.rb` runs 3 threads per process (`RAILS_MAX_THREADS`), so three idle viewers on one process can starve every other request on it. ## The live thread pool The pool is `ActionController::Live.live_thread_pool_executor`, a `Concurrent::CachedThreadPool` named `action_controller.live`. A cached pool creates threads on demand and reuses idle ones; it has no small fixed size, so the real limit on concurrent streams is the number of server threads, not this pool. Each new stream also copies every thread-local variable into the live thread, which the Rails guide notes has a cost when there are many. ## Backpressure: a ten-slot queue `Live::Buffer` uses a `SizedQueue` whose size is `Live::Buffer.queue_size`, **10** by default. If the browser reads slowly, the server thread waits on the socket, the queue fills, and the live thread's next `write` **blocks**. That is the right behaviour, as it bounds memory, but it means a stalled client also stalls the action. ## Active Record connections in the live thread The connection pool hands out connections per **execution context**, which for the default isolation level is the thread. The live thread is a different context from the server thread, so its queries never reuse the request thread's connection; they check out their own. What happens next depends on how the code touches the database: | code in the live thread | connection held | |---|---| | plain queries (`find`, `where(...).to_a`, `update`) | checked out for the query and returned when it finishes, via `with_connection` | | `ActiveRecord::Base.transaction do ... end` | one connection for the whole block | | `ActiveRecord::Base.lease_connection` or the soft-deprecated `ActiveRecord::Base.connection` | a sticky lease, kept until released | The trap is a stream that wraps its loop in a transaction or takes a sticky lease and then sleeps between polls: each open stream **pins one connection** for its lifetime. The generated `database.yml` sizes `max_connections:` from `RAILS_MAX_THREADS`, so a few viewers can drain the pool, and ordinary requests wait `checkout_timeout` and fail with **`ActiveRecord::ConnectionTimeoutError`**. Keep each database touch short, never sleep inside a transaction, and if code did take a lease, return it with `ActiveRecord::Base.connection_pool.release_connection` before sleeping. ## Replica routing follows the stream Because the live thread receives a copy of the request's execution state, it inherits whatever `connected_to` set up. An action that starts streaming inside `ActiveRecord::Base.connected_to(role: :reading)` keeps using the replica, and a write from the live thread raises `ActiveRecord::ReadOnlyError`. Rails **8.1.2** added `config.action_controller.live_streaming_excluded_keys`, an array of execution-state keys not to copy; listing `:active_record_connected_to_stack` gives the live thread its own connection routing. By default nothing is excluded. ## Spotting the symptoms - Requests that do not stream start timing out or queueing while a handful of dashboards are open: server threads are held by streams. - `ActiveRecord::ConnectionTimeoutError` appears in unrelated actions, with the message that all pooled connections were in use: streams are holding connections. - Writes from a stream fail with `ActiveRecord::ReadOnlyError` only when the page that opened it ran under a reading role: inherited `connected_to` state. ## What to do about it - Keep streaming actions in a dedicated controller, so ordinary actions do not run on live threads. - Budget server threads for the number of simultaneous viewers, or move fan-out to a push channel built for many idle clients. - Poll the database in short queries, outside any transaction, and sleep with no connection checked out. - Exclude `:active_record_connected_to_stack` when streams start under a reading role but must write.
- Why does an ActionController::Live write sometimes block for seconds at a time?The live thread writes into a `SizedQueue` of 10 chunks (`Live::Buffer.queue_size`) that the server thread drains as the socket accepts data. When the browser reads slowly the queue fills and `write` waits for space. It bounds memory, but a slow client also slows the action.
- A streaming action began inside connected_to(role: :reading) and its write raises ActiveRecord::ReadOnlyError. Why, and what is the fix?The live thread receives a copy of the request's execution state, including the connected_to stack, so it still routes to the reading role. In Rails 8.1.2 and later, set `config.action_controller.live_streaming_excluded_keys = [:active_record_connected_to_stack]` so the live thread starts with its own routing, or do the write outside the reading block.
- A Live action shares the request thread's database connection, so it costs nothing extra.
- Once the headers are sent, the web server thread is free for other requests.
- Rails caps live threads with a small fixed pool sized from RAILS_MAX_THREADS.
- Plain Active Record queries in the live thread pin a connection until the stream closes.
- connected_to(role: :reading) never affects the live thread, because it is a new thread.
Assumes Rails 8.1.2 or later in the 8.1 series, where config.action_controller.live_streaming_excluded_keys exists and queries check connections out per query unless a lease is held.