SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

Pagination, Filtering and Sorting

Return big lists a page at a time, and let clients narrow and order them.

⏱ 14 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Pagination, filtering and sorting are the three tools that let an API return a small, useful slice of a big list instead of everything at once.

  • Pagination cuts a long list into pages, so one response stays small and fast.
  • Filtering keeps only the rows the client asked for (for example, only orders that are "paid").
  • Sorting puts the rows in a known order (for example, newest first). Without a stable order, pages can overlap or miss rows.

02Concept: What is it?

Imagine an endpoint GET /orders on a shop with 10 million orders. Sending all of them would take a long time, use a lot of memory on the server and on the phone, and almost nobody wants to read them all. So the API returns one page and tells the client how to get the next one.

There are two common ways to say "give me the next page":

  • Offset (or page number): ?offset=40&limit=20 means "skip the first 40 rows and give me 20". It is simple, and the client can jump to any page.
  • Cursor (or keyset): ?after=8841&limit=20 means "give me 20 rows that come after the row I saw last". The server often wraps this value in an opaque string called a cursor.
Offset versus cursor
Offset
πŸ“¨offset=40skip 40, take 20
→↓scan and drop 40
πŸ—„οΈDatabase
Work grows with the page numberdeep pages are slow
Cursor
πŸ“¨after=8841continue after this row
→↓jump with index
πŸ—„οΈDatabase
Work stays the same on every pageneeds an index
Offset counts from the top every time. A cursor remembers where you stopped.
🧠Filtering and sorting come first
The database filters first, then sorts, then cuts a page. So the page you get is always a slice of a filtered, sorted list. If the sort order is not stable (two rows can tie), the same row may land on two pages, or on none.

03Real-Life Example

🍡The Library Shelf and the Bookmark
A library has a shelf with thousands of books, sorted by the date they arrived. You cannot carry them all home, so the librarian gives you 10 books at a time. If you say "skip the first 40 and give me the next 10", the librarian has to count 40 books each time. And if a new book is slipped onto the front of the shelf while you are away, your count is now off by one, so you get a book you already have. A bookmark works better: "give me the 10 books after the one I am holding". New books at the front do not matter.
Library
API
The whole shelf
The whole table of results
Taking 10 books at a time
Page size (limit)
β€œSkip the first 40”
Offset
The bookmark in the last book
A cursor
Only cookery books
A filter (category=cookery)
Sorted by arrival date
Sort order (created_at, id)
Two books that arrived the same minute
Ties: need a tie-breaker like the id
A limit of 100 books per visit
A maximum page size
One list request, step by step
πŸ”ŽFilterstatus = paid
→↓
↕️Sortnewest first, then id
→↓
βœ‚οΈCut a page20 rows
→↓
πŸ“¦Respondrows + next cursor

04Why Do We Need It?

⚑Fast responses
A small page is quick to read from the database, send over the network and draw on the screen.
🧠Less memory
Neither the server nor the phone has to hold millions of rows at once.
πŸ›‘οΈProtect the database
A maximum page size stops one request from reading the whole table.
🎯Show what matters
Filters and sorting let the user find the 20 rows they care about.
πŸ’ΈLower cost
Less data sent means less bandwidth and fewer database reads to pay for.
πŸ”Predictable behaviour
A fixed way to walk a list means clients can loop through it safely.
Never return an unbounded list. Return a page, a sort order that never ties, and a way to ask for the next page.

05Where Do We Use It?

πŸ›’Order and product lists
Shops list products by price or newest, with filters for size, colour and brand.
πŸ“°Feeds and timelines
Social apps load the next batch as you scroll. This is nearly always cursor-based.
πŸ“ŠAdmin tables
Dashboards show numbered pages with a total, so offset or page numbers are common.
πŸ“œLogs and audit trails
Huge, always-growing lists where deep offsets would be very slow.
πŸ”ŒPublic APIs
Services such as payment and code-hosting APIs return a page plus a link or cursor for the next one.
πŸ”„Data sync and export
A job that copies every row walks the list with a cursor, so no row is skipped or repeated.

06Types / Parts / How It Works

Three ways to paginate

StyleRequest looks likeGood atWeak at
Offset / limit?offset=40&limit=20Simple, easy to jump to any pageSlow on deep pages. Rows can repeat or be skipped when data changes.
Page number?page=3&per_page=20Friendly for numbered page links in a UISame weaknesses as offset (it is offset in disguise).
Cursor / keyset?after=8841&limit=20Fast at any depth. Stable while data changes.No jumping to page 50. Needs a unique sort key and an index.

