レストランで理解する Rack・プロセス・スレッド・Unicorn・Puma・Action Cable
普段 Controller や Model を書いているぶんには、Rails の下で何が動いているかを意識することはあまりありません。 ところが、 Rails アプリにリアルタイムチャットや通知のような「つなぎっぱなし」の機能を入れようとすると 、急に「Unicorn だと相性が悪い」「Action Cable なら大丈夫」といった話が出てきます。 この記事では、そうした話を理解するための土台となる Rails の足元の仕組みを、 レストラン にたとえて整理します。 1. Rack:注文票の共通フォーマット Rack は、 Ruby の Web サーバーと Web アプリをつなぐ共通の約束事 です。 call(env) を持ち、 [ステータス, ヘッダ, ボディ] を返すオブジェクトなら Rack アプリ class HelloApp def call ( env ) [ 200 , {…
The article explains the underlying mechanics of Rails, using a restaurant analogy for better understanding.
1. Rack is the common format for an order ticket, connecting a Ruby web server to a web application. It returns a status, header, and body, allowing different hosting options like Unicorn or Puma with Rails or Sinatra.
2. Layers include the web server (Unicorn/Puma), the restaurant (Rack + middleware), the application layer (Rails), and the kitchen (where Rails' controller and model run).
3. Processes are the restaurant, and threads are the employees. Processes have their own memory with separate costs, while threads share memory but can cause thread safety issues. Ruby uses class and global variables to avoid shared data errors.
4. Blocking occurs when a thread is waiting for something, causing it and other threads to stop. This can be problematic for long polling or WebSocket communication.
5. Unicorn is a single restaurant with multiple employees, capable of handling one request at a time safely. Puma, on the other hand, is multiple restaurants with many employees, allowing more connections but requiring thread safety in Ruby code.
6. Action Cable is like a host who removes the need for customers to stand at the table. The host places a bell at each table, and when a bell rings, the host quickly attends to that table. This event loop allows Action Cable to manage many connections efficiently, even on top of Unicorn. However, heavy queries or sleeps can still cause issues, so it's best to offload those to background jobs.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.