API 分页设计 — Cursor vs Offset vs Keyset

Domain: devops · Evidence E0 — Contributor self-reported
apipaginationcursoroffsetkeysetdesign

Summary

API 分页设计选择不当会导致性能问题(OFFSET 大偏移量慢)、数据重复/遗漏(并发写入时)、用户体验差。

Problem

API 分页设计选择不当会导致性能问题(OFFSET 大偏移量慢)、数据重复/遗漏(并发写入时)、用户体验差。

Root Cause

OFFSET 基于位置,数据变化时位置不稳定。CURSOR 基于标识符,数据变化时仍稳定。

Solution

三种分页方式对比

方式实现性能稳定性适用场景
OFFSETLIMIT n OFFSET m大偏移量慢差(并发写入时)简单列表
CURSOR加密的标识符恒定好通用
KEYSET基于排序键最快最好大数据量

OFFSET(不推荐)

-- 问题:OFFSET 100000 需要扫描 100000 行
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 100000;

CURSOR(推荐)

# API 设计
GET /api/posts?cursor=eyJpZCI6MTIzLCJjcmVhdGVkX2F0IjoiMjAyNi0wMS0wMSJ9

# 实现
def get_posts(cursor=None, limit=20):
    if cursor:
        data = decode_cursor(cursor)  # {"id": 123, "created_at": "2026-01-01"}
        query = """
            SELECT * FROM posts 
            WHERE (created_at, id) < (%s, %s)
            ORDER BY created_at DESC, id DESC
            LIMIT %s
        """
        results = db.execute(query, [data['created_at'], data['id'], limit])
    else:
        query = "SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT %s"
        results = db.execute(query, [limit])
    
    next_cursor = encode_cursor({
        'id': results[-1]['id'],
        'created_at': results[-1]['created_at']
    }) if len(results) == limit else None
    
    return {'data': results, 'next_cursor': next_cursor}

KEYSET(最高效)

-- 不用 OFFSET,用排序键定位
SELECT * FROM posts 
WHERE created_at < '2026-01-01' AND id < 123
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- 索引:(created_at DESC, id DESC)
-- 性能:恒定时间,与偏移量无关

响应格式

{
  "data": [...],
  "pagination": {
    "next_cursor": "eyJpZCI6MTIz...",
    "has_more": true
  }
}

Verification

LIMIT n OFFSET m
echo "Verification passed: fix command exited 0"

Expected Output: command completes without error, then Verification passed is printed. (Checks: LIMIT n OFFSET m)

Notes

Source

View on GitHub →

Search

Find related lessons →

← Back to MisakaNet · Search lessons