API design: REST, gRPC, async

In one sentence

REST for public resource APIs, gRPC for typed internal calls and streaming, an async contract (202 + status, webhooks, SSE) for anything slow; build in pagination, versioning and idempotency from day one.

Analogy: Ordering a custom cake: the bakery doesn't keep you at the counter for three days. It hands you a ticket number (202 + status URL) and calls you when it's ready (webhook).

Accept fast, work in the background: 202 plus a status URL, then polling or a signed webhook. A retried POST with the same Idempotency-Key gets the same job.

How it works

  • REST treats resources as nouns and HTTP verbs as actions: GET is safe, PUT and DELETE idempotent, POST not.
  • GraphQL lets clients ask for exactly the fields they need, but it's harder to cache and rate-limit.
  • Go async past ~30 s: API Gateway's default timeout is 29 s, ALB's idle timeout 60 s.
  • Use cursor pagination, not OFFSET, which slows on deep pages and skips or repeats rows as data changes.
  • Versioning: ship additive changes only; breaking ones get /v2 or a dated header.

Check yourself

Answer to mark it learned; your answers aren't scored.

An admin UI pages through a live audit-log table with ?page=N, implemented as OFFSET. Users report rows that repeat or vanish between pages, and page 10,000 takes seconds. Best fix?

Go deeper

Full explanation

An API is a contract; pick its style by who calls it and how long the work takes.

  • REST (HTTP + JSON): resources as nouns (/orders/42), HTTP verbs as actions (GET safe; PUT, DELETE idempotent; POST not), and status codes that mean something (201, 409, 429). Universal and cacheable: the default for public APIs.
  • gRPC: protobuf over HTTP/2, generated clients, bidirectional streaming. Compact and strictly typed; best between internal services (browsers need gRPC-Web).
  • GraphQL: clients ask for exactly the fields they need. Good for many UIs over many backends; harder to cache and rate-limit.

Long-running work must not hold a request open for minutes:

  • 202 Accepted and a Location: /jobs/123 to poll.
  • Webhooks: call the client back when done (signed, retried with backoff).
  • SSE / WebSockets: push progress or tokens over an open connection (Streaming responses (SSE)).

Day-one essentials:

  • Cursor pagination (?after=opaque_cursor), not OFFSET, which slows on deep pages and skips or repeats rows as data changes.
  • Versioning: additive changes only; breaking ones get /v2 or a dated header.
  • Idempotency keys on POST, so a retry never charges twice (Idempotency).

LLM APIs hit all of this: answers stream over SSE, agent runs take minutes, batch jobs hours, and every retry costs tokens.

Code 202 Accepted with an idempotency key (FastAPI)
python202 Accepted with an idempotency key (FastAPI)
import uuid
from fastapi import FastAPI, Header, HTTPException, Response

app = FastAPI()
JOBS: dict[str, dict] = {}   # Postgres/Redis in production
KEYS: dict[str, str] = {}    # idempotency key -> job id, kept ~24 h

@app.post("/v1/summaries", status_code=202)
async def create_summary(body: dict, response: Response,
                         idempotency_key: str = Header()):
    # A retried POST with the same key returns the same job, not a second LLM run.
    # In production make check-and-set atomic (e.g. Redis SET NX) and scope keys per client.
    job_id = KEYS.get(idempotency_key)
    if job_id is None:
        job_id = KEYS[idempotency_key] = str(uuid.uuid4())
        JOBS[job_id] = {"id": job_id, "status": "queued"}
        await enqueue("summarize", job_id, body["document_url"])  # worker calls the LLM
    response.headers["Location"] = f"/v1/jobs/{job_id}"
    response.headers["Retry-After"] = "5"   # polling hint, in seconds
    return JOBS[job_id]

@app.get("/v1/jobs/{job_id}")
async def get_job(job_id: str):
    if job_id not in JOBS:
        raise HTTPException(status_code=404)
    return JOBS[job_id]  # queued | running | succeeded (+ result_url) | failed (+ error)
