AI Hints
Home›System Design Tutorial›Designing APIs
System Design · Lesson 18 of 120

Pagination

One page at a time.

⏱ 2 min read▶ Video at 20:20🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Shoply now has a million orders. If an API returned all of them at once, it would be huge and slow. Pagination returns a list one page at a time.

Pagination
From the video: Pagination
  • A million orders
  • Too big for one response
  • Send one page at a time

Offset vs cursor

There are two main styles. Offset pagination says, skip forty, give me twenty. It's simple, but slow for deep pages, and items shift if new ones are added. Cursor pagination says, give me twenty after this item. It stays fast and stable, which is why big feeds use it.

Offset: ?offset=40&limit=20

  • SimpleSlow on deep pagesItems can shift

Cursor: ?after=abc&limit=20

  • Fast at any depthStable while data changesUsed by feeds

Cursor pagination

Here's cursor pagination in a few lines. The cursor is the last ID the client saw. Each call returns items after it, plus the next cursor. Run it. We walk through ten orders, three at a time, and the last page tells us there's nothing more.

pages.pypython
orders = list(range(101, 111))  # order ids

def page(after=None, limit=3):
    start = 0 if after is None else orders.index(after) + 1
    items = orders[start:start + limit]
    nxt = items[-1] if start + limit < len(orders) else None
    return items, nxt

cursor, n = None, 1
while True:
    items, cursor = page(cursor)
    print(f"page {n}: {items}  next={cursor}")
    if cursor is None:
        break
    n += 1
Output
page 1: [101, 102, 103]  next=103
page 2: [104, 105, 106]  next=106
page 3: [107, 108, 109]  next=109
page 4: [110]  next=None

Summary

Pagination returns long lists in pages. Cursors stay fast and stable, offsets are simpler. Next, a property that makes retries safe. Idempotency.

Key takeaways
  • Never return everything
  • Offset: simple
  • Cursor: fast and stable
Next up: Idempotency — safe to retry