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

推荐订阅源

C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
A
Arctic Wolf
Security Latest
Security Latest
T
Threatpost
P
Palo Alto Networks Blog
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
Cyberwarzone
Cyberwarzone
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
G
GRAHAM CLULEY
The Hacker News
The Hacker News
C
CERT Recently Published Vulnerability Notes
Know Your Adversary
Know Your Adversary
I
Intezer
Scott Helme
Scott Helme
T
Tenable Blog
NISL@THU
NISL@THU
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
N
News and Events Feed by Topic
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
Project Zero
Project Zero
Latest news
Latest news
Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Forbes - Security
Forbes - Security
Security Archives - TechRepublic
Security Archives - TechRepublic
AI
AI
S
Security Affairs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
D
Docker
P
Proofpoint News Feed
博客园 - Franky

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
The Offset Massacre — Why Cursor Pagination is Mandatory (2026)
Kaushikcoder · 2026-05-09 · via DEV Community

Kaushikcoderpy

Efficient Pagination: Moving Beyond OFFSET for Scalable Data Retrieval

Many applications rely on pagination to display large datasets, from product catalogs to social media feeds. While the OFFSET and LIMIT clauses are commonly taught for this purpose, they often become a significant performance bottleneck as data volumes grow. This article explores the inherent issues with OFFSET-based pagination and presents a more robust, scalable alternative: cursor-based pagination.

The Hidden Costs of Deep Pagination

Consider a scenario where an automated scraper systematically requests pages from a large product catalog API. As the scraper delves deeper into the dataset, perhaps reaching page=80000 on a table containing 20 million records, the database begins to struggle. A single query for this deep page, intended to retrieve 50 items, might force the database to scan and discard millions of preceding rows before identifying the target subset. This sequential processing, especially under sustained load from multiple requests, can quickly exhaust CPU resources, leading to service degradation or even outages. Such experiences often highlight the critical need to re-evaluate the underlying pagination strategy.

The Performance Bottleneck of OFFSET

The fundamental flaw of OFFSET-based pagination lies in its execution. When a query specifies OFFSET N LIMIT M, the database doesn't magically "jump" to the Nth record. Instead, it typically performs a full scan from the beginning of the sorted result set, processes N records, discards them, and then retrieves the subsequent M records.

This linear scan means that the time taken to retrieve data scales proportionally with the offset value, resulting in O(N) complexity. Accessing the first page might be instantaneous, but retrieving data from page 10,000 in a large table could involve scanning hundreds of thousands or millions of rows. This leads to unacceptable latency, increased CPU utilization, and poor database scalability.

Inconsistent User Experience

Beyond performance, OFFSET pagination introduces significant user experience issues, particularly in dynamic datasets. Imagine browsing a social media feed where new posts are constantly added. If a user views the first page and then requests the "next" page using OFFSET, any new items added before the current offset will shift existing records. This can lead to users seeing duplicate items across pages or, conversely, missing items entirely if records are deleted. This inconsistency stems from the OFFSET value being a fixed numerical position, which becomes unreliable in a rapidly changing data environment.

Leveraging Cursor-Based Pagination

The solution to these challenges is cursor-based pagination. Instead of relying on a numerical offset, this method uses a "bookmark" or "cursor" to mark the last item retrieved. Typically, this cursor is a unique, indexed column like a primary key ID or a timestamp.

When a client requests the next set of data, it provides the cursor value of the last item it saw. The database then leverages its B-Tree index to efficiently locate this specific record and retrieve subsequent items. This approach transforms the lookup from an O(N) linear scan to an O(log N) indexed lookup, providing consistent, fast performance regardless of how deep into the dataset the user navigates.

Practical Implementation Example

Implementing cursor-based pagination is straightforward and doesn't require complex libraries. The core idea is to pass the identifier of the last item from the previous page as a parameter for the next request.

Consider this simplified FastAPI example, demonstrating the pattern:

from fastapi import APIRouter, Query
from typing import List, Optional

router = APIRouter()

# Assume FeedItem is a SQLAlchemy model or similar ORM object
# with an 'id' column that is indexed and ordered.
class FeedItem:
    def __init__(self, id: int, content: str):
        self.id = id
        self.content = content

# Mock database interaction for demonstration purposes
# In a real application, this would be a database query.
_mock_db = [FeedItem(i, f"Item {i}") for i in range(1, 1000001)]

@router.get("/api/v1/feed", response_model=dict)
def get_paginated_feed(
    # For the initial request, last_id can be 0 or None
    last_id: int = Query(0, description="The ID of the last item seen in the previous batch."),
    page_size: int = Query(50, ge=1, le=100)
) -> dict:
    """
    Retrieves a paginated list of feed items using cursor-based pagination.
    """

    # The critical SQL pattern: WHERE id > last_id ORDER BY id ASC LIMIT page_size
    # This leverages the index on 'id' for efficient lookup.

    # Simulate database query:
    # In a real application, this would be an ORM query like:
    # results = session.query(FeedItem).filter(FeedItem.id > last_id).order_by(FeedItem.id.asc()).limit(page_size).all()

    filtered_items = [item for item in _mock_db if item.id > last_id]
    sorted_items = sorted(filtered_items, key=lambda x: x.id) # Ensure order for consistent pagination
    results = sorted_items[:page_size]

    # Determine the cursor for the next request
    next_cursor: Optional[int] = results[-1].id if results else None

    return {
        "data": [{"id": item.id, "content": item.content} for item in results],
        "next_cursor": next_cursor
    }

Enter fullscreen mode Exit fullscreen mode

When a client makes the initial request (e.g., /api/v1/feed), last_id defaults to 0. The server returns the first page_size items and the id of the last item in that batch as next_cursor. For subsequent requests, the client sends /api/v1/feed?last_id={next_cursor_value}, allowing the database to directly locate and retrieve the next set of records without rescanning.

Architectural Trade-offs

While cursor-based pagination offers superior performance and data consistency, it introduces a specific constraint on the user interface: the inability to directly jump to an arbitrary "page number." Since a cursor only points to the next logical item in a sequence, it inherently supports only "next" and "previous" navigation (though "previous" requires careful cursor management, often involving ordering in reverse).

This limitation is why many applications employing cursor pagination, such as social media feeds, opt for an "infinite scroll" UI pattern. This design choice prioritizes backend scalability and responsiveness over random-access navigation, effectively transforming a technical constraint into a seamless user experience.

Verifying Performance Gains

To empirically demonstrate the performance difference, consider a practical experiment. A simple backend application can be set up to simulate both OFFSET and cursor-based pagination against a large dataset (e.g., 1,000,000 records).

When querying a deep "page" using OFFSET (e.g., retrieving items starting at offset 999,950), the execution time will visibly increase, reflecting the database's need to sequentially process and discard nearly a million rows. In contrast, a cursor-based query for the same data, using last_id=999950, will complete almost instantaneously. This stark difference in execution time, often orders of magnitude faster for cursor pagination, directly illustrates the efficiency gained by leveraging database indexes for direct data access.