Tweet Pin Share

Offset vs Cursor Pagination: Where Python API Sync Scripts Lose Records

/ 14 min

Table of Contents

  1. A Zero Exit Code Over a Missing Suppression Entry
  2. LIMIT and OFFSET Against a Table That Keeps Moving
  3. Anchoring Each Page to the Last Row Seen
  4. Where a Plain Keyset Cursor Still Loses Records
  5. A Sync Loop That Re-Reads Its Own Boundary

A Zero Exit Code Over a Missing Suppression Entry

Picture a cron job at 02:00 that pulls bounce logs from a mail relay API into a local database. It requests page after page, parses each JSON payload, writes the batch, and stops when the API hands back an empty data array. The script exits with status 0. Your monitoring stays green.

Three days later a customer complains that your newsletter keeps mailing an address that hard-bounced last week. The bounce exists upstream. It never reached your suppression table.

Nothing crashed. Every HTTP request returned 200, and the page count matched what the API advertised. The script did exactly what it was written to do: walk a list by position while somebody else rearranged that list between requests.

This is the trap. An HTTP 200 and a matching page total tell you that each request succeeded on its own terms. They say nothing about whether the rows on page 3 follow on from the rows on page 2. Row-level continuity is a property of the whole traversal, and no single response can vouch for it.

For anyone running self-hosted email infrastructure or a LEMP application with Python glue scripts, the data you sync is almost never frozen while you read it. Mail relay logs grow every second. Webhook queues get drained and pruned. User directories see sign-ups, deactivations and soft deletes throughout the night. Your nightly job reads a moving target, and the pagination strategy decides whether that motion costs you records.

LIMIT and OFFSET Against a Table That Keeps Moving

Offset pagination is the default on a huge number of APIs because it is easy to build. The client sends a limit and an advancing offset (0, 100, 200) or a page number that the server converts into one. Behind the endpoint, the query usually looks like this:

SELECT id, recipient, status, created_at
FROM bounces
ORDER BY id ASC
LIMIT 100 OFFSET 100;

The database evaluates the ordering, counts 100 positional slots from the top of the current result set, throws those away, and returns the next 100. The key word is current. Every request recounts from the top of whatever the table looks like at that instant. The PostgreSQL LIMIT and OFFSET query execution documentation spells out both halves of the problem: the engine still has to compute and step through the skipped rows, and because each page runs as a separate query, concurrent changes can shift rows across offset boundaries between one request and the next.

LIMIT and OFFSET Against a Table That Keeps Moving

Deleting row 45 while page 1 is still in flight

Your script fetches page 1: rows 1 through 100, ordered by ID. While it writes that batch locally, an upstream cleanup job deletes row 45.

Every row after 45 moves up one slot. Former row 101 now sits in position 100. Your script asks for OFFSET 100, and the database skips positions 1 to 100, which now include former row 101. Page 2 begins at former row 102.

Row 101 never appears in any response. No error, no warning, no gap visible in the payload. It is simply gone from this run, and if the next run starts from scratch with the same race, it can vanish again.

A fresh insert at the top of a descending feed

The opposite failure shows up on feeds sorted newest first, which is how most event and log APIs present data:

SELECT id, event_type, created_at
FROM webhook_events
ORDER BY created_at DESC
LIMIT 100 OFFSET 100;

You fetch page 1. Before page 2 is requested, a new webhook arrives and lands at position 1. Everything shifts down. The row that was at position 100 is now at 101, so OFFSET 100 returns it again as the first item on page 2.

Duplicates sound harmless next to missing data, but they inflate counters, double-charge billing events and fire downstream notifications twice if your local writes are plain inserts. On a busy relay the drift compounds: each new arrival during the run pushes the window further.

Watch the Retention Cron

The deletes that break offset pagination often come from your own housekeeping. A log-pruning job scheduled for the same hour as the sync is enough to trigger the backward shift every single night.

Anchoring Each Page to the Last Row Seen

