Level: IntermediateGo Lang

Go Pagination for REST APIs: Offset vs Cursor

8 min read
Go Pagination featured image: limit, cursor and item count cards

Go pagination lets your API return a long list in small pages instead of one huge reply. In this post, you will learn two popular styles, offset and cursor. Then we will build cursor pagination in Go and test it page by page.

This lesson builds on Go REST API for beginners and Go JSON encoding and decoding. We also use ideas from Go input validation. So it helps to read those first.

What Is Go Pagination?

Imagine a library with 50,000 books. Now a user asks for the list of books. You would not hand over all 50,000 at once, because the reply would be huge and slow. Instead, you give ten books and tell the user to ask again for the next ten. That simple idea is pagination. It is also the base of every list API.

In an API, each page is one response with a fixed number of items. The client reads the page, shows it and asks for the next one when needed. Go pagination is just the server code that decides which items belong on each page. So the idea is simple, even though the details need care.

There are two main styles. The first is offset pagination, which says “skip 20 items and give me 10”. The second is cursor pagination, which says “give me 10 items after this marker”. Each has strengths and weaknesses.

Why Go Pagination Matters

Without Go pagination, one request can load a whole table into memory. That is slow for the user, and it is also costly for your server. Here is what Go pagination gives you.

  • Faster replies: small pages are quick to build and quick to send.
  • Lower memory use: the server never holds the full list in one response.
  • Smoother apps: a mobile app can show the first page while it loads the next.
  • Fair use: a client cannot ask for everything in one call.

However, bad pagination can cause strange bugs. Items can appear twice or vanish between pages. Therefore, the choice of style matters, and we will see why in a moment.

How Go Pagination Works

Every paged API follows the same loop, and Go pagination is no different. First, the client sends a request with a page size. Next, the server returns the items and a hint for the next page. Then the client uses that hint in its next request.

Go Pagination diagram showing three requests, three pages and the cursor passed to each next request
The client asks for a page with a limit. The server returns the items plus a next cursor. The client sends that cursor to get the following page, until no cursor is returned.

How Offset Pagination Works

With offset pagination, the client sends limit and offset. For example, limit=10&offset=20 means “skip 20 and take 10”. In SQL, this maps to LIMIT 10 OFFSET 20. It is easy to understand, and you can also jump to any page number.

How Cursor Pagination Works

With cursor pagination, the client sends limit and a cursor. The cursor marks the last item of the previous page. In our example, it is the last ID, encoded as text. The server returns the items that come after that ID. When there are no more items, it returns no cursor at all.

Go Pagination: Offset vs Cursor

The two styles behave differently as data grows and changes. The table below compares them.

FeatureOffsetCursor
Jump to page 50EasyNot possible
Speed on big tablesSlows down as the offset growsStays fast with an index
New rows during pagingItems may repeat or be skippedStable results
Client codeVery simpleSlightly more steps
Best forAdmin tables with page numbersFeeds, timelines and APIs
Go Pagination diagram comparing offset and cursor pages when a new row appears
With offset pagination, a new row at the top shifts every later item, so a page repeats an item. With cursor pagination, the marker stays on the same item.

Here is why offset can fail. Suppose you read page 1. Then a new row appears at the top. When you ask for page 2, every item has moved down by one. As a result, the last item of page 1 shows up again on page 2. A cursor avoids this, because it points to a specific item and not to a position. For this reason, most public APIs use cursors for feeds.

Go Pagination Request and Response Design

Good Go pagination starts with a clear contract. Clients should know which parameters exist and what comes back. The table below shows a simple design that works for most APIs.

PartNameExampleMeaning
Requestlimit10How many items to return
RequestcursorMTA=Where the next page starts
ResponseitemsA list of objectsThe data for this page
Responsenext_cursorMjA=Cursor for the following page

Keep the names stable, because mobile apps may stay on an old version for months. Also, add the new fields instead of renaming old ones. In that way, no client breaks when you improve the API.

What About the Total Count?

Many clients ask for the total number of items. Counting a big table on every request is slow, though. So, return a total only when the user really needs page numbers. Otherwise, a simple “next” button works fine, and it keeps each request cheap.

Pagination with a Database

In a real project, the loop in our handler becomes a query. For cursor pages, the query looks like WHERE id > $1 ORDER BY id LIMIT $2. An index on id makes it fast, even on millions of rows. Our Go database/sql tutorial shows how to run such a query safely.

Go Pagination Hands-On: Cursor Pages

Now let’s build cursor pagination. We use 25 fake books with IDs from 1 to 25, so that we can see every page.

