Pagination Architectures: Navigating Data Without Losing Your Mind (or Users) ๐Ÿ˜œ๐Ÿš€

Smit Patel
4 min readFeb 16, 2025

--

Scalable Strategies for High-Traffic Systems

Hey there, fellow coders! ๐Ÿ‘‹ Ever tried to eat a pizza in one bite? ๐Ÿ• No? Then why are you forcing your users to swallow 10,000 records in one gulp? ๐Ÿ˜ฑ Thatโ€™s where pagination swoops in like a superhero with a napkin. But not all heroes wear capes โ€” some use LIMIT and OFFSET. Letโ€™s break down the types of pagination, their spicy pros, stinky cons, and when to use them. Buckle up! ๐Ÿš—๐Ÿ’จ

1. Offset Pagination: The Old Reliable (But Sometimes Slothful) ๐Ÿข๐Ÿ“œ

What is it?

The classic โ€œpage 1, 2, 3โ€ฆโ€ approach. Itโ€™s like telling your SQL, โ€œHey, skip the first 1000 pizzas and gimme the next 20!โ€ ๐Ÿ•โžก๏ธ

Real-Life Problem

Imagine scrolling through an e-commerce site for โ€œWorldโ€™s Okayest T-Shirtsโ€ ๐Ÿ‘•. Page 1? Fast. Page 500? Your grandkids will finish scrolling before the page loads. ๐Ÿ˜ญ

Code Magic (Node.js + MySQL)

app.get('/products', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = 20;
const offset = (page - 1) * limit;
const [products] = await connection.query(`
SELECT * FROM products
ORDER BY created_at DESC
LIMIT ? OFFSET ?
`, [limit, offset]);
res.json(products);
});

Pros

  • Simplicity: Easy to implement. Even your cat ๐Ÿˆ could write this query.
  • Stateless: No need to track where users left off. They can jump to page 42 directly! ๐ŸŽฏ

Cons

  • Performance Nightmare: OFFSET 100000 makes your database cry. ๐Ÿ˜ญ It literally counts all skipped rows.
  • Skipped/Repeated Data: If new data arrives while paginating, you might see duplicates or missing items. โ€œWait, whereโ€™d that T-rex T-shirt go?!โ€ ๐Ÿฆ–

When to Use

  • โœ… Required random page access (e.g., support dashboards)
  • โœ… Small datasets (<100K rows)
  • โŒ Avoid for large tables without composite indexes on sorted columns.

2. Cursor Pagination: The Speedy Gonzales of Pagination ๐ŸŽฏ๐Ÿš€

What is it?

Use a pointer (like the last itemโ€™s ID) to fetch the next set. Perfect for infinite scroll! Think of it as SQL saying, โ€œGimme 20 items after this T-rex mug.โ€ โ˜•

Real-Life Problem

Scrolling through a social media feed ๐Ÿ•ถ๏ธ. You donโ€™t want to see the same โ€œIโ€™m babyโ€ meme 5 times because new posts shifted the offset. ๐Ÿ˜ค

Code Magic

app.get('/posts', async (req, res) => {
const cursor = parseInt(req.query.cursor) || 0;
const limit = 20;
const [posts] = await connection.query(`
SELECT * FROM posts
WHERE id > ?
ORDER BY id ASC
LIMIT ?
`, [cursor, limit]);
const nextCursor = posts.length ? posts[posts.length - 1].id : null;
res.json({ posts, nextCursor });
});

Pros

  • Blazing Fast: No OFFSET, so your DB doesnโ€™t waste time counting skips. ๐ŸŽ๏ธ
  • Stable Order: New data wonโ€™t mess up your pagination. Bye-bye, duplicate memes! ๐Ÿ‘‹

Cons

  • No Random Jumps: Users canโ€™t leap to page 69. Itโ€™s like a โ€œYou Must Be This Tallโ€ ride โ€” forward only! ๐ŸŽข
  • Single Column Limitation: Needs a unique, sequential column (like id or created_at).

