Why CKAN DataStore pagination slows on very large tables
The fix for slow paging on a very large DataStore table has two parts: the portal enforces a row cap on API queries, and clients page with keyset pagination on _id instead of deep offset paging. The exact cap and the offset depth where paging degrades must be confirmed in the DataStore documentation for the CKAN version you run before you set any limit. Offset paging makes PostgreSQL read and discard every row before the requested position on each request, so pages near the end of a table cost more than pages near the start. A portal team usually notices this when a published table has grown into the millions of rows and API clients begin timing out or stalling while they page.
This pattern matters most for three groups. Portal operators who publish large resources own the row cap and need to decide what limit suits their hosting and their largest tables. App developers building on datastore_search need to page with _id and stop increasing offset in their loops. Bulk consumers who pull whole tables through the API need a documented path that does not depend on deep paging. Each group has a different check: operators review the configured limit against their slowest published tables, developers review their paging code, and consumers confirm which endpoint serves full-table exports.
This change does not fix everything that makes large tables slow. A filter on a column without an index still forces PostgreSQL to scan the table, so ask whoever owns the database to review query plans for the filters your consumers actually use. Full-table downloads are a separate path with their own behavior and should be planned on their own. A resource that is slow to load or never reaches the DataStore is a loader problem, and changes to paging will not affect it. Check the loader and its job settings separately.
Row limit and paging options and when each fits
This table compares the paging and row limit options a Large CKAN DataStore client can use, with the state each one asks the client to carry and the work it adds on the server. Read each row as a choice: the simpler options suit small or occasional reads, while keyset paging on _id suits full walks of tables that change slowly. Confirm the rows_max default and the point where offset slowdown starts in the DataStore docs for your CKAN version before you set limits.
| Option | What the client carries | What the server must support | When it fits |
|---|---|---|---|
| Limit and offset paging | Offset, limit and a stable sort. Inserts between requests cause duplicates or gaps | Scans and discards skipped rows, so deep pages cost more | Browsing shallow pages of a table that changes rarely |
| Keyset paging on _id | Last _id seen and ascending order on _id. Cursor breaks if a reload reassigns _id | Seeks from the cursor on _id, so each page starts at the last value. Confirm an index on _id | Walking a large table end to end, such as sync jobs and exports through the API |
| Limit with rows_max cap | A page size at or below the cap, and paging for anything larger | Caps each response to protect the database and the API | Public APIs that need bounded responses. Confirm the default in the DataStore docs |
| include_next_page | Follow the next-page signal until it reports no more rows | Signals whether more rows exist. Confirm how this is computed and what it costs | Clients that page until done and do not need an upfront total. Confirm behavior in your version |
| Changing data between pages | Tolerates duplicates or gaps, or restarts from a saved cursor | Reloads and upserts can change which rows exist and their _id values | Frequently updated feeds: keyset paging with upserts, or a full reload followed by a fresh walk |
| Full table download | No paging state, one request to the dump endpoint | Full downloads follow different row caps than API queries. Confirm in your version | Bulk copies of the full table for users who will load it elsewhere |
How keyset pagination on _id differs from offset paging
Offset paging asks PostgreSQL to skip a number of rows and then return the next block, so the database still has to find and discard every skipped row before it can answer. A crawl that reads page 1, page 2 and then page 400 pays more on each request because the discarded region grows with every page. Keyset paging avoids that. The client sends the last _id it received and asks for rows with a greater _id, sorted ascending, so PostgreSQL can start reading at that point through the index on _id. Each page then costs about the same as the one before it, and cost depends mainly on the page size. Confirm how your DataStore version expresses a range condition on _id in datastore_search, then run EXPLAIN on the exact statement your crawler will send against a copy of your largest table before you settle the design.
The client takes on bookkeeping that offset paging hides. It must persist the last _id from each page before requesting the next one, so a failed crawl can resume without re-reading earlier pages, and it must write rows out in _id order. Rows added during a crawl are the main design decision. New rows receive higher _id values, so a forward crawl usually picks them up, but rows changed or removed behind the cursor will be missed. Decide whether the crawl is a point-in-time export, which means waiting until no loads are running on the resource, or a best-effort sync that runs again later. None of this works unless the key is stable and indexed. If a reload of the resource renumbers rows, every saved cursor becomes invalid, so do not resume a crawl across a reload until you have confirmed how _id is assigned in your version.
include_next_page gives the client a direct signal for when to stop. Read it from the response after each request: while it indicates more rows exist, send the next request with the new last _id, and when it does not, end the crawl. Do not infer the end from a short page alone, because a short page can also come from a filter or a boundary your code did not expect. Confirm how your CKAN version exposes this signal, whether as a field in the response or a request option, and whether it appears on every search path your client uses. The DataStore documentation is the place to check. Then test the stop condition on a table whose row count you know, and confirm that the final page ends at the last row of the source file.
How a client walks a large table page by page
The flow starts when an API client calls datastore_search with a limit and either an offset or an _id cursor. The CKAN action API checks the requested size against rows_max, the server-side cap on rows per call. The DataStore then runs the query through the read-only database user, so reads never need write permissions. PostgreSQL applies the _id filter using the primary key index, so later pages do not depend on scanning earlier rows. The response returns the records plus the next cursor or next page indicator. Check that field before requesting another page.
Trust boundary sits between the public API and the read-only database connection.
Setting up keyset paging for a large DataStore table, step by step
Keyset paging replaces deep offset reads with a cursor on the last _id seen, so each request does a bounded lookup on the index. This sequence checks the versions and row cap, confirms the key column is indexed, changes the client, and proves the result with a full crawl whose totals match the resource metadata.
Confirm CKAN, DataStore and rows_max settings
Record the CKAN version of the portal and the DataStore version that ships with it, then read the rows_max value in the site configuration. The DataStore default is 32000 rows per request, so note whether your site overrides it. Confirm your exact version against the CKAN release notes for your minor line, since behavior can change between minor releases even though patch releases keep backwards compatibility. The check passes when all three values are written in your runbook before any configuration changes.
Confirm the _id column is unique and indexed
Check that the table has an
_idcolumn, that its values are unique, and that an index covers it. Inspect the table definition in the DataStore database using the read-only user, so the check itself cannot change data. Confirm the rows return in a stable order when you sort on_id. If the source file carries its own identifier, record it, but page on_idunless that identifier is also unique and indexed. The check passes when the index appears in the table definition and two identical sorted queries return the same first and last rows.Switch the client to an ordered cursor
Change the client so every request sorts by
_idascending and passes the last_idfrom the previous page as the lower bound for the next one. Keep the page size below the rows_max cap so no page exceeds it. Store the cursor after each page so an interrupted crawl can resume from it. Ask the client developers to confirm the filter syntax your DataStore version accepts for a range on_id, and whether include_next_page can supply the cursor for your client. The step is done when the client sends no offset for this resource and its unit tests cover the cursor handoff.Run a full crawl of a sample resource
Pick a sample resource with a known record count, large enough to need several pages at your chosen page size. Crawl it end to end with the new client and log the page count, the first and last
_idvalues, and the total records returned. Repeat the crawl and confirm the totals and order match. Confirm where your CKAN version shows the record count for the resource. The check passes when the crawl total equals that count. A mismatch means the cursor skipped or repeated rows, so fix the cursor logic before moving on.Compare crawl output with the source file
Count the rows in the original upload, such as the CSV or spreadsheet the resource was loaded from, and compare that count with the crawl total. Spot-check the first and last rows of several pages against the source, paying attention to rows at page boundaries, where cursor errors tend to appear. Confirm that repeated values in the data cannot cause the client to drop rows, because the cursor relies only on
_id. The step is done when the counts match and each sampled boundary row matches its source row.Record the setup and retest after upgrades
Write down the CKAN and DataStore versions, the rows_max value, the index on
_id, and the cursor logic in your runbook. Rerun the full crawl on the sample resource after every CKAN upgrade, after a loader change, and after any change to rows_max, then compare the totals with the resource metadata again. Read the CKAN release notes for the target version before upgrading, since minor releases can include backwards-incompatible changes. The step is done when the runbook entry exists and the crawl passes on the upgraded site.
Choosing a paging approach for each client type
Dashboard and web page builders usually need a small, fixed number of rows per view, plus a count for a pager or summary. Use datastore_search with a limit that matches what the page displays, and request a total only where the interface shows one, because counting a large filtered table costs more than returning one page. Offset paging is workable while the page stays shallow, since most users never go far past the first few pages.
- Page size: Keep
limitsmall enough to render quickly, and treat the row cap as an upper bound only. - Offset paging for shallow views:
offsetworks for the first few pages of a view. Past roughly 500k records, deep offsets slow down, so do not expose links to page 10,000 or beyond. - Totals: Cache a total for a short period if the data changes slowly, and drop it entirely if the page does not display it.
- Filters and sorting first: Push filters and sort order into the query so the page does not step through rows the user never sees.
- Full export links: A "download all" link should point to the dump endpoint for that resource, not to a paged loop in the page code.
Check that your CKAN version supports the filters you plan to use, and confirm the deepest page your users will reach before you choose offset paging.
Mobile and application developers usually keep a local copy and need to fetch only what changed since the last sync. Use keyset pagination on _id: sort by _id, read a batch, and start the next request after the last _id you stored. Each request then costs about the same regardless of how far into the table the sync has gone, and the client avoids replaying the whole table on every run.
- Keyset on
_id: Resume after the last stored value. Confirm which range condition your CKAN version and portal allow, either through filters or throughdatastore_search_sqlwhere that is enabled. - Batch size: Choose a batch size that suits mobile networks and the row cap on your portal, and retry a failed batch from the same starting point.
- Stop signal: Use
include_next_pagewhere your CKAN version returns it, so the client knows when to stop instead of guessing from a short batch. - Updated rows: Rows changed in place keep their
_id, so they will not appear as new rows in a keyset walk. Ask the publisher whether the table is upserted, reloaded or appended, and read the sibling topic ondatastore_upsertbefore you design the sync. - Full resync: When a local copy is far behind or the schema changes, switch to a full download instead of replaying thousands of batches.
Ask the portal team how the publisher changes rows, then test your sync against a table that receives updates during the test.
Analysts, researchers and other bulk consumers usually want every row in a table, not a view of it. Send them to the dump endpoint for the resource, which returns the complete table as a file in a format they choose, instead of paging through the Data API. The dump endpoint has its own behavior, separate from API queries, so confirm it on your version before you promise a complete export.
- Dump endpoint: Point users to the dump endpoint for the resource to get the full table as CSV, TSV, JSON or XML.
- Spreadsheet opening: Use the
bomoption in the downloads topic when analysts open CSV files in Excel. - Subsets: For one region, one date range or another slice, use a filtered query and keep the full download for complete tables.
- Large tables: Check file size and download time before you share a link in a scripted loop, and confirm whether your proxy or timeout settings affect large exports.
- Access: Confirm that the resource is public or that the analyst holds the right permissions, since private resources need credentials.
Confirm with the portal team which download formats are enabled and whether large exports need a longer proxy timeout on your deployment.
Security and operational risks of large row queries
Large tables create risks that small datasets hide: one heavy query can slow the database for every user, and a crawl can return inconsistent pages. Each card names a risk, the control to put in place, and what to confirm in your own environment before you open the table to users.
Unbounded queries slow other users
A query with no row cap or tight filter can scan a large table and hold database resources while other users wait. The main control is the row cap set by rows_max, which limits how many rows one search returns, combined with keyset pagination so clients never request deep offsets. Confirm the value of ckan.datastore.search.rows_max in your configuration, then test a deep paging request against your largest table before you publish it.
Public access without caps
Open data portals usually allow anonymous API calls, so one client can send thousands of requests against the same table. Plan rate limits and request size caps at the reverse proxy or API gateway in front of the portal, and confirm that the proxy enforces them rather than assuming the portal does. Also confirm which DataStore endpoints are reachable without a token, and whether datastore_search_sql is enabled on public resources.
Read-only user as the write-safe path
The DataStore keeps a read-only user alongside a write user in its own PostgreSQL database. Public queries and any tooling that reads rows should connect only as the read-only user, so a bug or injected query cannot change table contents. Keep write credentials on the loader and CKAN backend only, and keep them out of crawler configurations and client-side scripts. Confirm that ckan datastore set-permissions has run for your database and that an insert attempted as the read-only role fails in a test table.
Cursor values exposed to clients
Keyset pagination returns a row identifier that tells the client where the next page starts, so the cursor reveals row position in the table. Treat the cursor as a paging token that carries no permission. A client who crafts a cursor should still receive only the rows that resource permissions allow. Confirm that private datasets and resources return no rows or cursors to callers without access, and that responses expose no internal fields you did not intend to publish.
Data changes during a crawl
A client that pages through a table while a loader replaces or upserts rows can see duplicates or gaps, because rows it already read may have moved or changed. Pick one publishing pattern: load the table completely before opening it to crawlers, or record the resource's last modified time at the start of a crawl and restart the crawl whenever that time changes. Confirm how your team publishes updates, whether a full reload reassigns _id values, and how crawlers detect a change.
Slow query logging and monitoring
Without logs, a slow table appears only as complaints from users. Enable slow statement logging on the DataStore database with log_min_duration_statement, set to a threshold your team chooses, and review those entries alongside web server request logs so a slow statement can be matched to the resource that caused it. Confirm where these logs are stored, how long they are kept, and who is alerted when a query crosses the threshold.
What buyers ask before paying for large-table paging work
How much does large-table paging work cost for a CKAN portal?
Cost follows the written scope, and DeployOpen does not publish a price list, so the quote is built from the deliverables you agree before work starts. The main cost components are the build work (query design, index review, client changes and testing), the effort for each consumer that must move to the new paging method, and the time your own team spends reviewing and approving changes. Table size and the number of consumers both shape the total. Retainers for upgrades, support and continuous testing are priced separately from the one-time build, so ask which items recur. Ask the quote to list each deliverable, the consumers in scope, the environments touched and which items are one-time and which recur.
What drives the effort for paging a large CKAN DataStore table?
Five factors drive the effort most: table size, the number of consumers that read the table, how many of those clients you can change, index work, and testing. Row count matters because offset paging slows down as the offset grows, and the slowdown becomes noticeable beyond roughly 500,000 records, so tables near that size need a different query shape. Each consumer adds work because each client needs new paging logic, its own tests and a cutover plan. Index work grows with the number of query patterns you keep. Testing effort rises with the number of environments and clients, and with how much you must prove about page completeness. Ask the written scope to split the effort across these five factors.
How long does keyset pagination work take to deliver?
Duration depends on scope and environment, and no single timeline fits every portal. The main variables are how many consumers change, whether a staging copy of the DataStore exists and matches production, how quickly your team reviews changes, and whether the portal configuration can be changed in an agreed window. A portal with one consumer and a ready staging copy is a very different job from a portal with many external API clients that need coordinated cutovers. Ask for a timeline in the written scope that lists milestones, dependencies on your team, the staging readiness check and the cutover window, and state which dates depend on your approvals.
What does our team need to provide for this work?
You need a named owner who makes scope decisions, approves changes and receives findings. You also need access to a staging copy of the DataStore database and the resource it holds, so paging can be tested against large row counts without touching live data. Access to the portal configuration is required to review the rows_max setting and any CKAN configuration keys that affect the Data API. For external consumers, you need a named contact for each client so cutover can be coordinated. Ask the written scope to name these roles, the expected response times for approvals, and what happens to the timeline when a dependency is late.
Can our own developers implement keyset pagination in CKAN?
Yes, an internal team with CKAN and PostgreSQL experience can do this work. The questions to answer honestly are whether anyone has run keyset queries against a large PostgreSQL table, whether the team can test against a staging copy, and whether it can change each consuming client. Your team also needs to own the testing of page completeness, including the boundary between pages and rows that change while a client is paging. If those skills are present, the work is mainly careful planning and disciplined testing. If they are not, a partner scope can cover the build, the tests and the handover documentation. Ask for a skills check in the written scope before deciding.
What changes for API clients after keyset pagination goes live?
After go-live, API clients page by the last _id value they received instead of by an offset, and they read the next-page signal from include_next_page to know when to stop. Client code, internal documentation and any saved links change, so each consumer needs a cutover date. If the rollout keeps both methods for a period, the transition window must be written down, along with what happens when it ends. Your team owns monitoring of query times, error rates and client complaints in the first weeks, and owns later decisions about the row cap. Ongoing support, upgrades and continuous testing are available as retainers, which cover CKAN upgrades that could change Data API behavior.
What breaks if we change the rows_max limit on a live portal?
Changing rows_max changes the largest page a Data API query can return, so clients that expect a certain page size or that loop until they get an empty result may behave differently. The default is 32000. Full table downloads use a separate path with its own limits, so test both. Lowering the cap can stop large queries that users or clients relied on. Raising it can increase memory use and query time on the database and web workers. Test the change on a staging copy with your largest table, watch database load during the first traffic, and record the previous value so you can roll back. The DataStore documentation is the natural starting point to confirm current behavior.
Limits to confirm in your CKAN environment
Every design choice in this topic depends on how your CKAN version and hosting setup behave, so confirm these six items before you write crawler or client code. Each card names the check and how to run it: read the documentation for your version, test on a staging copy of a large table, or ask the vendor or hosting provider. Record the answers beside the design so the team can recheck them after each upgrade or table reload.
Row cap and default
The rows_max setting caps how many rows one Data API request can return. Confirm the value your instance actually runs with in the documentation for your version, then check which endpoints it governs, since search, SQL and full downloads are handled differently. On a staging copy, request more rows than the cap and read the response to see how the truncation is reported. Your batch size and crawl count depend on this number, so record it before you choose a page size.
include_next_page behavior
Client code that pages through a table relies on the API to signal whether more rows exist. Confirm in the documentation for your CKAN version that include_next_page is available, and whether the response returns a link or only a flag. Then call the endpoint on a staging table and read the raw response on the last page. Do not end a crawl on an empty page alone until you have seen how the API reports the final page.
_id present and indexed
Keyset pagination orders and filters on the _id column, so each large table needs that column present and indexed. Check the column list for every table you plan to crawl, because tables loaded at different times may not match. On a staging copy, run a query sorted by _id and compare its timing with an unfiltered query on the same table. Note any table without the column before you commit to a keyset design, since that table will need a different cursor.
Concurrent reader load
A crawl running beside other readers shares application workers and database connections with your portal visitors. Ask your hosting provider how many workers and database connections the Data API can use, and whether a request rate limit applies at the load balancer or CDN. Then run several parallel readers against a staging copy of your largest table and watch response times and errors. Use the results to set how many crawlers run at once and when they should back off.
_id after table reloads
A saved cursor is only useful if _id values stay stable after the table changes. Confirm with your loader and reload procedure whether a reload keeps existing _id values or assigns new ones. Test this on a staging copy: record _id values and a sample of row contents, reload the resource, then compare both. If the values change, a client that stores a last _id can skip or repeat rows after each reload, so plan a restart point for every reload.
Proxy and gateway timeouts
A long crawl holds an HTTP connection open for each request, and any proxy in front of CKAN can close it. Check the read and idle timeouts on your reverse proxy, your load balancer and any API gateway, and confirm the values in each live configuration file. Then run a crawl on staging through the same path your users take, and note which request fails when a timeout is reached. The shortest timeout in the chain sets the largest page you can safely request.
How DeployOpen scopes and delivers large-table DataStore work
DeployOpen treats large DataStore tables as a combined design and operations task that covers row caps, pagination contracts, client behavior and database load. Every engagement starts with a written scope, and we build, test and document the setup inside your own infrastructure so your team can review and run it.
How we scope
- The written scope lists the large tables, their row volumes and the API endpoints that serve them.
- Pagination method is agreed for each client: keyset on
_id, offset, or a documented export path for full downloads. - Deliverables and timelines are agreed in writing before work starts, and ongoing support is available as a retainer.
How we build
- Keyset pagination on
_idis designed into client queries and tested against the full table. - Row caps, timeouts and the read-only DataStore user are configured and checked in your environment.
- Setup follows the CKAN DataStore documentation for the CKAN version in use.
How we hand over
- Handover includes the pagination contract for API clients, with example requests and
include_next_pagebehavior documented. - Runbooks cover row cap changes, index maintenance and what to check when a client reports missing rows.
- Your team receives configuration, test results and documentation in a form your compliance and security reviewers can read.
How we support
- Ongoing support can cover upgrades of CKAN, PostgreSQL and the DataStore setup as those components change.
- Retainers can include continuous testing of API limits and query behavior as tables grow.
- Changes to row caps or pagination are agreed in writing and retested before they reach production.

