Advanced REST API design: idempotent methods, gateway URLs, pagination and sorting
Senior-level REST API design, part 1: the design-first mindset, getting safe and idempotent right, URL conventions behind an API gateway, offset/cursor/deferred-join pagination with real PostgreSQL measurements, sort allowlists and modelling N-N relationships.
On this page
After the basics, this post covers what it takes for an API to "work in production": method semantics, URLs behind a gateway, paginating tables with tens of millions of rows, sorting and relationships. Part 2 covers exporting a 500 MB file, duplicate payment requests and API docs; read Web and HTTP and Indexes first.
1. The problem
A reconciliation job loops over GET /transactions?page=N&size=100. Between two calls, 2 transactions on the first page are deleted and every row shifts up by 2: 2 transactions are never reconciled. Page 1,500 also takes 800 ms because the DB reads and discards 150,000 rows.
2. Key idea
Public APIs are the hardest thing to change because you don't control the clients: design the OpenAPI spec first and run OpenAPI diff in CI.
| Method | Safe | Idempotent | Use for |
|---|---|---|---|
| GET, HEAD | yes | yes | reads |
| PUT | no | yes | replacing a whole resource |
| DELETE | no | yes | deletes |
| POST | no | no | creates, actions; made idempotent with an Idempotency-Key |
| PATCH | no | not guaranteed | {"age": 34} is idempotent, "add 10 to balance" isn't |
Proxies and service meshes retry on timeout: retrying a money-transfer POST without a key is a second transfer.
2.1 Which pagination?
| Kind | Use when | Don't use when |
|---|---|---|
| Cursor (keyset) | public APIs, feeds, sync jobs | you need "jump to page 37" |
| OFFSET + deferred join | admin pages that need page numbers | jobs that walk all the data |
Cursors need three things: a unique sort key (add id), an index matching ORDER BY, an opaque cursor (next_cursor, not last_id). Fetch limit + 1 rows to know has_next and skip COUNT(*).
2.2 URLs and sorting
- Plural nouns with a version:
/v1/orders,POST /orders/145/cancellation; kebab-case in URLs. - A service name in the URL (
/order-service/v1/orders) lets the gateway route by prefix but leaks internal structure: splitting the service becomes a breaking change. For public APIs, let the gateway map by resource. - Column names in
ORDER BYcan't be bound: sort only by whitelisted, indexed fields, with anidtie-breaker.
3. In Java
record Cursor(Instant createdAt, long id) {
String encode() {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString((createdAt.toEpochMilli() + ":" + id).getBytes(UTF_8));
}
}
static final Map<String, String> SORTABLE = Map.of("price", "p.price", "created_at", "p.created_at");
// index: (account_id, created_at DESC, id DESC)
String sql = """
SELECT id, amount, created_at FROM transactions
WHERE account_id = :accountId
AND (created_at, id) < (:lastCreatedAt, :lastId) -- MySQL: expand into an OR
ORDER BY created_at DESC, id DESC
LIMIT :limitPlusOne""";
// page 1 or page 10,000 both take ~0.02 ms; rows deleted between calls don't make others vanishBase64 isn't encryption: clients can decode and edit cursors. Reapply filters and authorization on every request; never put tenant_id in a cursor and trust it. Other languages: the same SQL.
Deferred join when you must use OFFSET
SELECT u.* FROM (
SELECT id FROM users ORDER BY created_at DESC, id DESC
LIMIT 10 OFFSET 150000
) page JOIN users u ON u.id = page.id
ORDER BY u.created_at DESC, u.id DESC;Paginate over the small index fetching only id, then join the full columns for exactly 10 rows: measured on a 200,000-row table, buffer reads drop about 10×. But it's still O(offset). On PostgreSQL it's only fast when the Index Only Scan needn't read the heap, i.e. the table is vacuumed.
4. Working with AI
Give the AI: an OpenAPI spec from your endpoint list, MockMvc tests for pagination, OpenAPI diff in CI.
Check in AI-written code:
- No
Sort.by(param)orsortconcatenated intoORDER BYwithout a whitelist. - Public list APIs use cursors;
ORDER BYhas anidtie-breaker. - An index matches the
ORDER BYand filters. - Jobs walking all data iterate by an increasing key, not page numbers.
- No "auto-retried" POST without an Idempotency-Key.
5. Exercises
Exercise 1: URLs for classes
course-service manages classes and students. The AI proposes POST /course-service/v1/addStudentToClass?classId=7&studentId=s9. Rewrite it for: listing class 7's students, adding s9, adding many students at once, removing s9.
Solution to Exercise 1
GET /course-service/v1/classes/7/students?limit=20&cursor=...
PUT /course-service/v1/classes/7/students/s9 # idempotent, 204 whether or not already there
POST /course-service/v1/classes/7/students # {"student_ids": ["s1","s2"]}, max 100
DELETE /course-service/v1/classes/7/students/s9 # 204; a repeat 404 is still idempotentBulk add: choose all-or-nothing (one transaction) for small batches, or per-item results with ON CONFLICT DO NOTHING for large ones; document which.
Exercise 2: Moving to cursors
Back to section 1. Redesign GET /v1/transactions so the reconciliation job misses nothing and deep pages stay fast, without breaking old clients right away.
Solution to Exercise 2
GET /v1/transactions?limit=50&cursor=<opaque>,ORDER BY created_at DESC, id DESC.- Index
(account_id, created_at DESC, id DESC), since you always filter by account. - Return
next_cursorandhas_next(fetch 51 rows). - The reconciliation job iterates
id > :last_idin increasing order. - Keep
?page=for a while with aDeprecationheader, and measure which clients still use it.
Summary
- Idempotency is about server state, not responses.
- Automatic retries are only safe for idempotent methods or with an Idempotency-Key.
- OFFSET is slow and skips rows; public APIs use cursors.
- Cursors: unique key, matching index, opaque cursor, never trust its contents.
- Sort only through a whitelist, always with an
idtie-breaker.
Read more: Async jobs and Idempotency-Key.
Practice interview questions on this topic
- How do you handle file upload and download in Spring Boot safely, including large files?
- What is the difference between safe and idempotent? Name a method that is idempotent but not safe?
- How do you design good REST resource URLs, and what does stateless mean in REST?
- What are LIMIT and OFFSET for? Why is a large OFFSET slow, and what do you use instead?
- When would you choose gRPC or GraphQL over REST?
All Spring Boot questions →All Web & REST API questions →All SQL & Query Tuning questions →
Comments
Community rules