惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
S
Secure Thoughts
月光博客
月光博客
美团技术团队
雷峰网
雷峰网
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
W
WeLiveSecurity
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
爱范儿
爱范儿
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AI
AI
Last Week in AI
Last Week in AI
Google Online Security Blog
Google Online Security Blog
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recent Announcements
Recent Announcements
Webroot Blog
Webroot Blog
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
N
News and Events Feed by Topic
罗磊的独立博客
The Register - Security
The Register - Security
Blog — PlanetScale
Blog — PlanetScale
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
人人都是产品经理
人人都是产品经理
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
B
Blog
腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Engineering at Meta
Engineering at Meta
Latest news
Latest news
IT之家
IT之家
D
DataBreaches.Net
博客园 - 司徒正美
N
Netflix TechBlog - Medium
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Offset Pagination Step by Step (with Sharding)
Mohamed Idri · 2026-05-10 · via DEV Community

Why pagination exists

Imagine a workers table with 1,000,000 rows. A request like GET /workers that returns all of them would:

  • send a huge JSON payload over the wire
  • crash the browser trying to render it
  • hammer the database

The fix is simple: send a small slice at a time. That slice is called a page.

That is all pagination is. We will build the rest from this idea.

Cute mental model

Think of a deck of 100 cards. You cannot hand someone the whole deck and ask them to find one card fast. Instead you say:

"Take 10 cards at a time. When you finish, ask me for the next 10."

  • 10 cards = page size
  • "which group of 10" = page number
  • "ask me for the next 10" = next page link

That is the whole game.

Step 1: the two numbers we always need

To grab a slice from a database, every ORM needs two things:

  • take — how many rows to return (the slice size)
  • skip — how many rows to ignore from the start

In SQL these are LIMIT and OFFSET.

SELECT * FROM workers ORDER BY id ASC LIMIT 10 OFFSET 20;

Enter fullscreen mode Exit fullscreen mode

That says: skip 20 rows, then give me 10. That is page 3 if each page has 10 rows.

Step 2: where the famous formula comes from

We do not want clients sending skip and take directly. That is awkward. Clients think in page numbers: "give me page 1, page 2, page 3".

So we accept a page number and convert it to skip/take ourselves.

If page size is 10:

Page Skip Take
1 0 10
2 10 10
3 20 10
4 30 10

See the pattern? skip = (page - 1) * size.

That is the formula in our codebase:

return {
  take: page.size,
  skip: (page.num - 1) * page.size,
  // ...
};

Enter fullscreen mode Exit fullscreen mode

Why (page - 1) and not just page?

Because page numbers start at 1 (humans count from 1) but skipping starts at 0 (databases count from 0). Page 1 skips nothing. Page 2 skips one page worth of rows. So we subtract 1 before multiplying.

If we used page * size instead, page 1 would skip 10 rows and the user would never see rows 0 to 9. The first page would be unreachable. That is exactly the bug fixed in commit 431955f of this project (fix(pagination): use 0-based offset so the first page is reachable).

Step 3: how does the client know there is a next page?

Two common answers:

Option A — return a total count. "There are 237 workers. You are on page 3 of 24."
Pros: client can render Page 3 / 24.
Cons: requires a COUNT(*) query on every request, which is slow on big tables.

Option B — just tell them if a next page exists. Return a next link or null.
Pros: cheap, simple, scales.
Cons: cannot show "page 3 of 24" in the UI.

This codebase picks Option B. The response shape is:

{
  "data": [ ... 10 workers ... ],
  "links": { "next": "https://api.example.com/workers?page=2" }
}

Enter fullscreen mode Exit fullscreen mode

When next is missing, you have hit the end.

Step 4: how do we know if a next page exists?

The trick: peek. Ask the database "is there at least one row on the next page?" If yes, return a next link. If no, return undefined.

In this codebase that lives in getNextPage:

const nextPageNum = currentPage.num + 1;
const nextPageInShard = getPage(nextPageNum, currentPage.shard);

const countRemainingInShard = await countOnPage(nextPageInShard, ...);

if (countRemainingInShard > 0) {
  return nextPageInShard;
}

Enter fullscreen mode Exit fullscreen mode

It runs a count query with the next page's skip and take. If the count is greater than 0, the next page has data.

Why not "if rows returned == page size, there is more"?

That is a very common shortcut. If you asked for 10 and got 10, maybe there are more. If you got fewer than 10, you are at the end.

It works, but it lies in one edge case: when the total is a perfect multiple of the page size. With 30 rows, page 3 returns exactly 10. The shortcut says "probably more", so the client requests page 4, gets an empty array, and now you served an extra useless request. Doing a count avoids that.

Cost tradeoff: the count query is extra work. For small to medium tables it is fine. For huge tables you would switch to cursor pagination (we will mention that at the end).

Step 5: the page object

Instead of passing (num, size, shard) everywhere, we wrap them in a single object:

interface Page {
  num: number;
  size: number;
  shard?: number;
}

Enter fullscreen mode Exit fullscreen mode

And a tiny helper builds it with safe defaults:

export function getPage(pageNum?: number, shard?: number): Page {
  return {
    num: pageNum ? pageNum : FIRST_PAGE,        // default to page 1
    size: PAGE_SIZE,                             // fixed at 10
    shard: shard !== undefined ? shard : DEFAULT_SHARD,
  };
}

Enter fullscreen mode Exit fullscreen mode

If the client sends nothing, they get page 1, size 10, shard 0. Nice and forgiving.

Step 6: parsing the request (the NestJS decorator)

