Part of the guide: Software architecture
Engineering8 min read

Keeping search fast at 20,000 records: keyset pagination in Django REST Framework

Search across every month of someone's spending sounds simple until the list gets long. These are the database and client decisions that kept Spendora's full-history search fast, with measured numbers.

Short answer

Paginate with a cursor on a stable sort key backed by a matching composite index, count totals only on the first page, and debounce and cancel requests on the client. Page 50 then costs the same as page 1.

01The problem with page numbers

Spendora lets users search every expense they have ever recorded — notes, custom category names, categories and income sources — with filters for category, date, amount and source. Results load 30 at a time as you scroll.

The default way to paginate in Django REST Framework is LIMIT and OFFSET. It is easy, and it gets slower the deeper you go: to return page 50, the database still has to walk past the first 1,470 rows. Worse, if a new expense is added while you scroll, every later page shifts by one, so you see one result twice or miss one entirely.

OFFSET pagination is a performance problem and a correctness problem at the same time.

02Keyset pagination on (date, id)

Keyset — or cursor — pagination asks a different question. Instead of "skip 1,470 rows", it asks "give me the next 30 rows after the last one I saw". Spendora orders results by date descending, then ID descending as a tie-breaker, so the order is total and stable.

The cursor is simply the date and ID of the last row on the current page, encoded opaquely. The next query filters for rows strictly before that pair. Because new expenses sort above the cursor, they never shift later pages — no gaps, no duplicates.

  • A composite index on (user, -date, -id) matches the sort exactly, so each page is an index range scan.
  • Category and amount filters have their own composite indexes, so filtered searches stay on an index too.
  • The response returns next_cursor; the client never builds page numbers.

03Text search that does not scan the table

A search box usually becomes an icontains query — a case-insensitive LIKE with a leading wildcard, which a normal B-tree index cannot help with. On a large table that means a full scan on every keystroke.

On PostgreSQL, Spendora adds a trigram GIN index using the pg_trgm extension. Trigram indexes break text into three-character chunks, which lets PostgreSQL answer "contains this word" queries from the index. Locally, the same code falls back to SQLite without the index, so development stays simple.

04Count once, not on every page

The results bar shows how many expenses match and their total amount. Counting and summing are the expensive parts of a search, and the answer does not change as you scroll.

So count and total are returned only on the first page. Later pages return just the rows and the next cursor. Tests also assert a fixed number of database queries per request, so a future change cannot quietly reintroduce an N+1 query on the related income source.

06The numbers

Measured on 20,000 expenses in SQLite during development: the first page of results in about 10 ms, a text search in about 34 ms, and a deep page in about 6 ms. A deep page is faster than the first because it skips the count and total.

None of these techniques are exotic. They are the difference between a search that works in a demo with 50 rows and one that still works after a user has been tracking their spending for five years.

TopicsDjango REST FrameworkPostgreSQLPerformancePaginationReact NativeAPI design

FAQ

Quick answers

Keyset (or cursor) pagination fetches the next page by filtering for rows after the last row already seen, using a stable sort key, instead of skipping a number of rows with OFFSET. Each page costs the same regardless of depth.

Yes. DRF includes CursorPagination, and you can also implement a custom cursor when you need a compound sort key such as date plus ID together with filters.

Enable the pg_trgm extension and add a GIN trigram index on the searched text column. PostgreSQL can then use the index for case-insensitive contains queries.

Keep reading

All articles

Projects behind this article

The production systems where these decisions were made.

All case studies
  • Spendora Expense Tracker App — Mobile app project preview
    Mobile appPersonal finance

    Spendora Expense Tracker App

    Spendora is an Android expense tracker and budget app built with Expo React Native and Django: income, expen…

    Read case studyLive
  • Veeivs Reporting Analytics Platform — SaaS reporting project preview
    SaaS reportingAnalytics dashboard

    Veeivs Reporting Analytics Platform

    A SaaS reporting and ranking platform for multi-branch performance: live centre stats, agent and team lead r…

    Read case studyLive
  • Healthcare Lead Generation CRM — SaaS project preview
    SaaSCRM

    Healthcare Lead Generation CRM

    A production CRM and lead tracking system for a US healthcare client, built with React, Django, Python, AI d…

    Read case studyLive
  • EMS Employee Management System — EMS project preview
    EMSHR management

    EMS Employee Management System

    A production employee management system for Veeivs covering attendance, leave, HR records, salaries, role-ba…

    Read case studyLive

Related services

If this describes a problem you have right now, these are the ways I can help.

All services
  • Django & Backend

    The backend is where a product either scales or quietly rots. I design data models that match the business, APIs tha…

    Explore service
  • API & Integrations

    Integrations fail quietly. I build them with retries, logging and clear failure states, so when a third-party servic…

    Explore service
  • Mobile App Development

    A mobile app is only as good as the API behind it. I bring the same backend discipline from my CRM and SaaS work — c…

    Explore service
  • Performance & SEO

    A site that Google cannot render is a site Google will not rank. Most technical SEO failures I find are not content …

    Explore service