Keyset pagination swaps the position counter for a value taken from the data itself. The client reads the identifier of the last record in the current batch and sends it back as a cursor. The server turns that cursor into a range predicate:

SELECT id, recipient, status, created_at
FROM bounces
WHERE id > :last_seen_id
ORDER BY id ASC
LIMIT 100;

Now the question each request asks is "give me the next 100 rows after ID 9184", and the answer depends only on rows whose IDs exceed 9184. If row 45 disappears, it changes nothing about which rows lie beyond the anchor. If a new row arrives with a higher ID, it lands ahead of the cursor and gets picked up in order. Mutations behind the cursor stop leaking into the traversal.

On the Python side, the loop becomes a generator that stops when the API returns a null next_cursor or an empty record list:

def iter_bounces(session, base_url, page_size=100):
    cursor = None
    while True:
        params = {"limit": page_size}
        if cursor is not None:
            params["cursor"] = cursor
        resp = session.get(base_url, params=params, timeout=30)
        resp.raise_for_status()
        body = resp.json()
        records = body.get("data", [])
        if not records:
            return
        yield from records
        cursor = body.get("next_cursor")
        if cursor is None:
            return

Composite cursors for timestamps that collide

Ordering by created_at alone looks natural for event data, and it breaks the moment two records share a timestamp. Mail relays can log several delivery attempts within the same second. If page 1 ends on one of three rows stamped 12:00:05 and the next query asks for created_at > '12:00:05', the other two rows are skipped.

The fix is a tie-breaker: pair the timestamp with the unique ID and compare the tuple.

SELECT id, event_type, created_at
FROM webhook_events
WHERE created_at > :last_ts
   OR (created_at = :last_ts AND id > :last_id)
ORDER BY created_at ASC, id ASC
LIMIT 100;

PostgreSQL also accepts the row-value form WHERE (created_at, id) > (:last_ts, :last_id), which reads more cleanly and lines up with a composite index on (created_at, id). The cursor you hand back to the client is then a pair, usually base64-encoded into an opaque token.

What the storage engine pays at page 5,000

Offset cost grows with depth. To serve OFFSET 500000, the engine walks and discards half a million index entries before returning anything, so late pages of a long history get steadily slower. A keyset seek, given an index on the cursor columns, jumps straight to the anchor and reads forward. Page 5,000 costs about the same as page 1.

For a homelab box or a Raspberry Pi running MariaDB on modest storage, this matters more than on a large cloud instance. A deep offset scan competes with the live application for I/O, and the sync job that used to take minutes stretches as the table grows. The keyset version keeps a flat profile.

The trade-off: keyset pagination gives up random access. You cannot jump to "page 37" without walking there. For a sync job that always reads forward from where it stopped, that loss costs nothing.

Where a Plain Keyset Cursor Still Loses Records

Keyset pagination closes the positional drift problem. It does not close every gap, and the remaining ones are subtler.

Updates that happen behind the cursor

A cursor of id > last_id only ever moves forward through new rows. Suppose row 2210 in your user directory was synced last night as active, and this afternoon an admin flags it suspended. Its ID sits far behind your cursor. Tonight's run never looks at it again, and your local copy keeps believing the account is active.

Append-only ID cursors fit append-only data: raw delivery logs, immutable audit events. On any table where rows change status or receive soft deletes, you need the API to expose a modification timestamp, typically updated_at, and you page on that column (with the ID as a tie-breaker) so edited rows move forward into your next window.

Commits that land out of order

Switching to updated_at introduces a timing problem on any backend with concurrent writers. Many databases and ORMs stamp the timestamp when the statement or transaction starts, while visibility to readers arrives only at commit.

Walk through it. Transaction T1 starts at 10:00:00.100, stamps its row, then waits on a slow lock. Transaction T2 starts at 10:00:00.300, stamps its row, and commits immediately. Your sync runs, sees T2's row, and records 10:00:00.300 as the new high-water mark. A moment later T1 commits. Its row carries 10:00:00.100, which is older than your mark. The next run asks for updated_at > 10:00:00.300 and never sees it.

