API Design (REST, gRPC, GraphQL)
- Model a payments or orders domain as resources with correct methods, status codes and money/time representations
- Implement stable pagination (keyset) and safe retries (idempotency keys) and prevent lost updates with ETags
- Choose between REST, gRPC and GraphQL for public, internal and mobile-facing APIs
- Design asynchronous operations and webhooks that are reliable and secure, with a consistent error format
TL;DR
- Model resources and state transitions, not RPC verbs:
POST /payments,POST /payments/{id}/refunds,GET /accounts/{id}/transactions. - Use status codes precisely: 201 +
Locationfor creation, 202 for accepted-but-not-done, 409 for state conflicts, 412 for failed preconditions, 422 for business-rule violations, 429 for rate limits. - Paginate large or changing collections with keyset (cursor) pagination; offset pagination is slow at depth and skips or duplicates rows when data changes.
- Every non-idempotent operation that moves money or creates orders accepts an
Idempotency-Key; the server stores the key, a request fingerprint and the response. - ETags +
If-Matchgive optimistic concurrency over HTTP and prevent lost updates. - REST for public and partner APIs, gRPC for internal service-to-service calls, GraphQL for client-driven aggregation (often a mobile BFF).
- Long operations return 202 + an operation resource and/or emit signed webhooks; errors use RFC 9457 problem details.
Why it matters
- Payments: the network fails after the server charged the card. If the client retries and the API is not idempotent, the customer pays twice. Idempotency keys are a hard requirement in any payment API.
- Banking history: a customer scrolls through 3 years of transactions while new ones arrive. Offset pagination shows duplicates and gets slower with every page; keyset pagination stays fast and stable.
- Partner integrations: merchants, fintechs and open-banking providers build against your API for years. Breaking changes, ambiguous errors or unsigned webhooks become support load, fraud vectors and contractual disputes.
- Interviews: most system design answers include an API section; strong candidates specify idempotency, pagination and error semantics, not just endpoint names.
Core concepts
Resource modeling
- Nouns for resources, HTTP methods for actions. When an action does not map to CRUD (capture, cancel, approve), model it as a sub-resource (
POST /payments/{id}/refundscreates a refund) or a clearly named custom action (POST /payments/{id}/capture, or Google's:cancelstyle). - Expose state machines explicitly. An order has a
statuswith documented transitions; invalid transitions return 409 (see Order Management & State Machines). - Money: amounts as integers in minor units (
"amount": 1250000, "currency": "VND") or as decimal strings ("amount": "12.50") with an ISO 4217 currency code. Never floats. Note that minor units differ by currency (VND has none in practice, USD has 2, some have 3). - Time: RFC 3339 timestamps in UTC (
2026-10-17T03:15:00Z); dates without time for business dates (value date, statement date). - IDs: opaque strings, optionally type-prefixed (
pay_…); 64-bit numbers as strings (see Unique ID Generation). - Do not leak internals: no database ids that reveal volume, no table names, no stack traces.
Method semantics
| Method | Safe | Idempotent | Typical use |
|---|---|---|---|
| GET, HEAD | Yes | Yes | Read |
| PUT | No | Yes | Replace at a known URI |
| DELETE | No | Yes | Remove (repeat → 404 or 204, same end state) |
| POST | No | No | Create, trigger actions — needs idempotency keys for safe retries |
| PATCH | No | Not necessarily | Partial update; use If-Match to avoid lost updates |
Status codes that matter
| Code | Use it for |
|---|---|
| 200 OK | Successful read or update returning a body |
| 201 Created | Resource created; include Location |
| 202 Accepted | Request accepted, processing asynchronously; return an operation resource |
| 204 No Content | Success with no body |
| 304 Not Modified | Conditional GET, unchanged |
| 400 Bad Request | Malformed syntax, invalid JSON, wrong types |
| 401 Unauthorized | Missing/invalid authentication |
| 403 Forbidden | Authenticated but not allowed |
| 404 Not Found | Does not exist — or you do not want to reveal it exists |
| 409 Conflict | State conflict (cancel a shipped order), idempotency key in flight |
| 412 Precondition Failed | If-Match ETag does not match current version |
| 422 Unprocessable Content | Valid syntax, but violates business rules (insufficient funds, limit exceeded) |
| 428 Precondition Required | Server requires If-Match for this update |
| 429 Too Many Requests | Rate limit exceeded; include Retry-After |
| 500 / 502 / 503 / 504 | Server error / bad upstream / unavailable / upstream timeout |
Conventions vary for business declines — some payment APIs return 402 for card declines, most use 422 with a specific problem type. Pick one, document it, and never return 200 with an error body.
Pagination
Offset/limit (?offset=4000&limit=50) is easy and supports "jump to page 80", but the database must skip 4,000 rows on every request, and inserts or deletes between requests shift rows across pages (duplicates or gaps).
Keyset (cursor) pagination remembers the last row's sort key and asks for rows after it:
-- Index: (account_id, booked_at DESC, id DESC)
SELECT id, booked_at, amount, currency, description
FROM transactions
WHERE account_id = $1
AND (booked_at, id) < ($2, $3) -- cursor from the previous page
ORDER BY booked_at DESC, id DESC
LIMIT 51; -- one extra row tells you if there is a next page
{
"data": [
{"id": "txn_8f2", "booked_at": "2026-10-16T09:12:44Z", "amount": "-250000", "currency": "VND"}
],
"next_cursor": "eyJiIjoiMjAyNi0xMC0xNlQwOToxMjo0NFoiLCJpIjoidHhuXzhmMiJ9",
"has_more": true
}
- Each page costs the same regardless of depth; results are stable under concurrent inserts.
- The sort key must be unique (add
idas a tie-breaker) and backed by an index. - Cursors are opaque to clients (base64 of the key, optionally signed) so you can change the encoding later.
- Trade-off: no random page access and no cheap total count. For "page 3 of 120" UIs on small data, offset is fine.
See Query Optimization and Indexing.
Filtering, sorting and field selection
- Filters as query parameters with explicit names:
?status=paid&created_from=2026-10-01T00:00:00Z&created_to=…&min_amount=100000. - Sorting from a whitelist that matches indexes:
?sort=-created_at. Arbitrary sort fields invite full scans. - Cap
limit(for example 100) and document defaults. - Optional sparse fieldsets (
?fields=id,status,amount) or expansions (?expand=customer) to reduce chattiness — Stripe'sexpand[]is a well-known example.
Versioning and evolution
- Additive changes are not breaking: new optional fields, new endpoints, new optional parameters. Clients must ignore unknown fields — say so in your contract.
- Breaking changes (removing or renaming fields, changing types or semantics, adding required parameters, new enum values for strict clients) require a new version.
- Strategies: URI version (
/v1/payments) — explicit and cache-friendly; header or media-type version — cleaner URIs, harder to test in a browser; date-based versions pinned per client (Stripe's model) — fine-grained, more server complexity. - Deprecation: announce, monitor usage per client, send the
Sunsetheader (RFC 8594) and aDeprecationheader, and give partners months, not weeks. In banking, partner contracts often fix minimum notice periods.
Idempotency keys
- The client generates the key (a UUID) once per logical operation and reuses it on every retry.
- The server stores
(client_id, key)→ request fingerprint (hash of method, path, body), status and response, typically for 24 hours or more. - Same key + same fingerprint → return the stored response. Same key + different body → reject (422 or 409). Same key still in progress → 409 (or wait briefly).
- Store the idempotency record in the same transaction as the business effect when possible; otherwise you need careful recovery for "effect done, record not saved".
- Downstream calls (to a card processor or another bank) must carry their own idempotency keys or unique references.
- The IETF HTTPAPI working group has a draft for a standard
Idempotency-Keyheader; Stripe popularised the pattern. Deep dive: Idempotency & Exactly-Once.
CREATE TABLE idempotency_keys (
client_id text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL,
status text NOT NULL CHECK (status IN ('in_progress', 'completed')),
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (client_id, key)
);
ETags and optimistic concurrency
Two back-office users edit the same merchant's payout settings; the second save silently overwrites the first — a lost update. HTTP has a built-in fix:
GET /merchants/m_42/payout-settings
200 OK
ETag: "v17"
PUT /merchants/m_42/payout-settings
If-Match: "v17"
Content-Type: application/json
{"schedule": "daily", "bank_account_id": "ba_9"}
412 Precondition Failed <- someone else saved v18 in the meantime
The server maps the ETag to a row version: UPDATE payout_settings SET … , version = version + 1 WHERE merchant_id = $1 AND version = $2; zero rows updated means 412. Return 428 if a client omits If-Match on resources where lost updates matter. ETags with If-None-Match also give cheap conditional GETs (304). See Locking & Concurrency Control.
REST vs gRPC vs GraphQL
| REST (HTTP + JSON) | gRPC (HTTP/2 + Protobuf) | GraphQL | |
|---|---|---|---|
| Contract | OpenAPI (optional) | .proto, mandatory, codegen | Schema, mandatory |
| Payload | Text JSON, human-readable | Binary, compact, fast | JSON, client-shaped |
| Streaming | SSE/WebSocket alongside | Native client/server/bidi streaming | Subscriptions (varies by server) |
| Caching | HTTP caching, CDNs, ETags | Not HTTP-cacheable | Hard (mostly POST to one endpoint) |
| Browser support | Native | Needs gRPC-Web or a proxy | Native |
| Strengths | Ubiquitous, simple tooling, great for public APIs | Performance, strict typing, deadlines, internal polyglot services | One round trip per screen, no over/under-fetching |
| Weaknesses | Chatty for complex screens, loose typing | Debuggability, load balancing needs L7 | Query cost control, N+1 resolvers, per-field authorization |
| Typical fit | Public/partner APIs, open banking | Service-to-service | Mobile/web BFF aggregating many services |
Common architecture at a bank or marketplace: REST for external partners (open-banking standards are typically REST/JSON), gRPC between internal services, and optionally GraphQL or a REST BFF for the mobile app. More on gRPC in RPC & gRPC.
Asynchronous APIs
Some operations cannot finish within a request: an interbank transfer through a slow switch, KYC verification, a statement export, a bulk payout file.
- Return 202 with an operation resource (
status:pending→running→succeeded/failed, plus result or error). - Support both polling (with
Retry-Afterhints) and webhooks; webhooks can be lost or delayed, so polling is the safety net. - Accept an idempotency key on the creating request so retries do not start two batches.
Webhooks: reliability and security
Delivery (sender side):
- At-least-once with retries and exponential backoff over hours or days; a dashboard and a manual redelivery endpoint.
- No ordering guarantee — include an event id, type, created timestamp and the resource version so receivers can discard stale events.
- Consider thin events ("payment pay_5 changed"), where the receiver fetches the current state via the API, for critical flows; it avoids acting on stale or forged payloads.
Security:
- Sign every delivery: HMAC-SHA256 with a per-endpoint secret over
timestamp + "." + raw_body, sent in a header. Receivers verify with a constant-time comparison against the raw bytes (before JSON parsing). - Replay protection: reject signatures whose timestamp is older than a tolerance (for example 5 minutes), and dedupe by event id.
- Secret rotation: support two active secrets and multiple signatures during rotation.
- Optional: mTLS or published egress IP ranges. HTTPS only.
- Receivers should return 2xx quickly and process asynchronously, idempotently by event id.
- The community Standard Webhooks specification describes a common format for these headers and signatures.
Errors: RFC 9457 problem details
RFC 9457 (which obsoletes RFC 7807) defines application/problem+json:
{
"type": "https://api.example-bank.vn/problems/insufficient-funds",
"title": "Insufficient funds",
"status": 422,
"detail": "The source account does not have enough available balance for this transfer.",
"instance": "/transfers/trf_01J9Z3K7Q4",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"errors": [
{"field": "amount", "code": "exceeds_available_balance"}
]
}
typeis a stable URI clients can switch on;titleis a short human summary;statusmirrors the HTTP code;detailexplains this occurrence;instanceidentifies it. Extensions (trace_id,errors) are allowed.- Keep
typevalues stable across versions; they are part of the contract. - Do not leak sensitive data (exact balances, whether a phone number is registered) or internals (SQL, stack traces).
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Offset pagination | Random page access, total counts | Slow at depth, unstable under writes | Small, mostly static lists, admin UIs |
| Keyset pagination | Constant cost, stable | No page jumping, needs unique sort key + index | Transaction history, feeds, large tables |
| URI versioning | Explicit, easy to route and test | Version sprawl | Public and partner APIs |
| Date-based versions per client | Fine-grained evolution | Server must support many behaviours | Large API platforms with many integrators |
| Idempotency keys | Safe retries for POST | Storage and careful implementation | Any money movement or order creation |
| ETag / If-Match | Prevents lost updates, standard HTTP | Clients must handle 412 | Editable configuration, back-office resources |
| Polling for async | Simple, reliable | Latency, wasted calls | Safety net, low-volume clients |
| Webhooks | Push, timely | Delivery and security complexity | Partner notifications, payment status |
| REST | Universal, cacheable | Chatty for complex UIs | External APIs |
| gRPC | Fast, typed, streaming | Browser/LB friction | Internal services |
| GraphQL | Client-shaped responses | Cost control, caching, authZ complexity | BFF for rich clients |
In practice
- API-first: write the OpenAPI or
.protocontract and review it like code; lint with tools like Spectral; generate clients and server stubs; run contract tests in CI. - Adopt a style guide rather than inventing one: Google's API Improvement Proposals (AIPs), Microsoft REST API Guidelines, or Zalando's RESTful API Guidelines.
- Correlation: accept and propagate W3C
traceparentand return a request id in every response and error body (see Observability & SLOs). - Security: OAuth 2.0 with scopes; for open banking, the OpenID Foundation's FAPI profiles and mTLS-bound tokens are common requirements. See Security for Architects.
- Verifying a webhook signature in Go:
package webhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"net/http"
"strconv"
"time"
)
const tolerance = 5 * time.Minute
var ErrInvalidSignature = errors.New("webhook: invalid signature")
// Verify reads the raw body and checks headers of the form
// X-Signature-Timestamp: 1760670900
// X-Signature: hex(HMAC-SHA256(secret, timestamp + "." + body))
func Verify(r *http.Request, secret []byte, now time.Time) ([]byte, error) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
return nil, err
}
tsHeader := r.Header.Get("X-Signature-Timestamp")
ts, err := strconv.ParseInt(tsHeader, 10, 64)
if err != nil {
return nil, ErrInvalidSignature
}
if d := now.Sub(time.Unix(ts, 0)); d > tolerance || d < -tolerance {
return nil, ErrInvalidSignature // stale or future-dated: possible replay
}
got, err := hex.DecodeString(r.Header.Get("X-Signature"))
if err != nil {
return nil, ErrInvalidSignature
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(tsHeader + "."))
mac.Write(body)
if !hmac.Equal(got, mac.Sum(nil)) { // constant-time comparison
return nil, ErrInvalidSignature
}
return body, nil // now parse JSON, dedupe by event id, enqueue, return 2xx
}
Common pitfalls
- POST without idempotency for payments. Symptom: duplicate charges after mobile network timeouts.
- Offset pagination on transaction history. Symptom: slow deep pages, customers seeing the same transaction twice while new ones arrive.
- Floats for money. Symptom:
0.1 + 0.2rounding errors in totals and reconciliation breaks. - 200 with
{"error": …}. Symptom: clients, proxies and monitoring treat failures as success; retries and alerts never fire. - Breaking changes without versioning (renamed field, new required parameter, new enum value for strict clients). Symptom: partner integrations fail on deploy day.
- Leaking existence. Different responses for "account does not exist" and "not yours" let attackers enumerate customers. Return 404 for both when appropriate.
- Unsigned or unverified webhooks. Symptom: an attacker posts a fake
payment.succeededand receives goods. - Processing webhooks synchronously. Symptom: sender timeouts, retries, duplicate processing.
- Chatty mobile APIs. Symptom: a home screen that needs 12 sequential calls over a mobile network; fix with a BFF or aggregate endpoint.
Interview angle
- Where it appears: the API step of every system design interview; standalone "design the API for a payment/transfer/order service" at banks and marketplaces.
- Strong answer covers: resources and key endpoints with methods and status codes, request/response shapes with money and time types, idempotency on creates, pagination strategy, error format, auth, versioning, and the async/webhook story for long operations.
- Follow-ups: "The client times out on POST /transfers — what happens on retry?", "How does the client page through 10,000 transactions?", "Two admins edit the same config — how do you avoid lost updates?", "REST or gRPC between services?", "How do merchants trust your webhooks?"
- Red flags: verbs everywhere in URIs, no idempotency, offset pagination for large tables without acknowledging trade-offs, floats for money, no error model, webhooks without signatures.
Self-check
1. Design the endpoints for creating a transfer, checking its status, and listing an account's transactions, with status codes.
POST /transfers with an Idempotency-Key → 201 + Location: /transfers/{id} if completed synchronously, or 202 with status pending if it goes through an async switch. GET /transfers/{id} → 200 with status (pending, completed, failed) and failure reason. GET /accounts/{id}/transactions?limit=50&cursor=… → 200 with keyset-paginated results and next_cursor. Errors use problem details: 422 for insufficient funds or limits, 409 for conflicts, 429 for rate limits.
2. Why does offset pagination produce duplicates on a live transaction list, and how does keyset avoid it?
With offset, page 2 is "skip 50 rows". If a new transaction is inserted at the top between requests, every row shifts down by one, so the last row of page 1 reappears as the first of page 2. Keyset asks for rows strictly after the last seen (booked_at, id), which does not depend on how many rows precede it, so inserts at the top do not shift the cursor.
3. Walk through how the server handles an idempotency key for: first request, retry after success, retry with a different body, concurrent duplicate.
First request: insert the key with the request fingerprint as in_progress, perform the operation, store the response, mark completed (ideally in one transaction). Retry after success: find the completed record with a matching fingerprint and return the stored response without re-executing. Different body: fingerprint mismatch → reject with 422 or 409. Concurrent duplicate while in_progress: return 409 (or wait briefly) so the operation runs only once.
4. How do ETags prevent lost updates, and what codes are involved?
GET returns an ETag representing the version. The client sends it back in If-Match on PUT/PATCH; the server updates only if the current version matches, otherwise returns 412 Precondition Failed and the client must re-read and reapply. 428 Precondition Required forces clients to send If-Match. Conditional GETs with If-None-Match return 304 when unchanged.
5. Scenario: a merchant says they received a payment.succeeded webhook for a payment that failed. What could have happened, and how should the system be designed?
Either the webhook was forged (no or unverified signature), replayed, or processed out of order (a stale success arriving after a later failure, or vice versa). Design: sign webhooks with HMAC over timestamp + raw body, verify in constant time, enforce a timestamp tolerance, dedupe by event id, include resource versions so stale events are discarded, and for critical decisions fetch the payment from the API before fulfilling.
6. When would you choose gRPC, REST and GraphQL in a bank's architecture?
REST for external partner and open-banking APIs — universal tooling, HTTP caching, standards alignment. gRPC between internal services — typed contracts, efficient binary encoding, deadlines and streaming. GraphQL (or a REST BFF) for the mobile app when screens aggregate many services and round trips over mobile networks are expensive, with query cost limits and field-level authorization.
Exercise
Design and partially implement a transfer API for a bank.
- Write an OpenAPI spec for
POST /transfers,GET /transfers/{id},GET /accounts/{id}/transactions(keyset), and the problem-details error schema. Include theIdempotency-Keyheader and money/time types. - Implement
POST /transfersin Go with theidempotency_keystable above, in one PostgreSQL transaction with the transfer insert. Write a test that fires the same request 20 times concurrently and asserts exactly one transfer row. - Implement keyset pagination and compare its latency against offset at page 1 and page 2,000 with
EXPLAIN ANALYZE. - Implement webhook signing on the sender side and the
Verifyfunction on the receiver; test valid, tampered, stale and replayed deliveries.
Done looks like: a lint-clean OpenAPI file, passing concurrency and webhook tests, and two EXPLAIN ANALYZE outputs with timings.
Further reading
- RFC 9110 "HTTP Semantics", RFC 9457 "Problem Details for HTTP APIs", RFC 8594 "The Sunset HTTP Header Field" (rfc-editor.org).
- IETF HTTPAPI draft, "The Idempotency-Key HTTP Header Field".
- Brandur Leach, "Implementing Stripe-like Idempotency Keys in Postgres" (brandur.org) and Stripe's API reference on idempotent requests and versioning.
- Google API Improvement Proposals (google.aip.dev) — resource-oriented design, pagination, long-running operations.
- Microsoft REST API Guidelines (github.com/microsoft/api-guidelines); Zalando RESTful API Guidelines.
- API Design Patterns (JJ Geewax, Manning) and Designing Web APIs (Jin, Sahni, Shevat, O'Reilly).
- Standard Webhooks specification (standardwebhooks.com).
Related
- Idempotency & Exactly-Once — the full idempotency design.
- RPC & gRPC — gRPC internals and trade-offs.
- HTTP/1.1, HTTP/2, HTTP/3 — the transport underneath.
- Rate Limiting — 429 and
Retry-Afterin depth. - Notification System — delivering webhooks and messages at scale.
- Payment System — APIs in a payment flow.
- Bank Transfer System — the transfer API in a full design.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).