A feed works perfectly in development. In production, a customer switches workspace, scrolls to the second page, and sees an article that belongs to the account they just left.
Every row involved exists. The SQL is valid. The rows decode into Swift without an error. The query is still wrong, because somewhere between the scroll gesture and the WHERE clause the request stopped meaning what the product promised.
iOS engineers tend to treat the database as the backend's problem and the JSON as the contract. I think that undersells our side of it. The app decides when to ask for the next page, which cursor to send, what to do when the workspace changes mid-request, and how to interpret an empty result. Those decisions are half of the query. This post follows one feed from the Swift model to the index, and marks the places where its meaning usually leaks.
Write the promise before the query
"The latest published articles in the current workspace" sounds complete. It leaves at least six questions open, so I answer them in writing first:
- Only articles the authenticated reader is allowed to see.
- Newest publication time first.
- Articles with the same publication time ordered by ID, so the order is total.
- At most 30 per page.
- A cursor is valid for one workspace and one filter configuration.
- Paging continues an ordered query. It does not promise a frozen snapshot of the past.
The last line is a product decision with engineering consequences. An infinite feed can tolerate an article disappearing between pages. A financial export cannot, and needs a different mechanism entirely.
The Swift side carries the same promise in its types:
import Foundation
struct ArticleSummary: Identifiable, Equatable, Sendable {
let id: UUID
let title: String
let publishedAt: Date
}
struct ArticlePage: Sendable {
let articles: [ArticleSummary]
let nextCursor: String?
}
struct FeedScope: Hashable, Sendable {
let workspaceID: UUID
let filter: String
}ArticleSummary holds what the list needs and nothing about storage. nextCursor is an opaque String on purpose; the client forwards it and never looks inside. FeedScope names the thing a cursor belongs to. That third type is the one missing from the app in the opening story.
Why OFFSET cannot keep the promise
The first implementation of most feeds is LIMIT 30 OFFSET 30. It fails in two independent ways.
It is unstable. Offset means "skip however many rows currently sort first". If one new article is published while the reader is on page one, every row shifts down by one, and page two begins with the last article of page one. If one is deleted, an article is silently skipped. On a busy feed, duplicates in a list are almost always this.
It also gets slower with depth. The database has to produce and discard every skipped row, so page 200 costs roughly 200 times page one.
Ordering is part of correctness
The first page, in PostgreSQL:
SELECT id, title, published_at
FROM articles
WHERE workspace_id = $1
AND status = 'published'
ORDER BY published_at DESC, id DESC
LIMIT $2;Values are bound as parameters by the driver. A workspace ID or a limit is never interpolated into the SQL text, including in the "internal" admin tool.
The id in ORDER BY is a tie-breaker. It says nothing about creation order; its only job is to make the ordering total. Bulk imports and scheduled publishing produce many rows with an identical published_at, and without the tie-breaker the database may return those rows in a different order on each execution. PostgreSQL's documentation is explicit that LIMIT without a fully determined ORDER BY gives an unpredictable subset. "Next page" has no meaning until the order is total.
A cursor is a position inside a scope
For the following pages:
SELECT id, title, published_at
FROM articles
WHERE workspace_id = $1
AND status = 'published'
AND (published_at, id) < ($2, $3)
ORDER BY published_at DESC, id DESC
LIMIT $4;This is keyset pagination. (published_at, id) < ($2, $3) is a row-value comparison: it is true when published_at is earlier, or when it is equal and id is smaller, which is exactly "after the last row I returned" in this ordering. It assumes published_at is never null for published rows; add a CHECK constraint so that assumption is enforced by the database and not by convention.
Ask for limit + 1 rows. If the extra row comes back there is another page; return only limit rows and build the cursor from the last one returned. A full page by itself does not prove more rows exist, and guessing produces the empty "last page" that users notice.
The cursor has to carry more than the position. On the server I model its payload like this:
import CryptoKit
struct FeedCursorPayload: Codable, Equatable, Sendable {
let version: Int
let workspaceID: UUID
let filter: String
let publishedAtMicroseconds: Int64
let id: UUID
}
enum CursorError: Error, Equatable {
case malformed, tampered, wrongScope
}
struct CursorCodec: Sendable {
let key: SymmetricKey
func encode(_ payload: FeedCursorPayload) throws -> String {
let body = try JSONEncoder().encode(payload)
let mac = HMAC<SHA256>.authenticationCode(for: body, using: key)
return (body + Data(mac)).base64EncodedString()
}
func decode(_ cursor: String, for scope: FeedScope) throws -> FeedCursorPayload {
guard let raw = Data(base64Encoded: cursor),
raw.count > SHA256.byteCount else {
throw CursorError.malformed
}
let body = raw.dropLast(SHA256.byteCount)
let mac = raw.suffix(SHA256.byteCount)
guard HMAC<SHA256>.isValidAuthenticationCode(
mac, authenticating: body, using: key
) else {
throw CursorError.tampered
}
guard let payload = try? JSONDecoder().decode(
FeedCursorPayload.self, from: body
) else {
throw CursorError.malformed
}
guard payload.version == 1,
payload.workspaceID == scope.workspaceID,
payload.filter == scope.filter else {
throw CursorError.wrongScope
}
return payload
}
}Three decisions in that code are worth explaining.
The scope is inside the cursor and checked against the request. A cursor minted for workspace A, presented with a request for workspace B, is rejected with wrongScope. Without that check, the position from A is applied to B's rows and the feed continues from an arbitrary point.
The signature detects tampering and grants nothing. The HMAC proves the server produced these bytes. It says nothing about whether the caller may read workspace B today. The server still derives the caller's identity from the session and checks membership on every request; the workspace_id = $1 parameter comes from that check, never from the cursor.
The timestamp is an integer count of microseconds. PostgreSQL's timestamptz has microsecond resolution. A Swift Date round-tripped through ISO 8601 with milliseconds, or through a Double of seconds, comes back slightly different from the stored value. The comparison published_at < $2 then lands a fraction of a millisecond away from the real boundary, and rows sharing that millisecond are skipped or repeated. Building the cursor from the database's own value, at its full precision, removes the problem. It is also the practical reason the client must treat the cursor as opaque: the moment the app reconstructs it from articles.last?.publishedAt, the precision is gone.
The half of the query that lives in the app
The server can reject a cursor from the wrong workspace. It cannot stop the app from appending a late response to the wrong list. That part is ours:
import Observation
protocol ArticleFeedFetching: Sendable {
func page(
scope: FeedScope, after cursor: String?, limit: Int
) async throws -> ArticlePage
}
@MainActor
@Observable
final class FeedModel {
private(set) var articles: [ArticleSummary] = []
private(set) var reachedEnd = false
private(set) var needsRestart = false
private let fetcher: any ArticleFeedFetching
private var scope: FeedScope
private var cursor: String?
private var generation = 0
private var isLoading = false
init(scope: FeedScope, fetcher: any ArticleFeedFetching) {
self.scope = scope
self.fetcher = fetcher
}
func switchScope(to newScope: FeedScope) {
guard newScope != scope else { return }
generation += 1
scope = newScope
cursor = nil
articles = []
reachedEnd = false
needsRestart = false
isLoading = false
}
func loadNextPage() async {
guard !isLoading, !reachedEnd else { return }
isLoading = true
let requested = generation
do {
let page = try await fetcher.page(
scope: scope, after: cursor, limit: 30
)
guard requested == generation else { return }
var known = Set(articles.map(\.id))
for article in page.articles
where known.insert(article.id).inserted {
articles.append(article)
}
cursor = page.nextCursor
reachedEnd = page.nextCursor == nil
} catch {
guard requested == generation else { return }
needsRestart = true
}
isLoading = false
}
}Switching workspace bumps a generation and discards the cursor together with the rows, in one synchronous step. A response that was requested under the previous generation is dropped when it arrives. That check is what the app in the opening story lacked: it kept the cursor in a property that outlived the workspace change, or it appended whatever page came back.
The known filter is there because of the "not a snapshot" clause. An article whose publication time is edited can legitimately appear again on a later page. ForEach over duplicate IDs is undefined behavior in SwiftUI, so the model removes duplicates at the boundary instead of trusting the feed to be a set.
Keyset pagination does not freeze the data
A new article published above the cursor does not disturb the next page, which is the main advantage over offsets. Everything else can still change between requests: rows are deleted, a publication time is corrected, an article is unpublished, the reader loses access to a folder.
If the product needs a reproducible result (an export, an audit, a report someone will sign), build it as one: materialize an export dataset, or record an explicit version boundary the query can filter on. Holding a database transaction open while a person scrolls is not an option; it pins old row versions and connections for as long as the phone stays in a pocket.
Isolation levels do not help across requests either. In PostgreSQL, Read Committed takes a new snapshot for every statement and Repeatable Read holds one for the transaction. Two HTTP requests are two transactions.
An index for the query you actually run
A candidate index for this feed:
CREATE INDEX articles_published_feed
ON articles (workspace_id, published_at DESC, id DESC)
WHERE status = 'published';The column order mirrors the query: equality on workspace_id first, then the two sort keys in the same direction as the ORDER BY. With it, the database can walk the index from the cursor position and stop after 31 entries.
I call it a candidate because an index is a hypothesis until the plan confirms it. Run EXPLAIN (ANALYZE, BUFFERS) on realistic data and look for three things: an index scan on articles_published_feed, no separate Sort node, and a rows-removed-by-filter count near zero. A partial index is only used when the planner can prove the query's predicate implies the index's, so status = 'published' must appear in the query as written, not as a bound parameter the planner cannot see through.
Test with production-shaped data. A workspace with 40 articles and one with four million behave differently, and the planner may choose a different plan for each. Every index also costs storage and slows every write to the table. "The query uses an index" is not an acceptance criterion; "page latency at the 95th percentile for the largest workspace" is.
NULL is a third truth value
A missing subtitle, an unknown publication time, and an empty title are three different facts. Swift can say so:
struct DraftSummary: Sendable {
let id: UUID
let title: String
let publishedAt: Date?
}SQL can as well, with rules that surprise people who think of NULL as "empty". Any comparison with NULL evaluates to unknown, and WHERE keeps only rows where the condition is true. So published_at = NULL matches nothing, ever; the test is IS NULL. The more expensive version of the same trap is id NOT IN (subquery): if the subquery returns a single NULL, the whole predicate is unknown for every row and the result is empty. Use NOT EXISTS.
On the Swift side, resist row.subtitle ?? "" in the mapper. It converts "we don't know" into "we know it is blank", and every rule written afterwards has to guess which one it is looking at.
Transactions keep related writes together
Publishing an article updates its row and records that downstream systems (search, notifications, the feed cache) must be told. Those two writes are one domain event. If the update commits and the notification record is lost, the article is published and nobody finds out.
Both go in one transaction: the status change and an outbox row. A separate worker delivers outbox rows with retries, and consumers deduplicate by event ID. The transaction does not make delivery happen exactly once. It makes the decision and the obligation to announce it atomic, which is the part a database can actually guarantee.
For edits, optimistic concurrency fits in the WHERE clause:
UPDATE articles
SET title = $1, revision = revision + 1
WHERE workspace_id = $2
AND id = $3
AND revision = $4
RETURNING revision;Zero rows returned means the update did not apply. Whether the API reports that as not found, forbidden, or conflict is a policy decision, and the careful answer avoids revealing that a row exists to someone who may not read it.
Tests that challenge the contract
Query behavior has to be tested against the real engine. An in-memory array or a different database will not reproduce PostgreSQL's ordering of equal keys, its NULL semantics, its planner, or its conflict behavior. Start a real instance in a container and test:
- forty rows with an identical
published_at: paging returns each exactly once; - a row inserted above the cursor between pages: no duplicate on the next page;
- a row deleted between pages: no error, no gap beyond the deleted row;
- a cursor from workspace A sent with workspace B: rejected;
- one flipped byte in a cursor: rejected;
- two concurrent edits with the same revision: exactly one succeeds.
Then test the Swift boundary on its own: a late page after switchScope is dropped, a duplicate ID is not appended, a rejected cursor puts the list into a restartable state instead of an endless spinner.
What to ask of your own feed
- Is the
ORDER BYtotal, with a unique tie-breaker? - Does the cursor carry its workspace and filter, and does the server compare them with the request?
- Does the client ever construct or modify a cursor?
- What happens in the app when the scope changes while a page is in flight?
- Has anyone read the query plan against the largest tenant?
Returning rows is the easy part. The work is making sure the request still means, at the WHERE clause, what the reader meant when they scrolled.
References
- PostgreSQL: LIMIT and OFFSET
- PostgreSQL: Row and array comparisons
- PostgreSQL: Transaction isolation
- PostgreSQL: Partial indexes
- PostgreSQL: Using EXPLAIN
- Apple CryptoKit: HMAC
Related editions
- Edition 29 · From Swift to GraphQL: Understanding the Work Behind a Request
- Edition 18 · Your App Is Showing the Truth. Just Not the Current One.
- Edition 17 · The Old Version Is Still Running
If this edition sharpened your next review, you can buy me a coffee.