Multi-worker application tiers make this worse. Several PHP-FPM or Gunicorn workers on separate hosts with slightly unsynchronized clocks can produce timestamps that disagree with commit order by more than a few milliseconds. A cursor that only ever advances to the exact maximum it has seen will drop records whenever commits arrive out of chronological order, and that is the one hard limit worth designing around rather than hoping away.

Clock Drift on the Pi

A Raspberry Pi has no battery-backed real-time clock. If one boots before NTP syncs and starts writing rows, its timestamps can lag badly. Run chrony or systemd-timesyncd and confirm timedatectl reports a synchronized clock before any worker on that board writes cursor-relevant data.

Vendors that only give you page and per_page

Plenty of third-party APIs, including some transactional mail providers and older billing platforms, expose nothing but page and per_page. You cannot add a cursor to someone else's endpoint. At that point the client has to assume drift will happen and defend against it locally: re-read a margin of each boundary, and make every write safe to repeat. The same two techniques also cover the out-of-order commit problem on endpoints that do support cursors, which is why I treat them as the default design for every sync job I write, whatever the upstream pagination looks like.

A Sync Loop That Re-Reads Its Own Boundary

Take a concrete case: replicating bounce records from a mail relay API into a local SQLite database that a Postfix policy service reads for suppression checks. The API supports a cursor on (updated_at, id), with updated_at as integer epoch seconds. The design has three parts.

  1. A persistent checkpoint. The last committed high-water mark lives in a sync_state table, and it advances only inside the same transaction that writes the batch.
  2. A lookback window. Each run starts from the checkpoint minus a fixed buffer, here 60 seconds, so rows that committed late with an older timestamp fall inside the re-read range.
  3. Idempotent writes. Every row goes through INSERT ... ON CONFLICT DO UPDATE, so a record fetched twice overwrites itself instead of appearing twice.
A Sync Loop That Re-Reads Its Own Boundary

The schema first:

