0
0
Rest-apiComparisonBeginner · 4 min read

Offset vs Cursor Pagination: Key Differences and When to Use Each

Offset pagination uses a page number or offset to fetch data slices, while cursor pagination uses a unique cursor pointing to a specific item for more efficient and consistent results. Cursor pagination handles large or changing datasets better by avoiding duplicates or missing items that offset pagination can cause.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of offset and cursor pagination based on key factors.

FactorOffset PaginationCursor Pagination
MethodUses numeric offset or page numberUses a unique cursor (e.g., ID or token)
PerformanceSlower on large datasets due to scanningFaster and more efficient with indexes
Data ConsistencyCan skip or duplicate items if data changesConsistent results even if data changes
Implementation ComplexitySimple to implementMore complex to implement
Use CaseSmall to medium static datasetsLarge or frequently changing datasets
User ExperienceEasy to jump to any pageSequential navigation, no direct page jumps
⚖️

Key Differences

Offset pagination works by specifying how many items to skip before starting to return results. For example, if you want page 3 with 10 items per page, you skip 20 items and return the next 10. This is simple but can be slow on large datasets because the database must count and skip many rows. Also, if data changes between requests, users might see duplicates or miss items.

Cursor pagination uses a unique identifier from the last item of the previous page as a cursor. The next page fetches items after this cursor. This method is faster because it uses indexed lookups and avoids counting rows. It also handles data changes gracefully, ensuring users see a consistent sequence without duplicates or gaps.

While offset pagination allows jumping directly to any page number, cursor pagination requires sequential navigation. Cursor pagination is more complex to implement but provides better performance and reliability for large or dynamic data.

💻

Offset Pagination Code Example

python
from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data
items = [f"item_{i}" for i in range(1, 101)]  # 100 items

@app.route('/offset-pagination')
def offset_pagination():
    try:
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
    except ValueError:
        return jsonify({'error': 'Invalid page or per_page'}), 400

    start = (page - 1) * per_page
    end = start + per_page
    data = items[start:end]

    return jsonify({
        'page': page,
        'per_page': per_page,
        'data': data
    })

if __name__ == '__main__':
    app.run(debug=False)
Output
{"page":2,"per_page":10,"data":["item_11","item_12","item_13","item_14","item_15","item_16","item_17","item_18","item_19","item_20"]}
↔️

Cursor Pagination Equivalent

python
from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data with IDs
items = [{'id': i, 'name': f'item_{i}'} for i in range(1, 101)]  # 100 items

@app.route('/cursor-pagination')
def cursor_pagination():
    try:
        cursor = int(request.args.get('cursor', 0))
        per_page = int(request.args.get('per_page', 10))
    except ValueError:
        return jsonify({'error': 'Invalid cursor or per_page'}), 400

    # Get items with id greater than cursor
    filtered = [item for item in items if item['id'] > cursor]
    data = filtered[:per_page]

    next_cursor = data[-1]['id'] if data else None

    return jsonify({
        'cursor': cursor,
        'per_page': per_page,
        'data': data,
        'next_cursor': next_cursor
    })

if __name__ == '__main__':
    app.run(debug=False)
Output
{"cursor":10,"per_page":10,"data":[{"id":11,"name":"item_11"},{"id":12,"name":"item_12"},{"id":13,"name":"item_13"},{"id":14,"name":"item_14"},{"id":15,"name":"item_15"},{"id":16,"name":"item_16"},{"id":17,"name":"item_17"},{"id":18,"name":"item_18"},{"id":19,"name":"item_19"},{"id":20,"name":"item_20"}],"next_cursor":20}
🎯

When to Use Which

Choose offset pagination when your dataset is small or mostly static, and you want users to jump directly to any page easily. It is simple to implement and works well for basic use cases.

Choose cursor pagination when working with large or frequently changing datasets where performance and data consistency matter. Cursor pagination avoids duplicates and missing items, providing a smoother experience for infinite scrolling or real-time data.

Key Takeaways

Cursor pagination is more efficient and consistent for large or dynamic datasets.
Offset pagination is simpler and allows direct page jumps but can be slower and inconsistent with data changes.
Use offset pagination for small, static data and cursor pagination for large, changing data.
Cursor pagination requires sequential navigation, while offset supports random page access.
Implement cursor pagination when performance and data integrity are priorities.