Originally published at Shipped Code.
A web frontend is redeployed with the backend, so it always speaks the current API. Mobile apps are builds that sit on phones for months, often on a flaky connection, and good API design for them follows from that. Use cursor pagination for scrolling lists, so new rows don't cause duplicates or gaps. Keep changes additive, version only for breaking changes, and ship a minimum-version check in the first release. Return errors as RFC 9457 Problem Details with a stable code, so the app knows whether to retry, log in again or show a message.
TL;DR checklist
- Lists that scroll use a cursor (
?cursor=…, response hasitemsandnextCursor), backed by an index on the sort key.- Never rename or remove a field an installed app reads. Add optional fields instead, and build the app to ignore unknown ones.
- One major version in the URL (
/v1), bumped only for breaking changes.- A minimum-version check exists before the first public release.
- Errors are
application/problem+jsonwith a stablecode, and the app maps status codes to actions.
What you'll learn:
- why offset paging repeats and skips items on a feed, shown on 6 rows in PostgreSQL;
- how to version an API when old app builds stay installed for months;
- which error status should make the app retry, log in again or show a message.
The examples use a made-up "expense list" API with infinite scroll, newest first. The core path runs through pagination, versioning and errors; the payload section is (Advanced). If you only build the app side, read the "what the app does" notes and the status table.
Example mobile API and its numbers
These numbers are an example estimate for a made-up expense app with 20k daily users. Every assumption is visible, so swap in your own.
dau = 20_000 # daily active users
opens_per_day = 4 # times a user opens the expense list
pages_per_open = 2.5 # first page + some scrolling
peak_factor = 5 # busiest minute vs. the daily average
page_size = 20
item_bytes = 300 # one expense as JSON, uncompressed
per_day = dau * opens_per_day * pages_per_open
avg_rps = per_day / 86_400
print(f"list requests/day: {per_day:,.0f}")
print(f"average req/s : {avg_rps:.1f}")
print(f"peak req/s : {avg_rps * peak_factor:.0f}")
print(f"bytes per page : {page_size * item_bytes:,}")
list requests/day: 200,000
average req/s : 2.3
peak req/s : 12
bytes per page : 6,000
Twelve requests per second at peak won't trouble any database. The hard part is that the phones run several app versions at once, and users scroll while new expenses arrive. The system design pillar does the same kind of estimate for a whole backend.
Pagination: use a cursor for scrolling lists
Offset pagination (?limit=20&offset=40) asks for "rows 41 to 60 of whatever the list looks like right now". On a feed that changes while the user scrolls, "right now" moves. Cursor pagination, also called keyset pagination, asks for "the 20 rows after the last one I saw" instead, so inserts and deletes above the reading position don't shift anything.
You can see the difference with 6 expenses and a page size of 3 in PostgreSQL 17. The user loads page 1, a new expense (id 7, "dinner") arrives, then the app asks for page 2.
SELECT id, note FROM expenses ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 0;
INSERT INTO expenses VALUES (7, '2026-12-03 18:20Z', 'dinner');
SELECT id, note FROM expenses ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3;
id | note
----+-----------
6 | books
5 | coffee
4 | groceries
id | note
----+-----------
4 | groceries
3 | taxi
2 | lunch
"Groceries" shows up twice, because the new row pushed everything down by one. Deletes do the opposite. When I deleted expense 6 instead, page 2 came back as "lunch" and "coffee" only, and "taxi" was never shown.
The keyset version remembers the last row of page 1 (created_at and id of "groceries") and continues from there:
SELECT id, note FROM expenses
WHERE (created_at, id) < ('2026-12-02 19:45Z', 4)
ORDER BY created_at DESC, id DESC LIMIT 3;
id | note
----+--------
3 | taxi
2 | lunch
1 | coffee
The id is in the sort key as a tie-breaker, because 2 expenses can share a timestamp and a row could otherwise fall between 2 pages.
Warning: offset pagination on a feed that receives new items shows duplicates and silently skips items. Users tend to report the duplicates, but a skipped item usually goes unnoticed.
Offset also slows down with depth, because the database still reads every skipped row. On a 1-million-row table indexed on (created_at DESC, id DESC), OFFSET 500000 LIMIT 20 read 500,020 index entries and took 41 ms on my laptop, while the keyset query read 20 rows in 0.03 ms. That was one warm-cache run, so take it as an order of magnitude. The PostgreSQL indexes post shows how to check that your query uses the index.
What the cursor looks like in the response
Encode the sort key into an opaque string, so you can change what's inside later without breaking installed apps:
import base64, json
def encode_cursor(created_at: str, id: int) -> str:
raw = json.dumps({"t": created_at, "id": id}, separators=(",", ":"))
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
def decode_cursor(cursor: str) -> dict:
padded = cursor + "=" * (-len(cursor) % 4)
return json.loads(base64.urlsafe_b64decode(padded))
c = encode_cursor("2026-12-02T19:45:00Z", 4)
print(c)
print(decode_cursor(c))
eyJ0IjoiMjAyNi0xMi0wMlQxOTo0NTowMFoiLCJpZCI6NH0
{'t': '2026-12-02T19:45:00Z', 'id': 4}
Anyone can decode Base64, so treat a cursor as untrusted input. Validate both fields and still filter by the logged-in user, so a hand-edited cursor stays inside that user's rows. The response looks like this:
{
"items": [
{ "id": 6, "createdAt": "2026-12-03T13:00:00Z", "note": "books", "amountMinor": 2450, "currency": "EUR" }
],
"nextCursor": "eyJ0IjoiMjAyNi0xMi0wMlQxOTo0NTowMFoiLCJpZCI6NH0"
}
nextCursor is null on the last page. Skip the total count unless the screen shows it, because COUNT(*) on a large table costs more than the page.
What the app does. On Android, a Paging 3 PagingSource takes the cursor as its key and returns nextCursor as the next key. In Flutter, a ListView.builder that requests the next page near the end does the same. Pull-to-refresh drops the cursor and loads page 1.
Cursors can't jump to page 7. For an admin table with page numbers, offset is fine.
Versioning for apps you can't force-update
Most API changes need no new version. A new optional field, endpoint or enum value is free if the app was built to tolerate it. The JSON parser must ignore unknown fields (ignoreUnknownKeys = true in kotlinx.serialization), and an unknown enum value must map to an "other" case instead of crashing. If version 1.0 chokes on a field it has never seen, every later addition becomes a breaking change.
Warning: renaming or removing a JSON field breaks every installed version that reads it. Changing a field's type or meaning (
amountfrom euros to cents) is the same break, only quieter. Add the new field, keep the old one, and remove it only when no supported app version reads it.
A breaking change gets a new major version. You can carry the version in the URL (/v1/expenses), in a header (API-Version: 2) or in the media type (Accept: application/vnd.example.v2+json). For a mobile backend I'd use the URL. It shows up in every access log, a gateway can route /v2 with one rule, and curl needs no extra header. Header versioning keeps URLs clean, which suits a public API with many integrators better.
If the backend is Spring, Framework 7 (Spring Boot 4) has built-in API versioning. You choose where the version comes from in configureApiVersioning (header, query parameter, path segment or media type parameter), and controller methods declare @GetMapping(version = "1.2") or "1.2+" for "this version and later". By default a request without a version is rejected with 400. If your first app release sent no version, set a default version before turning the feature on, or that release breaks.
Minimum supported version and the update screen
Sooner or later an old version has to stop working, after a security fix or a removed endpoint. You can only enforce that if the app already knows how to ask, so the check belongs in version 1.0. The simplest form is a config endpoint the app calls at startup:
{
"minSupportedVersion": "2.0.0",
"latestVersion": "3.0.0"
}
Below minSupportedVersion, the app shows a blocking screen with a store link. Below latestVersion, it shows a dismissible "update available" banner, which moves many users before you need the hard block. I'd keep the previous major API version running until its traffic share drops below a threshold you pick from your own analytics, so log the app version on every request.
Some APIs answer old apps with 426 Upgrade Required. RFC 9110 defines 426 for switching protocols, with an Upgrade header, so I'd rather return a normal Problem Details error with a code like APP_UPDATE_REQUIRED and let the app show the same update screen.
To announce that a whole API version is going away, send the Deprecation header (RFC 9745, a Proposed Standard since March 2025) and a Sunset header (RFC 8594) with the shutdown date. The two use different date formats, which is easy to get wrong. Here /v1 is deprecated from the end of 2026 and shuts down 6 months later:
Deprecation: @1798761599
Sunset: Wed, 30 Jun 2027 23:59:59 GMT
In Spring, you configure StandardApiVersionDeprecationHandler with these dates per version, and it adds both headers.
Errors the app can act on
An English message tells the user what went wrong, but the app needs a value it can branch on. RFC 9457 Problem Details gives errors a standard JSON shape with the application/problem+json media type. Extra members are allowed, so add a stable code and field errors:
{
"type": "https://api.example.com/problems/validation",
"title": "Request has invalid fields",
"status": 422,
"detail": "2 fields are invalid.",
"code": "VALIDATION_FAILED",
"errors": [
{ "field": "amountMinor", "code": "MUST_BE_POSITIVE" },
{ "field": "currency", "code": "UNSUPPORTED_CURRENCY" }
]
}
The app branches on code (or type), never on title or detail, which are for humans and will get reworded. Field errors carry codes too, so the app can show its own localized text next to the right input. The ProblemDetail post for Spring Boot builds this format with Bean Validation.
Here is how I'd map statuses to app behaviour:
| Status | Meaning | What the app does |
|---|---|---|
| 400 | Malformed request | Log it as a bug; show a generic message |
| 401 | Missing or expired token | Refresh the token once (one refresh shared by parallel requests) and retry; if refresh fails, go to login |
| 403 | Logged in, not allowed | Show the reason from code (plan limit, banned); don't retry |
| 404 | Resource gone | Remove it from local state; show "no longer available" |
| 409 | Conflict with current state | Reload the item, then let the user decide |
| 422 | Validation failed | Show field errors next to the inputs |
| 429 | Rate limited | Wait for Retry-After, then retry |
| 5xx | Server or gateway failure | Retry with backoff for safe or idempotent requests; otherwise ask the user |
Be careful with retries on 5xx. Retrying a GET is safe. Retrying a POST /expenses after a timeout can create 2 expenses, because the first request may have succeeded and only the response got lost. An idempotency key makes that retry safe; the idempotency keys post covers it, and token refresh gets its own JWT post.
Payloads and caching (Advanced)
You can skip this on a first read.
A screen that needs 5 calls is slow on a mobile network, since every round trip costs latency. A screen-shaped endpoint (GET /v1/home) fixes that, but couples the API to one layout, which hurts when 2 app versions draw the screen differently. GraphQL starts to pay off once many clients need many screen endpoints; for one app and one backend, REST with a few includes is usually enough.
The estimate assumed 300 bytes per expense. When I generated 20 sample items with a category object and a receipt URL, the whole response came to 4,733 bytes (about 236 per item) and gzip shrank it to 607. Generated data with repeated values compresses unusually well, so expect less on real data, but gzip is still the cheapest bandwidth win.
ETag with If-None-Match (conditional requests in RFC 9110) returns an empty 304 Not Modified when nothing changed. It pays off for config or categories, which the app refetches often and which rarely change.
Send timestamps as ISO 8601 in UTC (2026-12-03T13:00:00Z) and money as integer minor units plus a currency, or as a decimal string. Never send money as a float.
Trade-offs at a glance
| Decision | Option A | Option B | Pick when |
|---|---|---|---|
| Pagination | Cursor (keyset) | Offset with page numbers | Cursor for any scrolling list; offset for admin tables that need "page 7 of 40" |
| Version location | URL /v1
|
Header or media type | URL for your own app's backend; header for public APIs with many integrators |
| Breaking changes | New major version | Add a field, deprecate the old one | Add a field whenever you can; new version only when the shape must change |
| Old apps | Soft update banner | Hard block via minimum version | Soft first; hard block for security fixes or removed endpoints |
| Screen data | Screen-shaped endpoint | Generic resources + include
|
Screen endpoint for a few hot screens; generic for everything else |
What I would choose today
For a new app backend, I'd start with cursor pagination on every scrolling list, a single /v1 in the URL, and Problem Details with a code for every error. The minimum-version endpoint would go into the first build, along with logging app version and platform on every request, so you know later when an old version can be retired. I build both the app and the backend on my own projects (Mockly is a Flutter app with a Flask and MySQL backend), and a contract like this is far easier to settle before release than to retrofit.
What I'd postpone is versioning machinery beyond /v1, GraphQL, and screen-shaped endpoints. Add them when a real breaking change or a measured slow screen asks for them.
Lost responses lead to the next topic in this series, an app that keeps working offline and merges its changes back later. The offline sync post covers the conflict strategies.
Top comments (0)