A million records, 10,000 requests and not one row to lose
Offset pagination makes the server scan nearly the whole table for the last pages, while cursors, keysets and checkpoints keep large pulls fast and free of silent duplicates.
In brief
- Offset is easy to write but slows down at large offsets, and it can duplicate or skip rows if the data changes mid-pull. For large datasets, prefer cursors.
- Always set an explicit limit, sort with a tiebreaker such as id, and stop when the server signals the end; never count pages yourself.
- Save the cursor only after a batch is on disk, and handle HTTP 429. That is what lets a large pull resume without losing rows.
A system with 1,000,000 records, fetched 100 rows a page, takes 10,000 requests. Forget to set limit on an API that defaults to 10 rows, as Stripe does, and that becomes 100,000.
If the API paginates by offset, the last pages are worse still: the server scans past almost a million rows and throws them away just to return the 100 you asked for.
Often the first task an FDE gets at a client is pulling tickets, transactions or messages out of the client’s system to build a pipeline or feed an agent. Everything downstream then rests on this one API-reading loop.
If it silently duplicates five rows, or drops five, every number in the demo is wrong.
This guide builds a Python data puller for the three common pagination styles, with filters, batching, rate-limit handling and checkpoints. You need Python 3, the requests library and a test API key. The code targets a hypothetical API with simplified field names; on a real engagement, swap in the field names from the client’s documentation.
Step 1: Read the docs to find out which kind of API it is
Before writing the loop, answer two questions: how does the API move to the next page, and how do you know the data has run out? The three public APIs below represent the approaches you will meet most often.
| API | How to continue | Page size | Stop signal |
|---|---|---|---|
| Confluence (Atlassian) | Offset with start and limit |
Atlassian recommends always setting limit explicitly |
The response no longer has a next link |
| Stripe | Cursor by object ID, starting_after / ending_before |
limit from 1 to 100, default 10 |
has_more is false |
| Slack | Server-issued cursor | Slack recommends 100 to 200 per call | next_cursor is empty, null or missing |
What all three share is that the server decides when to stop, not the client. That is the first rule: never work out in advance that “there are 50 pages” and loop 50 times.
By the end of this step you should be able to state three things about the client’s API: the name of the parameter that moves to the next page, the maximum limit, and the field that says the data is exhausted.
Step 2: An offset loop with an explicit limit
For a Confluence-style API, the loop follows the next link instead of incrementing start itself. The snippet is simplified: links.next is a placeholder field name, so check it against a real response.
import requests
def iter_offset(session, url, limit=100):
params = {"start": 0, "limit": limit} # always set limit explicitly
while url:
resp = session.get(url, params=params)
resp.raise_for_status()
page = resp.json()
yield from page["results"]
url = page.get("links", {}).get("next") # no next link means no more data
params = None # the next link usually already carries start/limit
Check: print the row count of each page. If every page has exactly 25 rows even though you asked for 100, the server is applying its own cap. That is why Atlassian recommends setting limit, so you know for certain how many results each page holds.
Why does offset break on live data?
Offset has two weaknesses. The obvious one is speed: the larger the offset, the more rows the database has to scan and discard. The more dangerous one is called page drift: new records land in the table while you are paging through it.
Take a ticket feed read newest first. Page 1 returns rows 1 to 100. Meanwhile five new tickets are created, and because they are the newest they jump to the top of the list, pushing every older row down five places.
When you request page 2 with offset 100, the server returns what used to be rows 96 to 195, so five rows come back twice. If records are deleted instead of added, the reverse happens and five rows are skipped.
Step 3: A cursor loop that stops when the server says so
A cursor avoids page drift because it marks “after this record” instead of “after position N”. Stripe uses the ID of the last object on the page as starting_after. The code below follows the Stripe pattern, with items as a placeholder field name.
def iter_cursor(session, url, limit=100):
params = {"limit": limit} # Stripe allows 1-100
while True:
resp = session.get(url, params=params)
resp.raise_for_status()
page = resp.json()
items = page["items"]
yield from items
if not page["has_more"] or not items:
break
params["starting_after"] = items[-1]["id"]
For a Slack-style API, change the stop condition: check whether next_cursor is empty, null or absent, and remember to handle all three cases. Stripe’s client libraries also support auto-pagination. If the client allows them, use them, but still understand the loop underneath so you can debug it when something goes wrong.
Cursors carry their own risk. With seek/keyset-style pagination, if the record used as the anchor is deleted, its ID may no longer be valid and the next request will fail. So log the last cursor whenever an error occurs, and do not log only the HTTP status code.
Step 4: Use filters to narrow what you pull
Do not pull a million rows if you only need last quarter’s data. Filters on time or status cut the scope from the very first request.
If what remains is still large, you can split it yourself into several time windows and run a separate cursor loop for each. That is a way of organizing the work on the client side and has nothing to do with the pagination scheme.
Keyset pagination is a different matter: it uses filter values from the previous page to define the next one. If the client’s API issues no cursor and offers only filtering and sorting, build a keyset yourself by taking created_at and id from the last row of the page as the condition for the next request.
Either way, the sort order must be stable. Sorting by created_at alone is not enough: two records with the same timestamp can swap places between two requests, and if they sit on a page boundary, one row is duplicated and the other is missed. Add id as a secondary key so two rows can never tie.
Two more details routinely eat an afternoon. Arrays are not passed in queries consistently: according to the OpenAPI guidance, the form style can be either ?color=blue,green,red or ?color=blue&color=green, so check which form the client’s API expects. And many APIs use a - prefix for descending order, for example sort=-created_at.
params = {
"limit": 100,
"status": "closed,resolved", # or repeat the parameter, depending on the API
"sort": "created_at,id", # ascending, id breaks ties (multi-field syntax is illustrative)
}
Filters and sorting are only fast when there is a database index behind them. If one filter makes every request noticeably slower, ask the client’s engineering team whether that field is indexed before concluding that the API is “slow”.
Step 5: Batches, 429s and checkpoints
Pull enough data and sooner or later you hit a rate limit. A well-behaved API returns HTTP 429 Too Many Requests, and your script must treat that as a signal to wait. The snippet below is a simplified approach with increasing wait times; if the client’s documentation specifies its own retry policy, follow the documentation.
import time, json, os
def get_with_retry(session, url, params, max_tries=6):
for attempt in range(max_tries):
resp = session.get(url, params=params)
if resp.status_code != 429:
resp.raise_for_status()
return resp.json()
time.sleep(2 ** attempt) # wait 1, 2, 4, 8... seconds
raise RuntimeError("Still getting 429 after several attempts")
def save_checkpoint(cursor, path="checkpoint.json"):
with open(path, "w") as f:
json.dump({"cursor": cursor}, f)
def load_checkpoint(path="checkpoint.json"):
if not os.path.exists(path):
return None
with open(path) as f:
return json.load(f).get("cursor")
These two functions only help once they are wired into the cursor loop. The most important rule: save the cursor only after the batch is on disk. If you save the cursor first and the script dies while writing the file, the next run starts after rows that were never written.
def flush(batch, out_dir):
last_id = batch[-1]["id"]
with open(f"{out_dir}/batch_{last_id}.jsonl", "w") as f:
for row in batch:
f.write(json.dumps(row) + "\n")
save_checkpoint(last_id) # save the cursor AFTER the data is fully written
def pull_all(session, url, out_dir, limit=100, batch_size=1000):
params = {"limit": limit}
cursor = load_checkpoint()
if cursor:
params["starting_after"] = cursor # resume from the saved position
batch = []
while True:
page = get_with_retry(session, url, params)
items = page["items"]
batch.extend(items)
if len(batch) >= batch_size:
flush(batch, out_dir)
batch = []
if not page["has_more"] or not items:
break
params["starting_after"] = items[-1]["id"]
if batch:
flush(batch, out_dir)
Say the script dies at request 7,000 of 10,000. The cursor in the file is the last ID of the most recent batch that was fully written, so the next run re-fetches the few pages that never made it to disk and carries on, without starting over and without missing a row.
Naming each file after the batch’s last ID also means a rerun does not overwrite earlier data.
For repeated syncs, check whether the API supports caching with ETag or Last-Modified, so you do not re-pull what has not changed.
Final check: compare the number of unique IDs with the total number of rows written. The two must match. If they do not, you have page drift, an unstable sort order or retries writing duplicates, and you must fix it before handing the data to anyone.
How does this skill show up at a client?
The client will not ask whether you know cursor pagination. They will ask why the dashboard is 312 tickets short of the source system. Whoever can answer that within an hour, because they logged cursors, counted unique IDs and know what page drift is, gets trusted with the next piece of work.
When reading FDE job descriptions, look for requirements about integrating with client systems or building data pipelines from third-party systems: that is where this skill is used every day.
On a CV, instead of writing “API integration”, be specific: how many records you pulled, through which pagination style, how you handled rate limits, and how you verified data integrity.
A small GitHub project that pulls data from Slack or a Stripe sandbox, with checkpoints and a row-count reconciliation step, is more convincing than a generic one-line description.
A script that runs on your laptop is only the starting point. What the client actually checks is whether the row counts match the source system, even after the script was interrupted and rerun at midnight.
Was this article useful?
Thanks for the feedback!
7 sources
- Everything You Need to Know About API Pagination · 2019-10-17
- Pagination in the REST API - Atlassian · 2018-10-02
- Pagination | Stripe API Reference
- Pagination | Slack Developer Docs
- Unlocking the Power of API Pagination: Best Practices and Strategies · 2023-06-06
- How to Implement Filtering and Sorting in REST APIs · 2026-01-26
- Describing Parameters - OpenAPI Guide