Step 1: The Types and the Handler

First, an Item has an ID and a name, while the Page holds the list. A Page also holds an optional next_cursor. Then the handler reads limit and cursor from the query string. After that, it collects the items after the cursor, and it builds the next cursor.

type Page struct {
	Items      []Item `json:"items"`
	NextCursor string `json:"next_cursor,omitempty"`
}

func listHandler(w http.ResponseWriter, r *http.Request) {
	limit, err := strconv.Atoi(r.URL.Query().Get("limit"))
	if err != nil || limit < 1 || limit > 100 {
		limit = 10
	}
	after := 0
	if c := r.URL.Query().Get("cursor"); c != "" {
		raw, err := base64.URLEncoding.DecodeString(c)
		if err != nil {
			http.Error(w, "bad cursor", http.StatusBadRequest)
			return
		}
		after, _ = strconv.Atoi(string(raw))
	}

	var page Page
	for _, it := range items {
		if it.ID > after {
			page.Items = append(page.Items, it)
			if len(page.Items) == limit {
				break
			}
		}
	}
	if n := len(page.Items); n == limit && page.Items[n-1].ID < items[len(items)-1].ID {
		page.NextCursor = base64.URLEncoding.EncodeToString([]byte(strconv.Itoa(page.Items[n-1].ID)))
	}
	json.NewEncoder(w).Encode(page)
}

Let’s look at the key lines. The limit has a default of 10 and a hard cap of 100. Because of this, a client cannot ask for a million items. The cursor is the last ID in base64, which hides the inner detail from the client. In other words, you can change the format later. Finally, omitempty leaves out next_cursor on the last page, and that is how the client knows to stop.

Step 2: Walk Through All the Pages

Then we write a loop that acts like a client. It asks for a page and prints a summary. After that, it follows the cursor until none is left.

func main() {
	h := http.HandlerFunc(listHandler)
	url := "/books?limit=10"
	for page := 1; ; page++ {
		p := get(h, url)
		fmt.Printf("page %d: ids %d-%d, items=%d, next=%q\n", page, p.Items[0].ID, p.Items[len(p.Items)-1].ID, len(p.Items), p.NextCursor)
		if p.NextCursor == "" {
			break
		}
		url = "/books?limit=10&cursor=" + p.NextCursor
	}
}

Here is the real output from our run.

page 1: ids 1-10, items=10, next="MTA="
page 2: ids 11-20, items=10, next="MjA="
page 3: ids 21-25, items=5, next=""

As you can see, 25 items arrive in three pages. The cursors MTA= and MjA= are just the numbers 10 and 20 in base64, so they are easy to check. On page 3, only five items remain, so the cursor is empty and the loop ends. This is Go pagination working from the first page to the last.

Common Mistakes with Go Pagination

  • No upper limit: a client can ask for a million rows. So always cap the page size, even for trusted clients.
  • Using offset on huge tables: the database must skip many rows each time. Therefore, prefer cursors for large or fast-changing data.
  • Sorting without a stable key: if two rows share the same sort value, they may swap places. Instead, sort by a unique column such as the ID.
  • Trusting the cursor: a client can send any text. So decode it carefully and return a 400 for bad input.
  • Missing the end signal: clients need to know when to stop. For that reason, return an empty cursor or a clear flag on the last page.

Best Practices for Go Pagination

  • Set a default and a maximum page size, because both protect your server.
  • Sort by a unique, indexed column, since the cursor depends on a stable order.
  • Treat the cursor as opaque, which lets you change its format later.
  • Return the next cursor in the body, so clients do not build URLs by hand.
  • Validate every query value, because paging parameters come from users.
  • Document the style, so other teams know how to loop through your pages.

Practice Task

To practise Go pagination, add a prev_cursor field so clients can go back one page. Alternatively, add an offset version of the handler and compare the two on a changing list.

Hint: for the offset version, insert a new item at the start of the slice between two calls. Then watch an item appear twice, as in the second diagram.

Official Resources

These pages describe the packages used in this lesson.

Quick Recap

  • Go pagination returns a long list as small pages.
  • Offset pagination skips a number of items, while cursor pagination continues after a marker.
  • Cursors stay stable when data changes, and offsets can repeat or skip items.
  • Always set a default and a maximum page size.
  • Sort by a unique column so the order never changes.
  • An empty cursor tells the client that the last page is done.

What’s Next?

By now, you can serve large lists in small, stable pages. However, some data is read far more often than it changes. So next, we will build an in-memory cache with a time to live.

Next up: Go in-memory cache with TTL and generics