What the response should include

A cursor response (example)
GET /orders?status=paid&sort=-created_at&limit=2

{
  "data": [
    { "id": 8842, "total": 30 },
    { "id": 8841, "total": 12 }
  ],
  "next_cursor": "eyJpZCI6ODg0MX0",
  "has_more": true
}

Some APIs put the next link in a Link header instead of the body. Either works. The important part is that the client never has to build the cursor itself.

Filtering and sorting rules

TopicGood practiceWhy
Filter fieldsAllow only a fixed list of fields, such as status, created_from, created_toA free-for-all filter can force slow queries on columns with no index.
OperatorsKeep them simple (equals, range, in a list) and document themClear rules are easier to validate and to optimise.
Sort fieldsAllow only a fixed list of sortable fieldsThe database needs an index to sort a big table quickly.
Tie-breakerAlways add the unique id as the last sort keyRows with the same date would otherwise come back in a random order, and pages would overlap.
Total countOffer it only when needed, or give an approximate countCOUNT(*) on a huge filtered table is slow.
Maximum page sizeSet a cap (for example, 100) and a defaultStops a client from asking for a million rows.
VisualizerOffset versus cursor while the data changesRead page 1, then add or delete rows, then read pages 2 and 3. Watch the amber repeats and red skipped rows with offset, and nothing wrong with the cursor. Then drag the depth slider to see how the cost grows.
What happens after the user reads page 1?
Row 40 is the newest at the start. Cyan = shown once. Amber = shown twice. Red = still in the table but never shown.
Offset paging
?offset=8&limit=8: skip N rows, take the next
Page 1
4039383736353433
Page 2
3534333231302928
Page 3
2726252423222120
Rows the user never saw
none
Cursor paging
?after=<last id>&limit=8: continue after the last row seen
Page 1
4039383736353433
Page 2
3231302928272625
Page 3
2423222120191817
Rows the user never saw
none
3 new rows were added at the top after page 1. Offset counts from the top again, so the last 3 rows of page 1 slid down and show up twice (amber). The cursor says "after row 33", so it keeps its place and shows no repeats.
Offset: rows read
16,000
about 16 ms (illustrative)
Cursor: rows read
8
about 1 ms (illustrative)
Offset: repeats
3
rows shown twice
Offset: skipped
0
rows never shown
Cursor: problems
0
repeats + skipped

A simplified model with a fixed table of 40 rows and no random numbers. The cost numbers are illustrative: they assume the database reads about 1,000 rows per millisecond and that the cursor query can use an index on the sort column. Real speeds depend on your hardware, data and indexes.

07How to Use It / Steps / Implementation

Designing a good list endpoint

  1. 1
    Always set a default and a maximum page size
    For example, a default of 20 and a hard limit of 100. Return an error or clamp the value if a client asks for more.
  2. 2
    Pick the style that fits the screen
    Infinite scroll and data sync: cursor. A small admin table with numbered pages: offset can be fine.
  3. 3
    Define one stable sort order
    Sort by a field plus the unique id, for example created_at DESC, id DESC. Add an index that matches it.
  4. 4
    Allow-list filters and sorts
    Accept only fields you have indexed and tested. Reject the rest with a clear error message (400).
  5. 5
    Make the cursor opaque
    Encode the last sort values into one string. Clients pass it back unchanged, so you can change how it works later.
  6. 6
    Tell the client what comes next
    Return next_cursor and has_more (or a Link header). Do not make the client guess when the list has ended.
  7. 7
    Think about the total
    A total count looks nice but can be costly. Return it only on request, or cache or estimate it.
πŸ’‘Match the index to the query
A cursor query like WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20 is fast only when there is an index on (created_at, id). Add the index first, then expose the sort field.
⚠️Do not let the cursor be a security hole
If a cursor is just a plain row id, a client can edit it. Treat it as untrusted input: validate it, and never let it bypass the permission checks for the rows.

08Key Terms to Know

TermMeaning in easy words
PaginationCutting a long list into pages
Page size / limitHow many rows one response holds
OffsetHow many rows to skip from the start of the list
CursorA marker that says where the last page ended
Keyset paginationA cursor made from the sort column values, used in a WHERE clause
FilterA condition that keeps only some rows
Sort orderThe order the rows are returned in
Tie-breakerA unique extra sort key (usually the id) that makes the order the same every time
Opaque cursorA cursor whose inside the client does not read or build
Total countThe number of rows that match the filter in all pages
Allow-listA fixed list of fields that clients may filter or sort by

