Let’s look into some of the features of sql data indexing. This will be super helpful while developing our Rails 8 Application.
๐ Part 1: What is a Covering Index?
Normally when you query:
SELECT * FROM users WHERE username = 'bob';
Database searches username index (secondary).
Finds a pointer (TID or PK).
Then fetches full row from table (heap or clustered B-tree).
Problem:
Heap fetch = extra disk read.
Clustered B-tree fetch = extra traversal.
๐ Covering Index idea:
โ If the index already contains all the columns you need, โ Then the database does not need to fetch the full row!
It can answer the query purely by scanning the index! โก
Boom โ one disk read, no extra hop!
โ๏ธ Example in PostgreSQL:
Suppose your query is:
SELECT username FROM users WHERE username = 'bob';
You only need username.
But by default, PostgreSQL indexes only store the index column (here, username) + TID.
โ So in this case โ already covering!
No heap fetch needed!
โ๏ธ Example in MySQL InnoDB:
Suppose your query is:
SELECT username FROM users WHERE username = 'bob';
Secondary index (username) contains:
username (indexed column)
user_id (because secondary indexes in InnoDB always store PK)
โฆ๏ธ So again, already covering! No need to jump to the clustered index!
๐ฏ Key point:
If your query only asks for columns already inside the index, then only the index is touched โ no second lookup โ super fast!
๐ Part 2: Real SQL Examples
โจ PostgreSQL
Create a covering index for common query:
CREATE INDEX idx_users_username_email ON users (username, email);
Now if you run:
SELECT email FROM users WHERE username = 'bob';
Postgres can:
Search index on username
Already have email in index
โ No heap fetch!
(And Postgres is smart: it checks index-only scan automatically.)
โจ MySQL InnoDB
Create a covering index:
CREATE INDEX idx_users_username_email ON users (username, email);
โ Now query:
SELECT email FROM users WHERE username = 'bob';
Same behavior:
Only secondary index read.
No need to touch primary clustered B-tree.
๐ Part 3: Tips to design smart Covering Indexes
โ If your query uses WHERE on col1 and SELECTcol2, โ Best to create index: (col1, col2).
โ Keep indexes small โ don’t add 10 columns unless needed. โ Avoid huge TEXT or BLOB columns in covering indexes โ they make indexes heavy.
โ Composite indexes are powerful:
CREATE INDEX idx_users_username_email ON users (username, email);
โ Can be used for:
WHERE username = ?
WHERE username = ? AND email = ?
etc.
โ Monitor index usage:
PostgreSQL: EXPLAIN ANALYZE
MySQL: EXPLAIN
โ Always check if Index Only Scan or Using Index appears in EXPLAIN plan!
๐ Quick Summary Table
Database
Normal Query
With Covering Index
PostgreSQL
B-tree โ Heap fetch (unless TID optimization)
B-tree scan only
MySQL InnoDB
Secondary B-tree โ Primary B-tree
Secondary B-tree only
Result
2 steps
1 step
Speed
Slower
Faster
๐ Great! โ Now We Know:
๐ง How heap fetch works! ๐ง How block lookup is O(1)! ๐ง How covering indexes skip heap fetch! ๐ง How to create super fast indexes for PostgreSQL and MySQL!
๐ฆพ Advanced Indexing Tricks (Real Production Tips)
Now it’s time to look into super heavy functionalities that Postgres supports for making our sql data search/fetch super fast and efficient.
1. ๐ฏ Partial Indexes (PostgreSQL ONLY)
โ Instead of indexing the whole table, โ You can index only the rows you care about!
Example:
Suppose 95% of users have status = 'inactive', but you only search active users:
SELECT * FROM users WHERE status = 'active' AND email = 'bob@example.com';
๐ Instead of indexing the whole table:
CREATE INDEX idx_active_users_email ON users (email) WHERE status = 'active';
โฆ๏ธ PostgreSQL will only store rows with status = 'active' in this index!
Advantages:
Smaller index = Faster scans
Less space on disk
Faster index maintenance (less updates/inserts)
Important:
MySQL (InnoDB) does NOT support partial indexes ๐ โ only PostgreSQL has this superpower.
2. ๐ฏ INCLUDE Indexes (PostgreSQL 11+)
โ Normally, a composite index uses all columns for sorting/searching. โ With INCLUDE, extra columns are just stored in index, not used for ordering.
Example:
CREATE INDEX idx_username_include_email ON users (username) INCLUDE (email);
Meaning:
username is indexed and ordered.
email is only stored alongside.
Now query:
SELECT email FROM users WHERE username = 'bob';
โ Index-only scan โ no heap fetch.
Advantages:
Smaller & faster than normal composite indexes.
Helps to create very efficient covering indexes.
Important:
MySQL 8.0 added something similar with INVISIBLE columns but it’s still different.
3. ๐ฏ Composite Index Optimization
โ Always order columns inside index smartly based on query pattern.
Golden Rules:
โ๏ธ Equality columns first (WHERE col = ?) โ๏ธ Range columns second (WHERE col BETWEEN ?) โ๏ธ SELECT columns last (for covering)
Example:
If query is:
SELECT email FROM users WHERE status = 'active' AND created_at > '2024-01-01';
Best index:
CREATE INDEX idx_users_status_created_at ON users (status, created_at) INCLUDE (email);
โฆ๏ธ status first (equality match) โฆ๏ธ created_at second (range) โฆ๏ธ email included (covering)
Bad Index: (wrong order)
CREATE INDEX idx_created_at_status ON users (created_at, status);
โ Will not be efficient!
4. ๐ฏ BRIN Indexes (PostgreSQL ONLY, super special!)
โ When your table is very huge (millions/billions of rows), โ And rows are naturally ordered (like timestamp, id increasing), โ You can create a BRIN (Block Range Index).
Example:
CREATE INDEX idx_users_created_at_brin ON users USING BRIN (created_at);
โฆ๏ธ BRIN stores summaries of large ranges of pages (e.g., min/max timestamp per 128 pages).
โฆ๏ธ Ultra small index size.
โฆ๏ธ Very fast for large range queries like:
SELECT * FROM users WHERE created_at BETWEEN '2024-01-01' AND '2024-04-01';
Important:
BRIN โ B-tree
BRIN is approximate, B-tree is precise.
Only useful if data is naturally correlated with physical storage order.
MySQL?
MySQL does not have BRIN natively. PostgreSQL has a big advantage here.
5. ๐ฏ Hash Indexes (special case)
โ If your query is always exact equality (not range), โ You can use hash indexes.
Example:
CREATE INDEX idx_users_username_hash ON users USING HASH (username);
Useful for:
Simple WHERE username = 'bob'
Never ranges (BETWEEN, LIKE, etc.)
โ ๏ธ Warning:
Hash indexes used to be “lossy” before Postgres 10.
Now they are safe, but usually B-tree is still better unless you have very heavy point lookups.
๐ PRO-TIP: Which Index Type to Use?
Use case
Index type
Search small ranges or equality
B-tree
Search on huge tables with natural order (timestamps, IDs)
BRIN
Only exact match, super heavy lookup
Hash
Search only small part of table (active users, special conditions)
Partial index
Need to skip heap fetch
INCLUDE / Covering Index
๐บ๏ธ Quick Visual Mindmap:
Your Query
โ
โโโ Need Equality + Range? โ B-tree
โ
โโโ Need Huge Time Range Query? โ BRIN
โ
โโโ Exact equality only? โ Hash
โ
โโโ Want Smaller Index (filtered)? โ Partial Index
โ
โโโ Want to avoid Heap Fetch? โ INCLUDE columns (Postgres) or Covering Index
๐ Now we Know:
๐ง Partial Indexes ๐ง INCLUDE Indexes ๐ง Composite Index order tricks ๐ง BRIN Indexes ๐ง Hash Indexes ๐ง How to choose best Index
MySQL InnoDB: Directly find the row inside the PK B-tree (no extra lookup).
โ MySQL is a little faster here because it needs only 1 step!
2. SELECT username FROM users WHERE user_id = 102; (Only 1 Column)
PostgreSQL: Might do an Index Only Scan if all needed data is in the index (very fast).
MySQL: Clustered index contains all columns already, no special optimization needed.
โ Both can be very fast, but PostgreSQL shines if the index is “covering” (i.e., contains all needed columns). Because index table has less size than clustered index of mysql.
3. SELECT * FROM users WHERE username = 'Bob'; (Secondary Index Search)
PostgreSQL: Secondary index on username โ row pointer โ fetch table row.
MySQL: Secondary index on username โ get primary key โ clustered index lookup โ fetch data.
โ Both are 2 steps, but MySQL needs 2 different B-trees: secondary โ primary clustered.
Consider the below situation:
SELECT username FROM users WHERE user_id = 102;
user_id is the Primary Key.
You only want username, not full row.
Now:
๐ต PostgreSQL Behavior
๐ In PostgreSQL, by default:
It uses the primary key btree to find the row pointer.
Then fetches the full row from the table (heap fetch).
๐ But PostgreSQL has an optimization called Index-Only Scan.
If all requested columns are already present in the index,
And if the table visibility map says the row is still valid (no deleted/updated row needing visibility check),
Then Postgres does not fetch the heap.
๐ So in this case:
If the primary key index also stores username internally (or if an extra index is created covering username), Postgres can satisfy the query just from the index.
โ Result: No table lookup needed โ Very fast (almost as fast as InnoDB clustered lookup).
๐ข Postgres primary key indexes usually don’t store extra columns, unless you specifically create an index that includes them (INCLUDE (username) syntax in modern Postgres 11+).
๐ MySQL InnoDB Behavior
In InnoDB: Since the primary key B-tree already holds all columns (user_id, username, email), It directly finds the row from the clustered index.
So when you query by PK, even if you only need one column, it has everything inside the same page/block.
โ One fast lookup.
๐ฅ Why sometimes Postgres can still be faster?
If PostgreSQL uses Index-Only Scan, and the page is already cached, and no extra visibility check is needed, Then Postgres may avoid touching the table at all and only scan the tiny index pages.
In this case, for very narrow queries (e.g., only 1 small field), Postgres can outperform even MySQL clustered fetch.
๐ก Because fetching from a small index page (~8KB) is faster than reading bigger table pages.
๐ฏ Conclusion:
โ MySQL clustered index is always fast for PK lookups. โ PostgreSQL can be even faster for small/narrow queries if Index-Only Scan is triggered.
๐ Quick Tip:
In PostgreSQL, you can force an index to include extra columns by using: CREATE INDEX idx_user_id_username ON users(user_id) INCLUDE (username); Then index-only scans become more common and predictable! ๐
Isn’t PostgreSQL also doing 2 B-tree scans? One for secondary index and one for table (row_id)?
When you query with a secondary index, like:
SELECT * FROM users WHERE username = 'Bob';
In MySQL InnoDB, I said:
Find in secondary index (username โ user_id)
Then go to primary clustered index (user_id โ full row)
Let’s look at PostgreSQL first:
โฆ๏ธ Step 1: Search Secondary Index B-tree on username.
It finds the matching TID (tuple ID) or row pointer.
TID is a pair (block_number, row_offset).
Not a B-tree! Just a physical pointer.
โฆ๏ธ Step 2: Use the TID to directly jump into the heap (the table).
The heap (table) is not a B-tree โ itโs just a collection of unordered pages (blocks of rows).
PostgreSQL goes directly to the block and offset โ like jumping straight into a file.
๐ Important:
Secondary index โ TID โ heap fetch.
No second B-tree traversal for the table!
๐ Meanwhile in MySQL InnoDB:
โฆ๏ธ Step 1: Search Secondary Index B-tree on username.
It finds the Primary Key value (user_id).
โฆ๏ธ Step 2: Now, search the Primary Key Clustered B-tree to find the full row.
Need another B-tree traversal based on user_id.
๐ Important:
Secondary index โ Primary Key B-tree โ data fetch.
Two full B-tree traversals!
Real-world Summary:
โฆ๏ธ PostgreSQL
Secondary index gives a direct shortcut to the heap.
One B-tree scan (secondary) โ Direct heap fetch.
โฆ๏ธ MySQL
Secondary index gives PK.
Then another B-tree scan (primary clustered) to find full row.
โ PostgreSQL does not scan a second B-tree when fetching from the table โ just a direct page lookup using TID.
โ MySQL does scan a second B-tree (primary clustered index) when fetching full row after secondary lookup.
Is heap fetch a searching technique? Why is it faster than B-tree?
๐ Let’s start from the basics:
When PostgreSQL finds a match in a secondary index, what it gets is a TID.
โฆ๏ธ A TID (Tuple ID) is a physical address made of:
Block Number (page number)
Offset Number (row slot inside the page)
Example:
TID = (block_number = 1583, offset = 7)
๐ต How PostgreSQL uses TID?
It directly calculates the location of the block (disk page) using block_number.
It reads that block (if not already in memory).
Inside that block, it finds the row at offset 7.
โฆ๏ธ No search, no btree, no extra traversal โ just:
Find the page (via simple number addressing)
Find the row slot
๐ Visual Example
Secondary index (username โ TID):
username
TID
Alice
(1583, 7)
Bob
(1592, 3)
Carol
(1601, 12)
โฆ๏ธ When you search for “Bob”:
Find (1592, 3) from secondary index B-tree.
Jump directly to Block 1592, Offset 3.
Done โ !
Answer:
Heap fetch is NOT a search.
It’s a direct address lookup (fixed number).
Heap = unordered collection of pages.
Pages = fixed-size blocks (usually 8 KB each).
TID gives an exact GPS location inside heap โ no searching required.
That’s why heap fetch is faster than another B-tree search:
No binary search, no B-tree traversal needed.
Only a simple disk/memory read + row offset jump.
๐ฟ B-tree vs ๐ Heap Fetch
Action
B-tree
Heap Fetch
What it does
Binary search inside sorted tree nodes
Direct jump to block and slot
Steps needed
Traverse nodes (root โ internal โ leaf)
Directly read page and slot
Time complexity
O(log n)
O(1)
Speed
Slower (needs comparisons)
Very fast (direct)
๐ฏ Final and short answer:
โฆ๏ธ In PostgreSQL, after finding the TID in the secondary index, the heap fetch is a direct, constant-time (O(1)) access โ no B-tree needed! โฆ๏ธ This is faster than scanning another B-tree like in MySQL InnoDB.
๐งฉ Our exact question:
When we say:
Jump directly to Block 1592, Offset 3.
We are thinking:
There are thousands of blocks.
How can we directly jump to block 1592?
Shouldn’t that be O(n) (linear time)?
Shouldn’t there be some traversal?
๐ต Here’s the real truth:
No traversal needed.
No O(n) work.
Accessing Block 1592 is O(1) โ constant time.
๐ Why?
Because of how files, pages, and memory work inside a database.
When PostgreSQL stores a table (the “heap”), it saves it in a file on disk. The file is just a long array of fixed-size pages.
Each page = 8KB (default in Postgres).
Each block = 1 page = fixed 8KB chunk.
Block 0 is the first 8KB.
Block 1 is next 8KB.
Block 2 is next 8KB.
…
Block 1592 = (1592 ร 8 KB) offset from the beginning.
โ So block 1592 is simply located at 1592 ร 8192 bytes offset from the start of the file.
โ Operating systems (and PostgreSQL’s Buffer Manager) know exactly how to seek to that byte position without reading everything before it.
Letโs walk through a real-world example using a schema we are already working on: a shopping app that sells clothing for women, men, kids, and infants.
Weโll look at how candidate keys apply to real tables like Users, Products, Orders, etc.
Here, a combination of order_id and product_id uniquely identifies a row โ i.e., what product was ordered in which order โ making it a composite candidate key, and weโve selected it as the primary key.
๐ Summary of Candidate Keys by Table
Table
Candidate Keys
Primary Key Used
Users
user_id, email, username
user_id
Products
product_id, sku
product_id
Orders
order_id, order_number
order_id
OrderItems
(order_id, product_id)
(order_id, product_id)
Let’s explore how to implement candidate keys in both SQL and Rails (Active Record). Since we are working on a shopping app in Rails 8, I’ll show how to enforce uniqueness and data integrity in both layers:
๐น 1. Candidate Keys in SQL (PostgreSQL Example)
Letโs take the Users table with multiple candidate keys (email, username, and user_id).
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
username VARCHAR(100) NOT NULL UNIQUE,
phone_number VARCHAR(20)
);
user_id: chosen as the primary key
email and username: candidate keys, enforced via UNIQUE constraints
If you examine the above table, there will be repetitive product items if consider for a size of an item there comes so many colours. We need to create different product rows for each size different colours.
So Let’s split the table into two.
1. Product Table
class CreateProducts < ActiveRecord::Migration[8.0]
def change
def change
create_table :products do |t|
t.string :name
t.text :description
t.string :category # women, men, kids, infants
t.decimal :rating, precision: 2, scale: 1, default: 0.0
t.timestamps
end
add_index :products, :category
end
end
end
2. Product Variant Table
class CreateProductVariants < ActiveRecord::Migration[8.0]
def change
create_table :product_variants do |t|
t.references :product, null: false, foreign_key: true
t.string :sku, null: false
t.decimal :price, precision: 10, scale: 2
t.string :size
t.string :color
t.integer :stock_quantity, default: 0
t.jsonb :specs, default: {}, null: false
t.timestamps
end
# GIN index for fast JSONB attribute searching
add_index :product_variants, :specs, using: :gin
add_index :product_variants, [ :product_id, :size, :color ], unique: true
add_index :product_variants, :sku, unique: true
end
end
Data normalization is a core concept in database design that helps organize data efficiently, eliminate redundancy, and ensure data integrity.
๐ What Is Data Normalization?
Normalization is the process of structuring a relational database in a way that:
Reduces data redundancy (no repeated data)
Prevents anomalies in insert, update, or delete operations
Improves data integrity
It breaks down large, complex tables into smaller, related tables and defines relationships using foreign keys.
๐ง Why Normalize?
Problem Without Normalization
How Normalization Helps
Duplicate data everywhere
Moves repeated data into separate tables
Inconsistent values
Enforces rules and relationships
Hard to update data
Isolates each concept so it’s updated once
Wasted storage
Reduces data repetition
๐ Normal Forms (NF)
Each Normal Form (NF) represents a level of database normalization. The most common are:
ite key (student_id, course_id), and student_name depends only on student_id, it should go into a separate table.
Think of normalization as organizing SQL tables to reduce duplication, inconsistency, and update problems.
1NF – First Normal Form
Rule: Each column should contain atomic/single values. No lists or repeating groups.
โ Not 1NF
id
name
phone_numbers
1
John
9876, 8765
phone_numbers contains multiple values.
โ 1NF
customers
id
name
1
John
customer_phones
id
customer_id
phone
1
1
9876
2
1
8765
Easy way to remember:
One cell = one value.
2NF – Second Normal Form
Rule: Must already be in 1NF, and every non-key column must depend on the whole primary key, not just part of it.
This matters mainly when you have a composite primary key.
โ Not 2NF
Suppose:
order_items
order_id
product_id
order_date
product_name
qty
101
10
2026-09-12
Laptop
2
101
20
2026-09-12
Mouse
1
Primary key:
(order_id, product_id)
But:
order_date -> depends only on order_id
product_name -> depends only on product_id
qty -> depends on both
So order_date and product_name don’t depend on the whole key.
โ 2NF
orders
order_id
order_date
101
2026-09-12
products
product_id
product_name
10
Laptop
20
Mouse
order_items
order_id
product_id
qty
101
10
2
101
20
1
Easy way to remember:
No column should depend on only part of a composite key.
3NF – Third Normal Form
Rule: Must be in 2NF, and non-key columns should not depend on other non-key columns.
โ Not 3NF
employees
employee_id
employee_name
dept_id
dept_name
1
John
10
Engineering
2
Mary
10
Engineering
Here:
employee_id -> dept_id
dept_id -> dept_name
So:
employee_id -> dept_name
indirectly.
dept_name depends on another non-key column (dept_id).
โ 3NF
employees
employee_id
employee_name
dept_id
1
John
10
2
Mary
10
departments
dept_id
dept_name
10
Engineering
Easy way to remember:
Non-key columns should depend on the key, the whole key, and nothing but the key.
The simplest mental model
1NF
โ
No multiple values in one cell
2NF
โ
No dependency on part of a composite key
3NF
โ
No dependency between non-key columns
Or the classic int. phrase:
3NF: Every non-key attribute depends on the key, the whole key, and nothing but the key.
Int.-friendly example
1NF โ "phone = 9876,8765" โ
split into rows โ
2NF โ (order_id, product_id) is the key
order_date depends only on order_id โ
move it to orders โ
3NF โ dept_id -> dept_name
dept_name shouldn't live in employees โ
move it to departments
โ๏ธ Normalization vs. Denormalization
โ Normalization = Good for consistency, long-term maintenance
โ ๏ธ Denormalization = Good for performance in read-heavy systems (like reporting dashboards)
Use normalization as a default practice, then selectively denormalize if performance requires it.
Delete button example (Rails 7+)
<%= link_to "Delete Product",
@product,
data: { turbo_method: :delete, turbo_confirm: "Are you sure you want to delete this product?" },
class: "inline-block px-4 py-2 bg-red-100 text-red-600 border border-red-300 rounded-md hover:bg-red-600 hover:text-white font-semibold transition duration-300 transform hover:scale-105" %>
Hover effects and transitions for a smooth UI experience.
Add Brand to products table
Let’s add brand column to the product table:
โ rails g migration add_brand_to_products brand:string:
index
class AddBrandToProducts < ActiveRecord::Migration[8.0]
def change
# Add 'brand' column
add_column :products, :brand, :string
# Add index for brand
add_index :products, :brand
end
end
โ๏ธImportant Note:
โ PostgreSQL does not support BEFORE or AFTER when adding a column.
Caused by:
PG::SyntaxError: ERROR: syntax error at or near "BEFORE" (PG::SyntaxError)
LINE 1: ...LTER TABLE products ADD COLUMN brand VARCHAR(255) BEFORE des...
PostgreSQL (default in Rails) does not support column order (theyโre always returned in the order they were created).
If you’re using MySQL, you could use raw SQL for positioning as shown below.
If I USEMySQL, I would like to see the brand name as first column of the table products. You can do that by changing the migration to:
class AddBrandToProducts < ActiveRecord::Migration[8.0]
def up
execute "ALTER TABLE products ADD COLUMN brand VARCHAR(255) BEFORE description;"
add_index :products, :brand
end
def down
remove_index :products, :brand
remove_column :products, :brand
end
end
Reverting Previous Migrations
You can use Active Record’s ability to rollback migrations using the revert method:
require_relative "20121212123456_example_migration"
class FixupExampleMigration < ActiveRecord::Migration[8.0]
def change
revert ExampleMigration
create_table(:apples) do |t|
t.string :variety
end
end
end
The revert method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations.
If youโve already built a Rails 8 app using the default SQLite setup and now want to switch to PostgreSQL, hereโs a clean step-by-step guide to make the transition smooth:
1.๐ง Setup PostgreSQL in macOS
๐ท Step 1: Install PostgreSQL via Homebrew
Run the following:
brew install postgresql
This created a default database cluster for me, check the output. So you can skip the Step 3.
==> Summary
๐บ /opt/homebrew/Cellar/postgresql@14/14.17_1: 3,330 files, 45.9MB
==> Running `brew cleanup postgresql@14`...
==> postgresql@14
This formula has created a default database cluster with:
initdb --locale=C -E UTF-8 /opt/homebrew/var/postgresql@14
To start postgresql@14 now and restart at login:
brew services start postgresql@14
Or, if you don't want/need a background service you can just run:
/opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14
Sometimes Homebrew does this automatically. If not:
initdb /opt/homebrew/var/postgresql@<version>
Or a more general version:
initdb /usr/local/var/postgres
Key functions of initdb: Creates a new database cluster, Initializes the database cluster’s default locale and character set encoding, Runs a vacuum command.
In essence, initdb prepares the environment for a PostgreSQL database to be used and provides a foundation for creating and managing databases within that cluster
๐ท Step 4: Create a User and Database
PostgreSQL uses a role-based access control. Create a user with superuser privileges:
# createuser creates a new Postgres user
createuser -s postgres
createuser is a shell script wrapper around the SQL command CREATE USER via the Postgres interactive terminal psql. Thus, there is nothing special about creating users via this or other methods
Then switch to psql:
psql postgres
You can also create a database:
createdb <db_name>
๐ท Step 5: Connect and Use psql
psql -d <db_name>
Inside the psql shell, try:
\l -- list databases
\dt -- list tables
\q -- quit
Then go to http://localhost:3000 and confirm everything works.
7. Check psql manually (Optional)
psql -d your_app_name_development
Then run:
\dt -- view tables
\q -- quit
8. Update .gitignore
Note: If not already added /storage/*
Make sure SQLite DBs are not accidentally committed:
/storage/*.sqlite3
/storage/*.sqlite3-journal
After moving into PostgreSQL
I was getting an issue with postgres column, where I have the following data in the migration:
# migration
t.decimal :rating, precision: 1, scale: 1
# log
ActiveRecord::RangeError (PG::NumericValueOutOfRange: ERROR: numeric field overflow
12:44:36 web.1 | DETAIL: A field with precision 1, scale 1 must round to an absolute value less than 1.
12:44:36 web.1 | )
Value passed is: 4.3. I was not getting this issue in SqLite DB.
What does precision: 1, scale: 1 mean?
precision: Total number of digits (both left and right of the decimal).
scale: Number of digits after the decimal point
If you want to store ratings like 4.3, 4.5, etc., a good setup is:
t.decimal :rating, precision: 2, scale: 1
# revert and migrate for products table
โ rails db:migrate:down VERSION=2025031XXXXX -t
โ rails db:migrate:up VERSION=2025031XXXXXX -t
Then go to http://localhost:3000 and confirm everything works.
For a Ruby on Rails 8 application, the choice of database depends on your specific needs, but hereโs a breakdown of the best options and when to use each:
PostgreSQL (Highly Recommended)
Best overall choice for most Rails apps.
Why:
First-class support in Rails.
Advanced features like full-text search, JSONB support, CTEs, window functions.
Strong consistency and reliability.
Scales well vertically and horizontally (with tools like Citus).
Used by: GitHub, Discourse, Basecamp, Shopify.
Use if:
Youโre building a standard Rails web app or API.
You need advanced query features or are handling complex data types (e.g., JSON).
SQLite (For development/testing only)
Lightweight, file-based.
Fast and easy to set up.
But not recommended for production.
Use if:
Youโre building a quick prototype or local dev/testing app.
NOT for multi-user production environments.
MySQL / MariaDB
Also supported by Rails.
Can work fine for simpler applications.
Lacks some advanced features (like robust JSON support or full Postgres-style indexing).
Not the default in many modern Rails setups.
Use if:
Your team already has MySQL infrastructure or legacy systems.
You need horizontal scaling with Galera Cluster or similar setups.
Others (NoSQL like MongoDB, Redis, etc.)
Use Redis for caching and background job data (not as primary DB).
Use MongoDB or other NoSQL only if your data model really demands it (e.g., unstructured documents, event sourcing).
Recommendation Summary:
Use Case
Recommended DB
Production web/API app
PostgreSQL
Dev/prototyping/local testing
SQLite
Legacy systems/MySQL infrastructure
MySQL/MariaDB
Background jobs/caching
Redis
Special needs (e.g., documents)
MongoDB (with caution)
If you’re starting fresh or building something scalable and modern with Rails 8, go with PostgreSQL.
Letโs break that down:
๐ฌ What does “robust JSON support” mean?
PostgreSQL supports a special column type: json and jsonb, which lets you store structured JSON data directly in your database โ like hashes or objects.
Why it matters:
You can store dynamic data without needing to change your schema.
You can query inside the JSON using SQL (->, ->>, @>, etc.).
You can index parts of the JSON โ for speed.
๐ง Example:
You have a products table with a specs column that holds tech specs in JSON:
SELECT * FROM products WHERE specs->>'color' = 'black';
Or check if the JSON contains a value:
SELECT * FROM products WHERE specs @> '{"brand": "Libas"}';
You can even indexspecs->>'color' to make these queries fast.
๐ฌ What does “full Postgres-style indexing” mean?
PostgreSQL supports a wide variety of powerful indexing options, which improve query performance and flexibility.
โ๏ธ Types of Indexes PostgreSQL supports:
Index Type
Use Case
B-Tree
Default; used for most equality and range searches
GIN (Generalized Inverted Index)
Fast indexing for JSON, arrays, full-text search
Partial Indexes
Index only part of the data (e.g., WHERE active = true)
Expression Indexes
Index a function or expression (e.g., LOWER(email))
Covering Indexes (INCLUDE)
Fetch data directly from the index, avoiding table reads
B-Tree Indexes: B-tree indexes are more suitable for single-value columns.
When to Use GIN Indexes: When you frequently search for specific elements within arrays, JSON documents, or other composite data types.
Example for GIN Indexes: Imagine you have a table with a JSONB column containing document metadata. A GIN index on this column would allow you to quickly find all documents that have a specific author or belong to a particular category.
Why does this matter for our shopping app?
We can store and filter products with dynamic specs (e.g., kurtas, shorts, pants) without new columns.
Full-text search on product names/descriptions.
Fast filters: color = 'red' AND brand = 'Libas' even if those are stored in JSON.
Index custom expressions like LOWER(email) for case-insensitive login.
๐ฌ What are Common Table Expressions (CTEs)?
CTEs are temporary result sets you can reference within a SQL query โ like defining a mini subquery that makes complex SQL easier to read and write.
WITH recent_orders AS (
SELECT * FROM orders WHERE created_at > NOW() - INTERVAL '7 days'
)
SELECT * FROM recent_orders WHERE total > 100;
Breaking complex queries into readable parts.
Re-using result sets without repeating subqueries.
In Rails (via with from gems like scenic or with_cte):
Window functions perform calculations across rows related to the current row โ unlike aggregate functions, they donโt group results into one row.
๐ง Example: Rank users by their score within each team:
SELECT
user_id,
team_id,
score,
RANK() OVER (PARTITION BY team_id ORDER BY score DESC) AS rank
FROM users;
Use cases:
Ranking rows (like leaderboards).
Running totals or moving averages.
Calculating differences between rows (e.g. โHow much did this order increase from the last?โ).
๐ค In Rails:
Window functions are available through raw SQL or Arel. Here’s a basic example:
User
.select("user_id, team_id, score, RANK() OVER (PARTITION BY team_id ORDER BY score DESC) AS rank")
CTEs and Window functions are fully supported in PostgreSQL, making it the go-to DB for any Rails 8 app that needs advanced querying.
JSONB Support
JSONB stands for “JSON Binary” and is a binary representation of JSON datathat allows for efficient storage and retrieval of complex data structures.
This can be useful when you have data that doesn’t fit neatly into traditional relational database tables, such as nested or variable-length data structures.
Absolutely โ storing JSON in a relational database (like PostgreSQL) can be super powerful when used wisely. It gives you schema flexibility without abandoning the structure and power of SQL. Here are real-world use cases for using JSON columns in relational databases:
Here are real-world use cases for using JSON columns in relational databases:
๐ง 1. Flexible Metadata / Extra Attributes
Let users store arbitrary attributes that don’t require schema changes every time.
A lightweight version that only declares attribute accessors for keys inside a JSON column. Doesnโt include serialization logic โ so you usually use it with a json/jsonb/text column that already works as a Hash.
๐ Example:
class User < ApplicationRecord
store_accessor :settings, :theme, :notifications
end
This gives you:
user.theme, user.theme=
user.notifications, user.notifications=
๐ค When to Use Each?
Feature
When to Use
store
When you need both serialization and accessors
store_accessor
When your column is already serialized (jsonb, etc.)
If you’re using PostgreSQL with jsonb columns โ it’s more common to just use store_accessor.
Querying JSON Fields
User.where("settings ->> 'theme' = ?", "dark")
Or if you’re using store_accessor:
User.where(theme: "dark")
๐ก But remember: youโll only be able to query these fields efficiently if youโre using jsonb + proper indexes.
๐ฅ Conclusion:
PostgreSQL can store, search, and index inside JSON fields natively.
This lets you keep your schema flexible and your queries fast.
Combined with its advanced indexing, itโs ideal for a modern e-commerce app with dynamic product attributes, filtering, and searching.
To install and set up PostgreSQL on macOS, you have a few options. The most common and cleanest method is using Homebrew. Hereโs a step-by-step guide:
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!
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.
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.