AlgoViz

API pagination

easy 24 min

Pagination sends a long list in small pages.

See it run

Twelve products, three per page: count past them, or remember where you stopped.

Operations

Offset pages

page=N, limit=3. Every page reads the rows in front of it again.

Step 1 of 4

Page 1

1 Mouse2 USB-C hub3 Keyboard4 Stand
5 Webcam6 Lamp7 Mouse pad8 Organizer
9 Laptop stand10 Cables11 Hook12 Wrist rest

read 3, return 3

GET /products?page=1&limit=3 becomes LIMIT 3 OFFSET 0.

Step 1: Page 1

def page(n, limit=3):    offset = (n - 1) * limit    return query(        "SELECT * FROM products ORDER BY id LIMIT ? OFFSET ?",        limit, offset)
Rows read
offset + 3
Jump to page
Yes
Keyset
3

The answer may carry page 1 of 4 and a total of 12. The total is a second query.

In the real world

The same api pagination doing real jobs. Pick one and step through it.

New posts arrive while somebody scrolls.

Step 1 of 4

Open the feed

Our systemPhone app9 8 7Products APIcursor after 7PostgreSQLposts 1 to 9

Three newest posts and a cursor after 7.

Step 1: Open the feed

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No unique last sort column

    critical

    Rows with equal values can be lost at a page border, or come in a different order each time.

    Wrong
    ORDER BY created_at DESC
    Right
    ORDER BY created_at DESC, id DESC
  • Sorting by one column, seeking by another

    critical

    This orders by created_at and filters by id. Pages repeat and lose rows as soon as the two orders differ.

    Wrong
    query.order_by(created_at.desc())     .filter(id < last_id)
    Right
    query.order_by(created_at.desc(), id.desc())     .filter((created_at, id) < last)
  • Unlimited page size

    major

    limit=1000000 is the whole table in one answer.

    Wrong
    limit = int(args["limit"])
    Right
    limit = max(1, min(int(args.get("limit", 20)), 100))
  • Trusting the cursor

    major

    Anyone can decode and change plain base64, also the owner inside it.

    Wrong
    q = json.loads(b64decode(cursor))rows = load(owner=q["owner"], after=q["id"])
    Right
    q = verify_signature(cursor)rows = load(owner=request.user.id, after=q["id"])

Interview tips

  • How to explain it

    • Offset counts, a cursor remembers.
    • A keyset is what a good cursor holds.
    • Same order, same columns, same index.
  • Memory trick: OCK

    • Offset: old-school, skip and take.
    • Cursor: continuous, where I left off.
    • Keyset: keen on speed, after this id.
  • Offset is fine when

    • The list is small.
    • Page numbers are required.
    • The data is calm.
  • Use a cursor when

    • People scroll without end.
    • Rows come and go.
    • Anyone may ask for a deep page.