09Pros, Cons and Trade-offs

βœ… Pros
  • Small, fast responses
  • Protects the database and the network
  • Cursors stay correct while data changes
  • Filters and sorts help users find things
  • Easy for clients to loop through a whole list
⚠️ Cons
  • Offset gets slow on deep pages
  • Offset can repeat or skip rows
  • Cursors cannot jump to page 50
  • Total counts can be expensive
  • Every filter and sort needs a matching index

Trade-offs

ChoiceWe gainWe lose
OffsetSimple, can jump to any pageSlow when deep, unstable when data changes
CursorFast and stable at any depthNo random page access, more design work
Return a total countNice page numbers in the UIAn extra, sometimes slow query
Allow any filterVery flexible for clientsSlow queries and a bigger attack surface
Allow-listed filtersPredictable speed and safetyClients cannot ask for every combination
Big page sizeFewer round tripsSlower responses and more memory

10Common Problems and Mistakes

Common mistakes

  1. No limit at all. One request for /orders reads the whole table and takes the service down.
  2. Sorting by a field that can tie. Sorting only by created_at lets rows with the same time swap places between pages. Add the id.
  3. Deep offsets on a huge table. OFFSET 5000000 still reads and throws away five million rows.
  4. Sorting without an index. The database sorts the whole result in memory every time.
  5. Counting everything on every request. A COUNT(*) on a big filtered table can cost more than the page itself.
  6. Letting the client build cursors. If they depend on the cursor's inside, you can never change it.
  7. Filtering on any column. Clients can trigger full table scans, or probe data they should not see.

Things to watch

πŸ‘―Repeats
A row shows twice because new rows pushed it down a page. Typical with offset on a fast-changing list.
πŸ•³οΈSkips
A row is never shown because rows before it were deleted. Typical with offset.
🐒Deep page latency
Response time grows with the offset. Watch the slowest pages.
πŸ”Permissions
Filter by what the caller may see before paging, not after, or counts and cursors can leak data.

11Real-World Examples

πŸ™Code-hosting APIs
Many list endpoints return a page of results plus links to the next and previous pages.
πŸ’³Payment APIs
Lists are walked with a cursor made from the last object’s id, which is easy to loop through.
πŸ“±Social feeds
Infinite scroll uses cursors, so new posts at the top do not shift what you already read.
πŸ“ˆAdmin consoles
Numbered pages with a total are common where the data is small or changes slowly.
πŸ”Search results
Page numbers are fine for the first few pages. Beyond that, many engines limit how deep you can go.
🧾Data exports
A job copying millions of rows uses keyset paging so it is fast and loses nothing.
πŸ“Note
Parameter names (limit, offset, page, cursor, after) differ from API to API. What matters is that you pick one style and use it everywhere.
Mini case: scrolling a feed
πŸ“±Page 1posts 40 to 33
→↓new post 41
πŸ“±Page 2after=33: posts 32 to 25
First read Data changed Cursor keeps its place
With a cursor, the new post at the top does not disturb the scroll.

12Related Topics to Read Next

What is an API?β†’

The basics of requests, responses and endpoints.

REST, GraphQL, gRPC→

Each style has its own way to paginate and filter.

Indexing→

Fast sorting and cursors depend on the right index.

Query Optimization→

Why deep offsets and unindexed filters are slow.

Rate Limiting→

Another way to stop one client from asking for too much.

Error Handling and Status Codes→

How to reject a bad filter or an oversized page.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: return a small slice of a big list, with filters and a stable sort.
  • βœ”Offset: simple, can jump around, but slow when deep and unstable when data changes.
  • βœ”Cursor: fast and stable. Continue after the last row. No random page access.
  • βœ”Sort: always end with a unique tie-breaker such as the id.
  • βœ”Limits: set a default and a maximum page size.
  • βœ”Filters and sorts: allow-list them, and keep an index for each.
  • βœ”Count: optional or approximate. Exact counts on big tables cost a lot.
  • βœ”One line: β€œReturn a page, in a stable order, with a bookmark to the next one.”
← Previous
REST, GraphQL, gRPC
Next β†’
API Versioning