Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 141/ 160
08. Backend

REST APIs

Resource-oriented HTTP APIs that front AI features for clients and partners.

BeginnerHTTP · Resources · JSON3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

A REST API is a set of web addresses where each address is a thing (a chat, a document, a job) and you use simple actions like get, create and delete on it.

Think of it like…

A restaurant with a menu, an order slip and a pager. Resources are the menu items and orders, verbs are the standard actions (order, check, amend, cancel) and for slow dishes the kitchen gives you a pager (a job resource) instead of making you stand at the counter.

Where you’ve seen it

An assistant product defines POST /v1/conversations (create), GET /v1/conversations/{id} (read), POST /v1/conversations/{id}/messages (add a user message and receive the reply) and GET /v1/conversations/{id}/messages?limit=20&cursor=... (history). Messages are short: a model call of about 3.4 seconds (0.6 s time to first token plus 420 tokens at 150 tokens a second) is acceptable synchronously, and a streaming variant (Accept: text/event-stream) returns tokens as they arrive. Document ingestion is different: POST /v1/documents stores the file and returns 202 Accepted with Location: /v1/jobs/j_91 and a job body {"id": "j_91", "status": "queued"}; GET /v1/jobs/j_91 then returns running with a progress field and finally succeeded with a link to the document. A 45-second job polled every 2 seconds costs about 23 requests; telling the client to back off through a Retry-After header (2, 4, 8, 16, 16 seconds) cuts that to 5 polls, finding the result at 46 seconds. Little's law sizes the synchronous path: 100 requests a second × 3.4 s = 340 requests in flight, which a pool of 50 blocking workers (capacity 50 / 3.4 = 14.7 requests a second) cannot carry, so the service uses an async server. Errors use one JSON shape with a machine-readable code, a human message and a request_id (the RFC 9457 problem-details format is a good model), and the API is versioned in the path so v2 can change fields without breaking v1 clients.

Words you’ll hear

Resource
A noun the API exposes at a URL, such as a conversation or a job.
Idempotent method
A method whose repeated use has the same effect as one use: GET, PUT, DELETE.
Job resource
A resource that represents long-running work and reports its status.
Problem details
A standard JSON error shape with type, title, status and detail.

Visual diagram

Loading interactive diagram

Theory & deep dive

Designing resources and choosing verbs

Model things, not procedures: /conversations, /conversations/{id}/messages, /documents, /jobs, /evals/{id}/results. Use plural nouns, nest only one level when ownership is clear and keep IDs opaque. Pick verbs by semantics: GET for reads (safe and cacheable), POST to create or trigger work (not idempotent by default), PUT to replace a resource wholesale (idempotent), PATCH for partial updates and DELETE to remove. Action-like operations that don't fit CRUD, such as POST /v1/messages/{id}:regenerate or POST /v1/chat/completions, are acceptable as action resources when documented, as long as they stay predictable.

Because POST is not idempotent, any client that retries a timed-out POST may create duplicates or pay for a second model call. The fix is an idempotency key (covered in its own lesson) so the server can recognise a repeat. Design responses for evolution: return objects rather than bare arrays, add fields without removing old ones, make enums extensible and put the version in the URL (/v1) or a header. Use pagination on every list, filtering with query parameters, and ETags or updated_at for conditional requests on resources that change.

Mapping a feature to resources

Feature "chat with history": POST /v1/conversations → 201 + Location; POST /v1/conversations/c_7/messages → 200 with the assistant message; GET /v1/conversations/c_7/messages?limit=20 → page with next_cursor; DELETE /v1/conversations/c_7 → 204. Feature "ingest a PDF": POST /v1/documents → 202 + job; GET /v1/jobs/j_91 → status.

Key takeaway: Expose nouns, use verbs by their semantics and design for retries, pagination and versioned evolution from the start.

Long-running work, errors and capacity

A model call of 3.4 seconds is fine to hold open; a 45-second ingestion or a multi-step agent run is not, because browsers, load balancers and mobile networks cut idle or slow requests (often between 30 and 120 seconds). Use the asynchronous request-reply pattern: accept the work, return 202 Accepted with a Location header pointing to a job resource, and let the client poll with backoff, subscribe to a stream or receive a webhook when the job completes. A job resource carries status, progress, created_at, a result link or an error object, and a retention window. Polling every 2 seconds for 45 seconds costs 23 requests per job; honouring a Retry-After of 2, 4, 8, 16 and 16 seconds costs 5.