CREATE TABLE IF NOT EXISTS bounces (
    id         INTEGER PRIMARY KEY,
    recipient  TEXT NOT NULL,
    status     TEXT NOT NULL,
    updated_at INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS sync_state (
    stream   TEXT PRIMARY KEY,
    last_ts  INTEGER NOT NULL,
    last_id  INTEGER NOT NULL
);

Walking through the loop

import sqlite3
import requests

API_URL = "https://relay.example.internal/api/v1/bounces"
STREAM = "bounces"
LOOKBACK_SECONDS = 60
PAGE_SIZE = 100

UPSERT_SQL = """
INSERT INTO bounces (id, recipient, status, updated_at)
VALUES (:id, :recipient, :status, :updated_at)
ON CONFLICT(id) DO UPDATE SET
    recipient  = excluded.recipient,
    status     = excluded.status,
    updated_at = excluded.updated_at
WHERE excluded.updated_at >= bounces.updated_at
"""

CHECKPOINT_SQL = """
INSERT INTO sync_state (stream, last_ts, last_id)
VALUES (?, ?, ?)
ON CONFLICT(stream) DO UPDATE SET
    last_ts = excluded.last_ts,
    last_id = excluded.last_id
"""

def load_checkpoint(db):
    row = db.execute(
        "SELECT last_ts, last_id FROM sync_state WHERE stream = ?",
        (STREAM,),
    ).fetchone()
    return row if row else (0, 0)

def sync(db_path):
    db = sqlite3.connect(db_path)
    session = requests.Session()

    saved_ts, saved_id = load_checkpoint(db)
    cursor_ts = max(saved_ts - LOOKBACK_SECONDS, 0)
    cursor_id = 0

    while True:
        resp = session.get(
            API_URL,
            params={
                "updated_after": cursor_ts,
                "after_id": cursor_id,
                "limit": PAGE_SIZE,
            },
            timeout=30,
        )
        resp.raise_for_status()
        records = resp.json().get("data", [])
        if not records:
            break

        tail = records[-1]
        cursor_ts, cursor_id = tail["updated_at"], tail["id"]

        with db:  # rows and checkpoint commit together or not at all
            db.executemany(UPSERT_SQL, records)
            if (cursor_ts, cursor_id) > (saved_ts, saved_id):
                db.execute(CHECKPOINT_SQL, (STREAM, cursor_ts, cursor_id))
                saved_ts, saved_id = cursor_ts, cursor_id

        if len(records) < PAGE_SIZE:
            break

    db.close()

A few lines carry most of the weight.

cursor_ts = max(saved_ts - LOOKBACK_SECONDS, 0) is the overlap window. Every run deliberately re-reads the last minute of history. The T1 row from the earlier example, stamped before the old high-water mark but committed after it, now falls inside that range and gets fetched.

The with db: block wraps the upsert batch and the checkpoint update in a single SQLite transaction. If the process dies after writing rows but before saving the checkpoint, both roll back, and the next run re-fetches the same batch. If it dies after the commit, the checkpoint reflects exactly what landed. The checkpoint never runs ahead of the data.

The tuple comparison before the checkpoint write stops the mark from moving backward. During the lookback portion of a run, the cursor sits behind the saved checkpoint, and writing it would rewind your progress.

The WHERE excluded.updated_at >= bounces.updated_at clause on the upsert guards against a stale re-read overwriting a newer local value. PostgreSQL accepts the same ON CONFLICT ... DO UPDATE syntax, so the statement ports directly if the destination moves off SQLite.

The page-only variant for legacy endpoints

When the vendor offers only page and per_page, apply the same idea with a row margin. Persist the last fully committed page number, and start each run one page earlier:

start_page = max(saved_page - 1, 1)

The repeated page catches rows pushed across the boundary by inserts, and the upsert absorbs the duplicates it produces. For the deletion case, a final full pass over the most recent pages on a slower schedule (hourly, say, against a nightly full walk) narrows the window in which a shifted row can hide.

What the overlap costs you

Each run re-fetches one lookback window of records and runs upserts that change nothing for most of them. On SQLite with the primary key as the conflict target, each of those is an index lookup plus a no-op or a single-row update, which a Raspberry Pi 4 on NVMe handles without strain at sync-job volumes. Keep the window proportionate to the commit delays you actually see on the upstream system: 60 seconds covers typical lock waits on a busy LEMP backend, while a minutes-long batch job upstream needs a wider buffer.

Wrap writes in larger transactions rather than committing per row; SQLite's per-commit fsync is the dominant cost on SD cards and slower disks. One transaction per page of 100 keeps write amplification modest and the checkpoint granularity fine enough that a crash loses at most one page of progress.

Completeness Lives in the Commit

A sync run is done when the final batch and its checkpoint commit in the same transaction. Exit code 0 only tells you the process ended.

Comparing the approaches side by side

Pagination strategy comparison for Python synchronization scripts
Pagination method Query anchor Upstream delete Upstream insert (DESC feed) Captures in-place updates Python client mitigation
Offset / page number Row position (OFFSET n) Later rows shift back; a boundary row is skipped Earlier rows shift forward; a boundary row is fetched twice Only if re-walked in full One-page lookback plus idempotent upserts
Keyset on ID id > last_id Unaffected New rows picked up in order No Suitable for append-only data only
Keyset on (updated_at, id) Composite tuple Unaffected (soft deletes appear as updates) New rows picked up in order Yes, except late commits Time-based lookback window
Keyset with overlap and upsert Composite tuple minus buffer Unaffected Unaffected Yes, including late commits within the buffer Checkpoint committed with each batch

Open the sync script that feeds your suppression list or billing table right now: if a row upstream committed thirty seconds late tonight, which line of that script would ever go back and read it?

Rate this article
3

Your Thoughts

Nothing here yet. Add your opinion.

Leave a Comment

Rate this article
3

Stay Updated

No spam. Unsubscribe at any time.

Set your preferences