Real example

A contract-review API runs an LLM over 200-page PDFs, ~90 s each. Version one was a synchronous POST: the load balancer's 60 s idle timeout cut off long calls, clients retried, and every retry started another paid LLM run. The redesign returns 202 with /v1/jobs/{id} in ~50 ms, requires an Idempotency-Key so a resubmission returns the same job, streams progress to the UI over SSE, and sends a signed webhook to server integrations. Duplicate LLM spend from retries dropped to zero.

Trade-offs +3 · −3

+ You gain

  • REST: universal tooling, HTTP caching, debuggable with curl.
  • gRPC: typed contracts, generated clients, compact binary payloads and native streaming.
  • Async contracts decouple client timeouts from how long the work really takes.

− You pay

  • REST: no enforced schema unless you add OpenAPI, and over- or under-fetching across many screens.
  • gRPC: not browser-native, harder to inspect, needs HTTP/2 through every proxy.
  • Async adds state: a job store, polling load, webhook delivery, retries and signatures.

Use it when

REST for public and partner APIs; gRPC for high-volume service-to-service calls; async (202 + polling or webhooks) for anything that can exceed a few seconds; SSE for token streams to UIs.

Avoid it when

Don't expose gRPC directly to browsers or third parties, don't adopt GraphQL for one client with a few screens, and don't make 2-second operations async: polling only adds latency.

Numbers to know 5
  • RFC 9110: GET, HEAD, OPTIONS are safe; those plus PUT and DELETE are idempotent; POST is not.
  • Go async past ~30 s: AWS API Gateway's integration timeout defaults to 29 s and ALB's idle timeout to 60 s.
  • Stripe prunes idempotency keys after ≥24 h; a replay within that window returns the original result, even a 500.
  • gRPC's default max receive message size is 4 MB: stream large payloads instead of raising it blindly.
  • OFFSET 500000 LIMIT 50 reads and discards 500,000 rows; a keyset cursor (WHERE id > $1 ORDER BY id) seeks straight there via the index.
Common pitfalls 4
  • Returning 200 with {"error": ...} in the body: clients, retries and monitoring all depend on real status codes.
  • Offset pagination on a live table: slow deep pages, plus skipped and duplicated rows.
  • Breaking changes inside a version (renamed field, stricter validation) with no deprecation window.
  • Unsigned webhooks without retries, and consumers that aren't idempotent to duplicate deliveries.
Interview questions 3

Answer out loud first, then reveal.

Design the API for an LLM document-summarization feature.Show answer

I'd split it by latency. Short inputs get a synchronous POST that streams tokens over SSE, because users judge speed by time to first token. Long documents go async: POST returns 202 with a job URL in milliseconds, and the client polls with Retry-After or registers a signed webhook. Every POST takes an Idempotency-Key, since retried LLM calls cost real money. Errors use real status codes, like 429 with Retry-After for quota. And I version from day one, because output formats will change as models change.

REST or gRPC between your services?Show answer

gRPC for high-volume internal calls where I own both sides: protobuf gives a typed contract, generated clients, smaller payloads and streaming, which matters when an inference service streams tokens. REST at the edge and for partners, because anyone can call it, it caches, and it's debuggable with curl. gRPC's cost is tooling: HTTP/2 through every proxy and load balancer, binary payloads that are harder to inspect, gRPC-Web for browsers. A common answer is gRPC inside, REST or GraphQL at the gateway.

How do you evolve an API without breaking clients?Show answer

Within a version, only additive changes: new optional fields and endpoints, never renamed or removed fields, and clients must ignore unknown fields. Breaking changes ship as a new version, /v2 or a dated header like Stripe's, and both run side by side. I announce a deprecation window with a Sunset header and track calls per client, so I know exactly who still uses v1. Internally, protobuf helps: never reuse a field number, and reserve deleted ones.