When to Use

  • โœ… High-velocity append-only data (logs, feeds)
  • โœ… Eliminates duplicates in real-time streams
  • โŒ Not for multi-column sorting.

3. Keyset Pagination: When Cursor Gets Fancy ๐Ÿ”‘๐ŸŽฉ

What is it?

Cursorโ€™s hipster cousin. Uses multiple columns for sorting. Perfect for โ€œSort by price, then by rating, then by alpaca nameโ€ scenarios. ๐Ÿฆ™

Real-Life Problem

Building a leaderboard ๐Ÿ† where users are ranked by score and registration date. Offset pagination would collapse faster than a house of cards. ๐Ÿƒ

Code Magic

app.get('/users', async (req, res) => {
const { lastScore, lastId } = req.query;
const limit = 20;
const [users] = await connection.query(`
SELECT * FROM users
WHERE (score, id) < (?, ?)
ORDER BY score DESC, id DESC
LIMIT ?
`, [lastScore, lastId, limit]);
res.json(users);
});

Pros

  • Efficient Sorting: Handles complex ordering like a champ. ๐Ÿฅ‡
  • No Offset: Still fast for large datasets.

Cons

  • Complex Queries: Writing WHERE (a, b) > (?, ?) feels like solving a Rubikโ€™s cube. ๐Ÿงฉ
  • Client-Side Hassle: Clients must track multiple values. โ€œWhat do you mean I need to remember the score AND the ID?!โ€ ๐Ÿ˜ซ

When to Use

  • โœ… Multi-dimensional sorting (e.g., e-commerce filters)
  • โœ… Avoids offset performance penalties
  • โŒ Requires deterministic sort order (no NULLs).

4. Time-Based Pagination: For the Chronically Organized โณ๐Ÿ“†

What is it?

Paginate using timestamps. Great for time-series data like logs or orders. โ€œShow me all errors after 3 AMโ€ฆ when the devs were asleep.โ€ ๐Ÿ˜ด

Real-Life Problem

Checking your UberEats history ๐Ÿ” to find that midnight snack you regret. Scrolling day-by-day is easier than guessing page numbers.

Code Magic

app.get('/logs', async (req, res) => {
const after = req.query.after || new Date(0).toISOString(); // 1970, baby! ๐Ÿ‘ถ
const limit = 20;
const [logs] = await connection.query(`
SELECT * FROM logs
WHERE created_at > ?
ORDER BY created_at ASC
LIMIT ?
`, [after, limit]);
const nextCursor = logs.length ? logs[logs.length - 1].created_at : null;
res.json({ logs, nextCursor });
});

Pros

  • Intuitive for Time Data: Feels natural for logs or activity feeds.
  • No Offset Issues: Smooth sailing for new data.

Cons

  • Duplicates Possible: If two events have the same timestamp, chaos ensues. ๐Ÿ˜ต
  • Not For Everything: Terrible for non-time-sorted data. โ€œWhy is this pizza order sorted by time?!โ€ ๐Ÿ•

When to Use

  • โœ… Time-range scans (logs, IoT sensor data)
  • โœ… Partition pruning minimizes I/O
  • โŒ Poor fit for non-temporal queries.

Conclusion: Choose Wisely, Padawan! ๐Ÿง™โ™‚๏ธโœจ

  • Offset Pagination: Your go-to for small datasets with random access. Just donโ€™t use it for the Encyclopedia Galactica. ๐Ÿ“š
  • Cursor/Keyset: Infinite scroll kings ๐Ÿ‘‘. Use them for social feeds, leaderboards, or anything where speed > random jumps.
  • Time-Based: When youโ€™re tracking the when more than the what. โฐ

Now go forth and paginate like a pro! And remember: if your users are happy, you can finally eat that pizza slice. ๐Ÿ•๐Ÿ˜Œ (Just donโ€™t use OFFSET 1000 to find it.)

--

--

Smit Patel
Smit Patel

Written by Smit Patel

Passionate about crafting efficient and scalable solutions to solve complex problems. Follow me for practical tips and deep dives into cutting-edge technologies

No responses yet