Clients send pagination as query params: ?page=2&shard=0. We turn that into a Page object once, in one place:

export const PaginationPage = createParamDecorator((_data, ctx) => {
  const request = ctx.switchToHttp().getRequest();
  const page = parseOptionalInt(request.query.page);
  const shard = parseOptionalInt(request.query.shard);
  return getPage(page, shard);
});

Enter fullscreen mode Exit fullscreen mode

Now any controller can do:

async get(@PaginationPage() page: Page) { ... }

Enter fullscreen mode Exit fullscreen mode

No manual parsing in every handler. Very clean.

Step 7: building the next link

Once we know the next page exists, we build a URL the client can call directly. Important detail: keep all the other query params the user sent (filters, sorting), only change pagination.

const url = new URL(`${request.protocol}://${request.get("Host")}${request.originalUrl}`);
const searchParams = new URLSearchParams(url.search);

searchParams.set("page", nextPage.num.toString());
if (nextPage.shard !== undefined) {
  searchParams.set("shard", nextPage.shard.toString());
}

Enter fullscreen mode Exit fullscreen mode

searchParams.set overwrites just those keys. If the original URL was /workers?location=NY&page=1, the next link becomes /workers?location=NY&page=2. The filter survives.

This pattern is called HATEOAS: the server tells the client where to go next, instead of the client guessing the URL shape.

Step 8: now the twist — sharding

Sharding means splitting one big table into smaller logical buckets. Each row has a shard column (0, 1, 2, ...). Queries always filter by one shard.

Why? On gigantic tables it spreads load and lets you query smaller subsets. In this project shards are limited to MAX_SHARDS = 10.

The pagination has to walk through shard 0 first, then shard 1, then shard 2... When shard 0 is exhausted, jump to shard 1 page 1. That is the second half of getNextPage:

// no more rows in current shard, try next shard
const nextShard = (currentPage.shard ?? DEFAULT_SHARD) + 1;

if (nextShard > MAX_SHARDS) {
  return undefined;       // we have walked all shards, truly done
}

const pageInNextShard = getPage(FIRST_PAGE, nextShard);
const countInNextShard = await countOnPage(pageInNextShard, ...);

if (countInNextShard > 0) {
  return pageInNextShard;
}

return undefined;

Enter fullscreen mode Exit fullscreen mode

Reading top to bottom:

  1. Try the next page in the same shard. Has data? Return it.
  2. Otherwise, jump to page 1 of the next shard. Has data? Return it.
  3. Otherwise, end.

A picture

shard 0:  [page 1] -> [page 2] -> [page 3] -> done in this shard
                                                      |
                                                      v
shard 1:  [page 1] -> [page 2] -> done in this shard
                                          |
                                          v
shard 2:  [page 1] -> ...

Enter fullscreen mode Exit fullscreen mode

The client never sees this complexity. They just keep following links.next.

Step 9: putting it all together

The full request flow for GET /workers?page=2:

1. Decorator parses ?page=2 into a Page object { num: 2, size: 10, shard: 0 }
2. Service calls queryParameters(page) -> { skip: 10, take: 10, where: { shard: 0 } }
3. Prisma runs SELECT ... LIMIT 10 OFFSET 10 WHERE shard = 0
4. Service calls getNextPage(...) which counts the next slice
5. Controller maps rows to DTOs and builds the next link
6. Client gets { data: [...], links: { next: "...?page=3&shard=0" } }

Enter fullscreen mode Exit fullscreen mode

Every piece has one job. That is why each function looks small.

Useful notes you should not forget

  • Always include ORDER BY in paginated queries. Without it, databases can return rows in any order, and the same row could appear on two pages or be skipped. The codebase uses orderBy: { id: "asc" } for this reason.
  • Page size should be capped on the server. If the client could send ?size=1000000, you are back to the original problem. This codebase hard-codes PAGE_SIZE = 10 so the client cannot abuse it.
  • Default to page 1 if the param is missing or invalid. Be forgiving.
  • Skipping is O(N). OFFSET 100000 makes the database scan and discard 100,000 rows. That is fine for small offsets, painful for huge ones. See the next section.

When offset pagination is the wrong choice

You will hit two problems eventually:

Problem 1: deep pages are slow. OFFSET 1000000 LIMIT 10 makes the database walk through a million rows just to throw them away.

Problem 2: shifting data. If a row is inserted while the user paginates, page boundaries shift. They might see the same row twice or miss one.

The fix for both is cursor pagination: instead of "page 2", the client sends "give me 10 rows after id=42". The query becomes WHERE id > 42 ORDER BY id LIMIT 10, which uses an index and is fast no matter how deep you go.

You give up the ability to jump to "page 47" directly. You can only go forward (and sometimes backward). For infinite-scroll feeds this is perfect. For admin tables with page numbers, offset pagination is fine.

This project uses offset pagination because the page sizes are small and the use case suits it. Knowing the alternative is gold in interviews.

Recap in one screen

  • Pagination = serve big lists in small slices.
  • Formula: skip = (page - 1) * size, take = size.
  • Page numbers are 1-based for humans, but skip is 0-based for databases. That is why we subtract 1.
  • Always order results.
  • Return a next link instead of a total count when you do not need page numbers in the UI.
  • To know if next exists, peek at the next slice with a count query.
  • Sharding adds an outer loop: walk pages within a shard, then jump to the next shard.
  • For very large datasets or live feeds, switch to cursor pagination.

If you can explain that list out loud without notes, you understand pagination better than 90 percent of candidates.