Make errors uniform: a stable code (such as context_too_long), a readable message, the HTTP status, field-level details for validation errors and a request_id that support can find in logs. Size capacity with Little's law: concurrent requests = arrival rate × latency, so 100 requests a second at 3.4 seconds each means 340 in flight; a blocking server with 50 workers only sustains 50 / 3.4 = 14.7 requests a second, which is why AI backends favour async servers, streaming and queues for the slow paths. Add rate limits and request size limits, document them and return headers that tell clients how to behave.

Polling cost

Fixed 2 s polling for a 45 s job: 45 / 2 ≈ 23 requests. Backoff with Retry-After 2, 4, 8, 16, 16 s: polls at 2, 6, 14, 30 and 46 s, so 5 requests and the result is seen 1 s after completion. At 1,000 jobs per hour that is 23,000 versus 5,000 requests.

Key takeaway: Use 202 and job resources for slow work, return uniform errors and size servers with arrival rate times latency.

How it works, step by step

Step 1 of 4
API designer

1. List the resources and actions

Name the nouns your product exposes and map each user action to a verb and URL, versioned from day one.

conversations · messages · documents · jobs
Key numbers at this step
Version
/v1

When to use it & trade-offs

What it is

A REST API exposes your system as resources (nouns such as conversations, messages, documents, jobs) addressed by URLs and manipulated with standard HTTP verbs: GET reads, POST creates or triggers, PUT replaces, PATCH changes part of a resource and DELETE removes it. Clients get predictable behaviour from the protocol: safe methods (GET) change nothing, idempotent methods (GET, PUT, DELETE) can be repeated without extra effect, and responses carry status codes, headers and a representation (usually JSON). For AI backends the interesting design question is the time dimension: a model call takes seconds, an ingestion job takes minutes, so the API needs synchronous endpoints for short work, asynchronous job resources for long work and a streaming option for incremental output.

Why it matters: A clear resource model is the contract between your AI feature and every client: web app, mobile app, partner integration, internal tool. Good design makes retries safe, lets clients cache and paginate, keeps versions evolvable and prevents the classic failure of a single endpoint that holds a connection open for 45 seconds until a proxy cuts it. Bad design shows up as duplicate charges after a retry, client timeouts on long jobs and breaking changes that strand integrators.

When to reach for it

  • Public and internal HTTP APIs in front of AI features
  • Job resources for ingestion, batch scoring and evals
  • Versioned contracts shared with partners

When to avoid or be careful

  • Verbs in URLs for plain CRUD, such as /getConversation
  • Holding requests open for tens of seconds
  • Bare array responses that cannot gain fields later

Long-running work patterns

Synchronous request
Best for: Work that finishes in a few seconds

Strengths: Simplest for clients.

Watch out: Timeouts and held connections if it runs long.

202 + job polling
Best for: Minutes-long ingestion and batch tasks

Strengths: Robust; works through any proxy.

Watch out: Extra requests; clients must poll sensibly.

Webhook callback
Best for: Server-to-server completion notices

Strengths: No polling cost.

Watch out: Needs a public endpoint, signing and retries.

Interview signals & numbers to know

When this topic comes up

  • “How would you design the API for a chat product?”
  • Idempotent versus non-idempotent methods
  • 202 Accepted and job resources
  • Little's law for sizing
  • API versioning and evolution

Benchmarks & rules of thumb

340 -
requests in flight at 100 requests/s and 3.4 s latency
14.7 req/s -
capacity of 50 blocking workers at 3.4 s per call
23 vs 5 -
polls for a 45 s job: every 2 s versus backoff

Common mistakes & follow-ups

Common interview mistakes

  • Retrying a POST that creates something without an idempotency key.
  • Returning 200 with an error message in the body.
  • Changing field meanings inside the same API version.

Likely interviewer follow-ups

  • How would you expose a 5-minute ingestion job?
  • What makes PUT idempotent but POST not?
  • How would you evolve the response of a v1 endpoint?
Interview tip: Use Little's law out loud when sizing; it shows you connect API design to capacity.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply REST APIs with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Rollbacks
Next topic
HTTP and Status Codes