Ruby on Rails 8 introduces several improvements that make development easier, more secure, and more maintainable. In this guide, we’ll walk through setting up a new Rails 8 application while noting the significant configurations and features that come out of the box.
Rails 8 provides new shortcuts and syntax improvements for database migrations:
NOT NULL Constraints with ! Shortcut
You can impose NOT NULL constraints directly from the command line using !:
# Example for not null constraints:
โ rails generate model User name:string!
Type Modifiers in Migrations
Rails 8 allows passing commonly used type modifiers directly via the command line. These modifiers are enclosed in curly braces {} after the field type.
# Example for model generation:
โ rails generate model Product name:string description:text
# Example for passing modifiers:
โ rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
Generating a Scaffold for the Product Model
Let’s generate a complete scaffold for our Product model:
The rails g resource command is a powerful way to generate models, controllers, migrations, and routes all in one go. This is particularly useful when setting up RESTful resources in a Rails application.
Basic Syntax
โ rails g resource product
This command creates the necessary files for a new resource, including:
A model (app/models/product.rb)
A migration file (db/migrate/)
A controller (app/controllers/product_controller.rb)
Routes in config/routes.rb
A test file (test/controllers/product_controller_test.rb or spec/)
Example Usage
To generate a Post resource with attributes:
โ rails g resource Product title:string! description:text brand:references
This will:
Create a Product model with title and description attributes.
Add a brand_id foreign key as a reference.
Apply a NOT NULL constraint on title (! shortcut).
Generate a corresponding migration file.
Set up routes automatically (resources :products).
Running the Migration
After generating a resource, apply the migration to update the database:
โ rails db:migrate
Difference Between resource and scaffold
Rails provides both rails g resource and rails g scaffold, but they serve different purposes:
Feature
rails g resource
rails g scaffold
Generates a Model
โ
โ
Generates a Migration
โ
โ
Generates a Controller
โ (empty actions)
โ (full CRUD actions)
Generates Views (HTML/ERB)
โ
โ (index, show, new, edit, etc.)
Generates Routes
โ
โ
Generates Helper Files
โ
โ
Generates Tests
โ
โ
rails g resource is minimalโit generates only essential files without view templates. It’s useful when you want more control over how your views and controller actions are built.
rails g scaffold is more opinionated and generates full CRUD functionality with prebuilt forms and views, making it ideal for rapid prototyping.
If you need full CRUD functionality quickly, use scaffold. If you prefer a leaner setup with manual control over implementation, use resource.
Conclusion
Rails 8 significantly enhances the development experience with built-in security tools, CI/CD workflows, streamlined deployment via Kamal, and modern front-end support with Turbo & Stimulus. It also improves caching, background jobs, and real-time features with Solid tools.
These improvements make Rails 8 a robust framework for modern web applications, reducing the need for additional dependencies while keeping development efficient and secure.
Active Record (AR) is the heart of Ruby on Rails when it comes to database interactions. Writing efficient and readable queries is crucial for application performance and maintainability. This guide will help you master Active Record queries with real-world examples and best practices.
Setting Up a Sample Database
To demonstrate complex Active Record queries, letโs create a Rails app with a sample database structure containing multiple tables.
Generate Models & Migrations
rails new MyApp --database=postgresql
cd MyApp
rails g model User name:string email:string
rails g model Post title:string body:text user:references
rails g model Comment body:text user:references post:references
rails g model Category name:string
rails g model PostCategory post:references category:references
rails g model Like user:references comment:references
rails db:migrate
Database Schema Overview
users: Stores user information.
posts: Stores blog posts written by users.
comments: Stores comments on posts, linked to users and posts.
categories: Stores post categories.
post_categories: Join table for posts and categories.
likes: Stores likes on comments by users.
Basic Active Record Queries
1. Fetching All Records
User.all # Returns all users (Avoid using it directly on large datasets as it loads everything into memory)
โ ๏ธ User.all can lead to performance issues if the table contains a large number of records. Instead, prefer pagination (User.limit(100).offset(0)) or batch processing (User.find_each).
2. Finding a Specific Record
User.find(1) # Finds a user by ID
User.find_by(email: 'john@example.com') # Finds by attribute
3. Filtering with where vs having
Post.where(user_id: 2) # Fetch all posts by user with ID 2
Difference between where and having:
where is used for filtering records before grouping.
having is used for filtering after group operations.
Example:
Post.group(:user_id).having('COUNT(id) > ?', 5) # Users with more than 5 posts
4. Ordering Results
User.order(:name) # Order users alphabetically
Post.order(created_at: :desc) # Order posts by newest first
5. Limiting Results
Post.limit(5) # Get the first 5 posts
6. Selecting Specific Columns
User.select(:id, :name) # Only fetch ID and name
7. Fetching Users with a Specific Email Domain
User.where("email LIKE ?", "%@gmail.com")
8. Fetching the Most Recent Posts
Post.order(created_at: :desc).limit(5)
9. Using pluck for Efficient Data Retrieval
User.pluck(:email) # Fetch only emails as an array
10. Checking if a Record Exists Efficiently
User.exists?(email: 'john@example.com')
11. Including Associations (eager loading to avoid N+1 queries)
13. Fetching Users, Their Posts, and the Count of Comments on Each Post
User.joins(posts: :comments)
.group('users.id', 'posts.id')
.select('users.id, users.name, posts.id AS post_id, COUNT(comments.id) AS comment_count')
.order('comment_count DESC')
Importance of inverse_of in Model Associations
What is inverse_of?
The inverse_of option in Active Record associations helps Rails correctly link objects in memory, avoiding unnecessary database queries and ensuring bidirectional association consistency.
Example Usage
class User < ApplicationRecord
has_many :posts, inverse_of: :user
end
class Post < ApplicationRecord
belongs_to :user, inverse_of: :posts
end
Why Use inverse_of?
Performance Optimization: Prevents extra queries by using already loaded objects.
Ensures Data Consistency: Updates associations without additional database fetches.
Enables Nested Attributes: Helps when using accepts_nested_attributes_for.
Example:
user = User.new(name: 'Alice')
post = user.posts.build(title: 'First Post')
post.user == user # True without needing an additional query
Best Practices to use in Rails Projects
1. Using Scopes for Readability
class Post < ApplicationRecord
scope :recent, -> { order(created_at: :desc) }
end
Post.recent.limit(10) # Fetch recent posts
2. Using find_each for Large Datasets
User.find_each(batch_size: 100) do |user|
puts user.email
end
3. Avoiding SELECT * for Performance
User.select(:id, :name).load
4. Avoiding N+1 Queries with includes
Post.includes(:comments).each do |post|
puts post.comments.count
end
Conclusion
Mastering Active Record queries is essential for writing performant and maintainable Rails applications. By using joins, scopes, batch processing, and eager loading, you can write clean and efficient queries that scale well.
Do you have any favorite Active Record query tricks? Share them in the comments!
Ruby is known for its elegant and expressive syntax, making it one of the most enjoyable programming languages to work with. In this blog post, we will explore some interesting aspects of Ruby, including syntax sugar, operator methods, useful array operations, and handy built-in methods.
Ruby Syntax Sugar
Ruby provides several shorthand notations that enhance code readability and reduce verbosity. Let’s explore some useful syntax sugar techniques.
Shorthand for Array and Symbol Arrays
Instead of manually writing arrays of strings or symbols, Ruby provides %w and %i shortcuts.
words = %w[one two three] # => ["one", "two", "three"]
symbols = %i[one two three] # => [:one, :two, :three]
Many mathematical and array operations in Ruby are actually method calls, thanks to Ruby’s message-passing model.
puts 1.+(2) # => 3 (Same as 1 + 2)
Array Indexing and Append Operations
words = %w[zero one two three four]
puts words.[](2) # => "two" (Equivalent to words[2])
words.<<('five') # => ["zero", "one", "two", "three", "four", "five"] (Equivalent to words << "five")
Avoiding Dot Notation with Operators
# Bad practice
num = 10
puts num.+(5) # Avoid this syntax
# Good practice
puts num + 5 # Preferred
Using a linter like rubocop can help enforce best practices in Ruby code.
none? Method in Ruby Arrays
The none? method checks if none of the elements in an array satisfy a given condition.
numbers = [1, 2, 3, 4, 5]
puts numbers.none? { |n| n > 10 } # => true (None are greater than 10)
puts numbers.none?(&:odd?) # => false (Some numbers are odd)
This method is useful for quickly asserting that an array does not contain specific values.
Exponent Operator (**) and XOR Operator (^)
Exponentiation
Ruby uses ** for exponentiation instead of ^ (which performs a bitwise XOR operation).
puts 2 ** 3 # => 8 (2 raised to the power of 3)
puts 10 ** 0.5 # => 3.162277660168379 (Square root of 10)
XOR Operator
In Ruby, ^ is used for bitwise XOR operations, which differ from exponentiation.
This is particularly useful for cleaning up user input or text from external sources.
Conclusion
Ruby’s syntax sugar, operator methods, and built-in methods make code more readable, expressive, and powerful. By leveraging these features effectively, you can write clean, efficient, and maintainable Ruby code.
Ruby on Rails is known for its developer-friendly syntax and expressive code structure. One of the key reasons behind this elegance is its use of Domain-Specific Languages (DSLs). DSLs make Rails configurations, routes, and testing more intuitive by allowing developers to write code that reads like natural language.
In this blog post, we’ll explore what DSLs are, how Rails implements them, and why they make development in Rails both powerful and enjoyable.
What is a DSL?
A Domain-Specific Language (DSL) is a specialized language designed to solve problems in a specific domain. Unlike general-purpose languages (like Ruby or Java), a DSL provides a more concise and readable syntax for a particular task.
Two types of DSLs exist:
Internal DSLs: Written using an existing programming languageโs syntax (e.g., Rails DSLs in Ruby).
External DSLs: Separate from the host language and require a custom parser (e.g., SQL, Regular Expressions).
Rails uses Internal DSLs to simplify web development. Letโs explore some core DSLs in Rails and how they work under the hood.
1. Routes in Rails: A Classic Example of DSL
In config/routes.rb, Rails provides a DSL to define application routes in a clear and structured way.
Example:
Rails.application.routes.draw do
resources :users do
resources :posts
end
get '/about', to: 'pages#about'
root 'home#index'
end
How Does This Work?
resources :users automatically generates RESTful routes for UsersController.
get '/about', to: 'pages#about' maps a GET request to the about action in PagesController.
root 'home#index' sets the default landing page.
Why Use a DSL for Routes?
Concise & Readable: Avoids manually defining each route.
Expressive Syntax: Reads like a structured list of instructions.
Rails extends DSL capabilities with ActiveSupport::Concern, which allows modular mixins in models and controllers.
Example:
module Trackable
extend ActiveSupport::Concern
included do
before_save :track_changes
end
private
def track_changes
puts "Tracking changes!"
end
end
class User < ApplicationRecord
include Trackable
end
How This Works:
included do ... end executes code when the module is included in a class.
before_save :track_changes hooks into the Rails lifecycle to run before saving a record.
Why a DSL for Mixins?
Encapsulation: Keeps related logic together.
Reusability: Can be included in multiple models.
Cleaner Code: Removes redundant callbacks in models.
Conclusion: Why Rails Embraces DSLs
DSLs in Rails make the framework expressive, flexible, and developer-friendly. They provide:
By leveraging DSLs, Rails makes web development intuitive, allowing developers to focus on building great applications rather than writing repetitive code.
So next time you’re defining routes, configuring settings, or writing tests in Railsโremember, you’re using DSLs that make your life easier!
Rails 8.x has arrived, bringing exciting new features and enhancements to improve productivity, performance, and ease of development. From built-in authentication to real-time WebSocket updates, this latest version of Rails continues its commitment to being a powerful and developer-friendly framework.
Let’s dive into some of the most significant features and improvements introduced in Rails 8.
Rails 8 Features & Enhancements
1. Modern JavaScript with Importmaps & Hotwire
Rails 8 eliminates the need for Webpack and Node.js, allowing developers to manage JavaScript dependencies more efficiently. Importmaps simplify dependency management by fetching JavaScript packages directly and caching them locally, removing runtime dependencies.
Key Benefits:
Faster page loads and reduced complexity
No need for Node.js or Webpack
Dependencies are cached locally and loaded efficiently
Example: Pinning a Package
bin/importmap pin local-time
This command fetches the package from npm and stores it locally for future use.
Hotwire Integration
Hotwire enables dynamic page updates without requiring heavy JavaScript frameworks. Rails 8 fully integrates Turbo and Stimulus, making frontend interactivity more seamless.
Importing Dependencies in application.js:
import "trix";
With this setup, developers can create reactive UI elements with minimal JavaScript.
2. Real-Time WebSockets with Action Cable & Turbo Streams
Rails 8 enhances real-time functionality with Action Cable and Turbo Streams, allowing WebSocket-based updates across multiple pages without additional JavaScript libraries.
Setting Up Turbo Streams in Views:
<%= turbo_stream_from @object %>
This creates a WebSocket channel tied to the object.
Any changes to the object will be instantly reflected across all connected clients.
Why This Matters:
No need for third-party WebSocket npm packages
Real-time updates are built into Rails
Simplifies building interactive applications
3. Rich Text with ActionText
Rails 8 continues to support ActionText, making it easy to handle rich text content within models and views.
Model Level Implementation:
has_rich_text :body
This enables rich text storage and formatting for the body attribute of a model.
View Implementation:
<%= form.rich_text_area :body %>
This adds a full-featured WYSIWYG text editor to the form, allowing users to create and edit rich text content seamlessly.
Displaying Updated Timestamps:
<%= time_tag post.updated_at %>
This helper formats timestamps cleanly, improving date and time representation in views.
4. Deployment with Kamal โ Simpler & Faster
Rails 8 introduces Kamal, a modern deployment tool that simplifies remote deployment by leveraging Docker containers.
Deployment Steps:
Setup Remote Serverkamal setup
Installs Docker (if missing) and configures the server.
Deploy the Applicationkamal deploy
Builds and ships a Docker container using Railsโ default Dockerfile.
File Uploads with Active Storage
By default, Kamal stores uploaded files in Docker volumes, but this can be customized based on specific deployment needs.
5. Built-in Authentication โ No Devise Needed
Rails 8 introduces native authentication, reducing reliance on third-party gems like Devise. This built-in system manages password encryption, user sessions, and password resets while keeping signup flows flexible.
Ensure manifest and service-worker routes are enabled.
Verify PWA files: pwa/manifest.json.erb and pwa/service-worker.js.
Deploy and restart the application to see the Install button in the browser.
Final Thoughts
Rails 8 is packed with developer-friendly features that improve security, real-time updates, and deployment workflows. With Hotwire, Kamal, and native authentication, itโs clear that Rails is evolving to reduce dependencies while enhancing performance.
Are you excited about Rails 8? Let me know your thoughts and experiences in the comments below!
Ruby on Rails is a powerful framework for building web applications. If you’re setting up your development environment on macOS in 2025, this guide will walk you through installing Ruby 3.4, Rails 8, and a best IDE for development.
1. Installing Ruby and Rails
“While macOS comes with Ruby pre-installed, it’s often outdated and can’t be upgraded easily. Using a version manager like Mise allows you to install the latest Ruby version, switch between versions, and upgrade as needed.” – Rails guides
Install Dependencies
Run the following command to install essential dependencies (takes time):
zsh completions have been installed to: /opt/homebrew/share/zsh/site-functions ==> Summary ๐บ /opt/homebrew/Cellar/rust/1.84.1: 3,566 files, 321.3MB ==> Running brew cleanup rustโฆ ==> openssl@3 A CA file has been bootstrapped using certificates from the system keychain. To add additional certificates, place .pem files in /opt/homebrew/etc/openssl@3/certs
and run /opt/homebrew/opt/openssl@3/bin/c_rehash ==> rust zsh completions have been installed to: /opt/homebrew/share/zsh/site-functions
By following this guide, you’ve successfully set up a robust Ruby on Rails development environment on macOS. With Mise for version management, Rails installed, and VS Code configured with essential extensions, you’re ready to start building Ruby on Rails applications.
When a client request comes into a Rails application, it doesn’t always go directly to the MVC (Model-View-Controller) layer. Instead, it might first pass through middleware, which handles tasks such as authentication, logging, and static asset management.
Rails uses middleware like ActionDispatch::Static to efficiently serve static assets before they even reach the main application.
ActiveRecord: Object-relational mapping (ORM) system for database interactions.
Action Pack: Handles the controller and view layers.
Active Support: A collection of utility classes and standard library extensions.
Action Mailer: A framework for designing email services.
The Role of Browsers in Asset Management
Web browsers cache static assets to improve performance. The caching strategy varies based on asset types:
Images: Rarely change, so they are aggressively cached.
JavaScript and CSS files: Frequently updated, requiring cache-busting mechanisms.
The Era of Sprockets
Historically, Rails used Sprockets as its default asset pipeline. Sprockets provided:
Conversion of CoffeeScript to JavaScript and SCSS to CSS.
Minification and bundling of assets into fewer files.
Digest-based caching to ensure updated assets were fetched when changed.
The Rise of JavaScript & The Shift Towards Webpack
The release of ES6 (2015-2016) was a turning point for JavaScript, fueling the rise of Single Page Applications (SPAs). This marked a shift from traditional asset management:
Sprockets was effective but became complex and difficult to configure for modern JS frameworks.
Projects started including package.json at the root, indicating JavaScript dependency management.
Webpack emerged as the go-to tool for handling JavaScript, offering features like tree-shaking, hot module replacement, and modern JavaScript syntax support.
The Landscape in 2024: A More Simplified Approach
Recent advancements in web technology have drastically simplified asset management:
ES6 Native Support in All Major Browsers
No need for transpilation of modern JavaScript.
CSS Advancements
Features like variables and nesting eliminate the need for preprocessors like SASS.
HTTP/2 and Multiplexing
Enables parallel loading of multiple assets over a single connection, reducing dependency on bundling strategies.
Enter Propshaft: The Modern Asset Pipeline
Propshaft is the new asset management solution introduced in Rails, replacing Sprockets for simpler and faster asset handling. Key benefits include:
Digest-based file stamping for effective cache busting.
Direct and predictable mapping of assets without complex processing.
Better integration with HTTP/2 for efficient asset delivery.
Rails 8 Precompile Uses Propshaft
What is Precompile? A Reminder
Precompilation hashes all file names and places them in the public/ folder, making them accessible to the public.
Propshaft improves upon this by creating a manifest file that maps the original filename as a key and the hashed filename as a value. This significantly enhances the developer experience in Rails.
Propshaft ultimately moves asset management in Rails to the next level, making it more efficient and streamlined.
The Future of Asset Management in Rails
With advancements like native ES6 support and CSS improvements, Rails continues evolving to embrace simpler, more efficient asset management strategies. Propshaft, combined with modern browser capabilities, makes asset handling seamless and more performance-oriented.
As the web progresses, we can expect further simplifications in asset pipelines, making Rails applications faster and easier to maintain.
Stay tuned for more innovations in the Rails ecosystem!
How does Puma handle multiple HTTP requests? How do threads work and what happens when multiple requests access the database simultaneously?
To understand this properly, we need to understand four concepts:
Processes and threads.
I/O-bound requests.
Database connections and connection pools.
Database locking and concurrent queries.
Let’s start from the beginning.
1. Why Did Rails Move from WEBrick to Puma?
Historically, WEBrick was commonly used as the default Rails development server.
With Rails 5.0, Rails changed its default development server from WEBrick to Puma.
One important reason was the introduction of Action Cable in Rails 5.
Action Cable introduced WebSocket support for real-time features such as chat, notifications and presence. It needed to operate alongside the Rails application in development.
Puma provided a better fit for this concurrent application-server architecture.
Puma provides:
Multithreading: Handles multiple requests using separate threads.
Better concurrency: Allows requests waiting for I/O to overlap.
Copy-on-write memory optimisation when using application preloading.
Production-oriented server capabilities.
One clarification: WEBrick could also create threads for requests. The change wasn’t simply because WEBrick could only process one request at a time. Puma offered a more suitable combination of thread-based and process-based concurrency.
Also, WEBrick’s removal from Ruby’s standard library in Ruby 3.0 was a separate event, not the original reason Rails moved to Puma.
Q) Does puma developed as a ruby library? Or puma has been written in another language and created in ruby as a gem?
Yes! Puma is a Ruby web server, distributed as a Ruby gem, and primarily written in Ruby.
It is not a web server written in another language with a Ruby wrapper.
You install it directly into a Rails application:
# Gemfile
gem "puma"
And start it using:
bundle exec puma
Puma runs inside the Ruby runtime (MRI/CRuby, JRuby, etc.). It uses Ruby’s threading and process capabilities to handle concurrent HTTP requests.
There is one interesting implementation detail: Puma is primarily Ruby, but it also uses native code for performance-critical components.
For example:
Most server logic is implemented in Ruby.
Its HTTP parser is based on Mongrel’s parser, implemented using Ragel and compiled to native C (or Java for certain Ruby implementations).
It uses Ruby’s thread and process APIs to manage concurrent requests.
How does Puma fit into Rails?
HTTP Request
|
v
Puma Server
(Ruby Gem)
|
Rack Interface
|
v
Rails Middleware
|
v
Rails Router
|
v
Controller / Model
|
v
PostgreSQL
Puma is not part of Ruby itself, nor is it part of the Rails framework core. It is an independent Ruby gem that serves Rack applications, including Rails.
Ianswer:
Puma is a Ruby-based, multithreaded and multiprocess HTTP server distributed as a Ruby gem. It implements the Rack interface, allowing it to serve Rails applications. Most of its implementation is Ruby, with native extensions for performance-critical components such as HTTP parsing.
You can also explore its actual source code: Puma GitHub Repository. It’s a useful project to study as a senior Ruby developer.
2. What Is the Difference Between a Process and a Thread?
This is fundamental to understanding Puma.
Process
A process is an independent running instance of an application.
Each process has its own:
Memory space.
Ruby interpreter state.
Global VM Lock (GVL) under MRI Ruby.
Active Record connection pool.
Processes are isolated from one another.
Thread
A thread is an execution unit running inside a process.
Multiple threads within the same process share:
Application memory.
Loaded classes and modules.
Global variables.
Other process-level resources.
However, each thread has its own execution context and can handle a different HTTP request.
Example
Suppose Puma is configured with:
workers 2
threads 3, 3
This means:
2 worker processes.
3 request threads per worker.
Total request-thread capacity:
2 workers ร 3 threads = 6 concurrent requests
Conceptually:
Puma Master Process
|
---------------------
| |
Worker 1 Worker 2
Process Process
| |
----------- -----------
| | | | | |
T1 T2 T3 T1 T2 T3
3 threads 3 threads
Total: 6 request threads
A worker is a process, not a thread.
This distinction is extremely important in ints.
3. What Is the Global VM Lock (GVL)?
When using MRI Ruby (the standard CRuby implementation), Ruby has a Global VM Lock.
The GVL ensures that only one thread within a process executes Ruby code at a time.
For example:
Thread.new do
1_000_000.times { |i| i * 2 }
end
Thread.new do
1_000_000.times { |i| i * 2 }
end
Although two threads exist, they cannot execute Ruby bytecode simultaneously within the same MRI process.
Then why do we need multiple threads?
Because not all application work involves executing Ruby code.
A Rails application spends significant time waiting for external operations:
Database queries.
HTTP requests to third-party APIs.
Redis operations.
File and network I/O.
During blocking I/O, Ruby can release the GVL, allowing another thread to execute.
Important distinction:
Threads improve concurrency by overlapping waiting time.
Multiple processes allow MRI Ruby code to execute in parallel across CPU cores.
Puma supports both.
4. What Are I/O-Bound Requests?
An I/O-bound request spends a significant portion of its execution time waiting for an external operation to complete.
Consider this Rails action:
def show
user = User.find(params[:id])
response = HTTParty.get(
"https://api.example.com/profile"
)
render json: {
user: user,
external_profile: response.parsed_response
}
end
Imagine:
Operation
Time
Ruby processing
10 ms
Database query
50 ms
External API request
500 ms
JSON response processing
10 ms
Total
570 ms
The application spends only 20 ms actively processing Ruby code.
The remaining 550 ms is waiting for external operations.
This is an I/O-bound request.
How do Puma threads help?
Imagine three requests arrive simultaneously.
Without useful concurrency, a single execution path might spend time waiting for each external API response.
With Puma:
Thread 1: Ruby code -> Wait for API -> Resume -> Response
Thread 2: Ruby code -> Wait for API -> Resume -> Response
Thread 3: Ruby code -> Wait for API -> Resume -> Response
While Thread 1 waits for its API response, Thread 2 or Thread 3 can execute.
The server uses waiting time more efficiently.
This improves throughput and reduces unnecessary request queuing.
What about CPU-bound requests?
Consider:
def calculate
result = 0
100_000_000.times do |i|
result += i * 2
end
render json: { result: result }
end
This request spends most of its time executing Ruby code.
Increasing Puma threads does not provide true parallel Ruby execution within one MRI process because of the GVL.
For CPU-heavy Ruby workloads, multiple worker processes are more useful because each process has its own GVL.
5. Does Accessing the Database Lock It for Other Requests?
This is an important question.
No. A database connection or a database query does not automatically lock the entire database.
We need to distinguish three different things:
Database connection.
Database connection pool.
Database locks.
They are not the same.
Database connections
A database connection represents a communication session between your Rails process and PostgreSQL.
Multiple connections can exist simultaneously.
For example:
Rails Thread 1 ---- DB Connection 1 ---- PostgreSQL
Rails Thread 2 ---- DB Connection 2 ---- PostgreSQL
Rails Thread 3 ---- DB Connection 3 ---- PostgreSQL
Each connection can execute its own SQL queries.
PostgreSQL is designed to handle concurrent database sessions.
What happens when two requests access the same table?
The pool: 5 setting means that this Active Record connection pool can provide up to five simultaneous database connections.
It doesn’t mean that only five requests can execute in Rails.
It means that only five threads can hold a connection from this particular pool at the same time.
How does the connection pool work?
Suppose three Puma threads receive requests.
Puma Worker Process
|
|
Active Record
Connection Pool
|
---------------------
| | |
DB Conn 1 DB Conn 2 DB Conn 3
| | |
---------------------
|
PostgreSQL
Here’s what happens:
Thread 1 receives a request.
Thread 1 executes an Active Record query.
Active Record checks out a connection from the pool.
The connection executes SQL against PostgreSQL.
The request completes.
Rails returns the acquired connection to the pool.
The connection becomes available to another thread.
The pool creates connections as needed, up to its configured limit.
What happens if all connections are busy?
Suppose:
pool: 2
But three threads simultaneously need database connections.
Thread 1 -> Connection 1 (Busy)
Thread 2 -> Connection 2 (Busy)
Thread 3 -> Waiting for a connection
Thread 3 waits until one of the connections becomes available.
If it cannot obtain a connection before checkout_timeout expires, Rails raises:
ActiveRecord::ConnectionTimeoutError
This is a common production issue when the connection pool is too small for the application’s database workload.
7. How Do Puma Workers and Active Record Connection Pools Work Together?
This is where everything comes together.
Remember that every Puma worker is a separate process.
Each worker process maintains its own Active Record connection pool.
A connection checked out by a thread in Worker 1 cannot be used by a thread in Worker 2.
What if we configure 5 Puma threads but only 2 DB connections?
workers 1
threads 5, 5
pool: 2
Five requests can be in progress, but only two threads can hold database connections simultaneously.
The remaining threads may wait for an available connection.
This can increase response latency and eventually cause connection timeouts.
What should the connection pool size be?
A useful starting rule is:
Set the connection pool at least as large as the maximum number of concurrent threads that need database connections in that process.
For example:
threads 5, 5
A pool size of five is a sensible starting point.
You may need a larger pool when using additional concurrent database consumers, such as asynchronous Active Record query executors.
You don’t always need one database connection for every Puma thread if only some requests access the database. A smaller pool is possible, but it introduces connection-pool contention.
What about Sidekiq?
Sidekiq is another process that can execute multiple jobs concurrently.
Suppose:
# config/sidekiq.yml
:concurrency: 10
If ten Sidekiq threads can execute database operations simultaneously, its Active Record connection pool should generally support at least ten connections per relevant database pool.
Remember:
Puma has its own database pool per worker process.
Sidekiq has its own database pool per process.
Console sessions and other application processes also consume database connections.
Always calculate total possible database connections across the entire application deployment.
A useful formula is:
Total DB connections =
(Puma workers ร Puma pool size)
+ (Sidekiq processes ร Sidekiq pool size)
+ Other application connections
This total must fit within your database connection capacity, leaving room for administration and other required sessions.
8. How Can We Configure Puma for Better Rails Performance?
Puma configuration mainly involves two important settings:
You can increase the thread count for applications with substantial I/O waiting.
However, don’t blindly increase it.
More threads can increase:
Memory consumption.
GVL contention.
Database connection demand.
External service concurrency.
Rails 7.2 changed its generated Puma thread default from five to three after observing that excessive threading could increase GVL contention and request latency.
B. Configure the number of workers
workers 2
This starts two worker processes.
Each process has its own Ruby execution environment and GVL.
Multiple workers allow MRI Ruby code to execute in parallel on different CPU cores.
However, workers also consume memory and increase the total number of possible database connections.
Don’t blindly set workers equal to the number of available CPUs without considering memory and database capacity.
C. Application preloading
preload_app!
This loads the application before Puma forks its worker processes.
It can reduce memory usage through an operating-system feature called Copy-on-Write (CoW).
When memory pages are shared and neither process modifies them, the operating system can avoid duplicating those pages.
Preloading is useful in clustered deployments, but it has lifecycle implications. In particular, it cannot be combined with Puma’s phased restart feature.
When configuring preloading, follow the connection and background-thread lifecycle requirements of your Puma version and Rails application.
D. What is the best configuration?
There is no universal best configuration.
For a typical I/O-heavy Rails application, start with a modest number of threads and workers, then benchmark.
For example:
workers 2
threads 3, 3
This provides six simultaneous request slots.
Measure:
Request throughput (requests per second).
P95 and P99 response latency.
Worker memory consumption.
CPU utilisation.
Database connection-pool wait time.
Database CPU and query latency.
Increase workers or threads only when measurements show that the current configuration is limiting performance.
9. Putting Everything Together
Let’s consider a real-world example.
A Rails application receives 100 HTTP requests.
Puma is configured with:
workers 2
threads 3, 3
The application can process six requests concurrently across its two worker processes.
The remaining requests wait in the server’s request-handling queue.
Now assume every request needs a database connection.
Each worker has:
pool: 3
Therefore:
Worker 1: 3 concurrent DB connections
Worker 2: 3 concurrent DB connections
Total: 6 possible DB connections
PostgreSQL can execute queries using these independent connections.
If one transaction updates a particular row, another transaction attempting to update the same row may wait for the lock to be released.
Meanwhile, other unrelated queries can continue.
This is how Puma, Active Record and PostgreSQL work together to handle concurrent Rails requests.
10. Common Interview Questions
1. What is the difference between a Puma worker and a thread?
A worker is an independent operating-system process. A thread is an execution unit inside that process. Puma uses both to handle concurrent requests.
2. What are I/O-bound requests?
Requests that spend considerable time waiting for external operations such as database queries, HTTP calls, Redis, or file I/O.
3. Does MRI Ruby support multithreading?
Yes. MRI supports multiple threads, but the GVL prevents multiple threads in the same process from executing Ruby bytecode simultaneously. Threads can still overlap blocking I/O.
4. Why does Puma use multiple processes?
Multiple processes allow Ruby code to execute in parallel across CPU cores despite the MRI GVL. They also provide process isolation.
5. Does every Puma thread need a database connection?
Not necessarily at every moment. However, when multiple threads simultaneously require database connections, each needs its own checked-out connection.
6. What happens when the connection pool is exhausted?
Threads wait for a connection. If one does not become available before the checkout timeout, Rails raises ActiveRecord::ConnectionTimeoutError.
7. Does PostgreSQL lock an entire table when a record is updated?
Not normally. PostgreSQL uses MVCC and row-level locking for conflicting updates. Certain operations, such as some DDL commands, can acquire table-level locks.
8. Why not increase the number of Puma threads to 100?
Too many threads can increase GVL contention, memory usage, database connection requirements and request latency. Thread count must be tuned based on the workload.
9. What is the difference between concurrency and parallelism?
Concurrency means multiple tasks make progress during overlapping periods. Parallelism means multiple tasks execute simultaneously, typically on different CPU cores.
10. How do you troubleshoot Active Record connection-pool exhaustion?
Check the configured pool size, Puma thread count, Sidekiq concurrency, connection checkout wait time, long-running transactions and database connection limits. Increase the pool only after checking total database capacity.
๐ Final Takeaway
Remember these relationships:
Puma workers = independent processes.
Puma threads = concurrent request execution within each process.
MRI GVL = one thread executes Ruby bytecode at a time per process.
I/O-bound operations = threads can make progress while another thread waits.
Active Record connection pool = manages reusable database connections for threads.
Database connection = a communication session, not a database lock.
PostgreSQL MVCC = allows concurrent access to consistent data snapshots.
Software development is not just about writing code; it’s about building high-quality, maintainable, and scalable systems that deliver value to users. To achieve this consistently, teams follow structured approaches known as software development methodologies. These methodologies provide a roadmap for planning, designing, developing, testing, and delivering software.
In this three-part blog series, we’ll explore key methodologies and best practices in software development, using Ruby and Ruby on Rails examples wherever appropriate.
What Are Software Development Methodologies?
Software development methodologies are structured processes or frameworks that guide the planning and execution of software projects. They help teams manage complexity, collaborate effectively, reduce risk, and deliver projects on time.
Common Goals of Any Methodology:
Define clear project scope and goals
Break down work into manageable tasks
Encourage communication among team members
Track progress and measure success
Deliver working software iteratively or incrementally
Why Methodologies Matter
Without a methodology, software projects often suffer from unclear requirements, missed deadlines, buggy releases, or scope creep. A good methodology:
Increases team productivity
Ensures better quality and maintainability
Reduces time-to-market
Improves customer satisfaction
In Ruby and Rails projects, where rapid development is a key feature, following a methodology keeps things under control and makes collaboration more effective.
A Brief Overview of Popular Software Development Methodologies
We’ll explore these in detail in Part 2, but here are the major ones:
1. Waterfall
A linear approach where each phase (Requirements โ Design โ Implementation โ Testing โ Deployment) happens one after another.
2. Agile
An iterative and incremental model that encourages adaptive planning, early delivery, and continuous improvement.
3. Scrum
A popular Agile framework that structures work in sprints and emphasizes team roles, ceremonies, and artifacts.
4. Kanban
A flow-based Agile method that uses visual boards to manage work and improve process efficiency.
5. Extreme Programming (XP)
Focuses on engineering excellence, including practices like pair programming, TDD, and continuous integration. Ruby and Rails communities highly embrace XP.
6. DevOps
Combines software development and IT operations to shorten the development lifecycle and deliver high-quality software continuously.
โจ Ruby On Rails: A Natural Fit for Agile and XP
Ruby and Rails were built with developer happiness and productivity in mind. They naturally complement Agile and XP methodologies.
Example:
Ruby on Rails encourages convention over configuration, which speeds up development.
It supports Test-Driven Development (TDD) out of the box via tools like RSpec and Minitest.
Features like scaffolding align well with the iterative nature of Agile.
Coming Up in Part 2
In the next part of this series, I’ll do a deep dive into each of the above methodologies, with pros, cons, and real-world use cases. I’ll also show examples of how Rails developers apply these in practice.
Order
.where("created_at < ?", last_created_at)
.order(created_at: :desc)
.limit(20)
This is called keyset pagination or cursor pagination.
Scenario 6 โ SELECT *
Query:
SELECT*
FROM users;
Returns:
id
name
email
city
address
bio
avatar
...
Suppose the page only displays:
name
city
Why fetch everything?
Better:
SELECT
name,
city
FROM users;
Rails:
User.select(:name, :city)
Scenario 7 โ COUNT(*)
Suppose:
SELECTCOUNT(*)
FROM orders;
On:
300 million rows
Question:
Can this be slow?
Yes.
Because PostgreSQL must count visible rows.
Unlike some databases, PostgreSQL generally doesn’t maintain an exact row count that’s instantly available for arbitrary COUNT(*).
Scenario 8 โ DISTINCT
Query:
SELECTDISTINCT users.*
FROM users
JOIN orders
ON users.id=orders.user_id;
Question:
Why is DISTINCT needed?
Because JOIN duplicates users.
Could EXISTS express the requirement more directly?
SELECT*
FROM users u
WHEREEXISTS(
SELECT1
FROM orders o
WHERE o.user_id=u.id
);
Sometimes that’s clearer.
Scenario 9 โ Functions in WHERE
Query:
SELECT*
FROM users
WHERE LOWER(email)='john@example.com';
Normal email index?
Not useful.
Solution:
CREATE INDEX idx_lower_email
ON users(LOWER(email));
Expression index.
Scenario 10 โ Too Many Indexes
Suppose:
users
โ
12 indexes
Problem?
Every INSERT must update:
Table
+
12 indexes
Indexes speed reads but slow writes.
Always consider the workload.
Optimization Decision Tree
When a query is slow, ask:
Is PostgreSQL scanning too many rows?
โ
โผ
Yes
โ
โผ
Would an index help?
โ
โผ
Yes
โ
โผ
Do I already have one?
โ
โผ
No
โ
โผ
Create the correct index.
But also ask:
Am I returning unnecessary data?
Am I sorting unnecessarily?
Am I joining unnecessarily?
Am I executing the query too many times?
Real Rails Optimization Example
Suppose this page loads slowly:
@orders = Order
.where(status: "completed")
.order(created_at: :desc)
.limit(20)
Questions:
Is there an index on status?
Is there an index on created_at?
Would a composite index help?
Potential solution:
CREATE INDEX idx_orders_status_created_at
ON orders(status, created_at DESC);
Why?
Because the query filters by status and orders by created_at.
Senior Interview Exercise
Suppose you see:
SELECT*
FROM orders
WHERE user_id =100
ORDERBY created_at DESC
LIMIT20;
Which index would you create?
Many people answer:
(user_id)
(created_at)
A stronger answer is:
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC);
Because it supports both the filter and the ordering in one index.
Common Performance Mistakes
Mistake 1
Adding indexes without measuring.
Mistake 2
Using SELECT * everywhere.
Mistake 3
Ignoring N+1 queries.
Mistake 4
Using huge OFFSET values.
Mistake 5
Creating duplicate indexes.
Mistake 6
Ignoring EXPLAIN ANALYZE.
Senior-Level Mental Model
Every query has a “cost.”
The cost comes from:
Rows read
+
Rows sorted
+
Rows joined
+
Rows transferred
+
Application round trips
The goal of optimisation is to reduce one or more of these.
Practical Exercises
Exercise 1
Create:
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC);
Run:
EXPLAIN ANALYZE
SELECT*
FROM orders
WHERE user_id=1
ORDERBY created_at DESC
LIMIT20;
Observe whether PostgreSQL can avoid an explicit Sort.
Exercise 2
Compare:
SELECT*
FROM users;
with:
SELECT name, city
FROM users;
Think about the amount of data returned.
Exercise 3
Write three versions of:
“Find users with completed orders.”
Using:
JOIN
EXISTS
IN
Then compare their execution plans.
Exercise 4
Find a query that performs a Seq Scan.
Add an appropriate index.
Run EXPLAIN ANALYZE again.
What changed?
Interview Case Study
Imagine you’re in a senior Rails interview.
The interviewer says:
“A customer reports that the Orders page takes 6 seconds to load.”
A strong answer isn’t:
“I’ll add an index.”
A stronger answer is:
Reproduce the issue.
Identify the SQL generated by ActiveRecord.
Run EXPLAIN ANALYZE.
Inspect scan types, joins, and sort operations.
Check existing indexes.
Decide whether the fix belongs in the SQL, indexes, ActiveRecord code, or schema.
Measure again after the change.
That systematic approach demonstrates senior-level thinking.
Homework
Build a small benchmark using your practice schema.
Populate:
100,000 users
500,000 orders
Measure these queries before and after adding indexes:
Find a user by email.
Find recent orders for a user.
Find completed orders.
Find users with no orders.
For each query, record:
Execution plan
Execution time
Scan type
Rows estimated
Rows returned
Explain why PostgreSQL chose each plan.
What’s Next?
At this point, you’re already covering topics that many experienced Rails developers never study in depth.
For Day 8, I recommend Window Functions:
ROW_NUMBER()
RANK()
DENSE_RANK()
LAG()
LEAD()
Running totals
Moving averages
Top N per group
Window functions are common in reporting, analytics, and senior backend interviews because they solve problems that are difficult or inefficient with plain GROUP BY. Understanding them will significantly broaden your SQL toolkit.