Skip to content
Interview prep · questions

APIs and data interview questions

22 questions, from core to senior. Say your answer out loud first, then open the model answer and check it against the points a strong answer covers.

How do you design a REST API for a resource such as orders?

  • Core
Show the model answer

I model resources as nouns in the URL and use the HTTP method for the action. So GET /orders lists, POST /orders creates, GET /orders/42 reads one, PATCH /orders/42 changes it, and DELETE /orders/42 removes it. There are no verbs in the path. The status code carries the result: 201 with a Location header after a create, 204 after a delete, 400 or 422 for bad input, 404 when the resource does not exist. A list endpoint is always paginated, with a limit and a cursor, and it takes filters and sorting as query parameters. All errors have one shape, for example a code, a message and details for each field, so the client handles them in one place. I version the API, usually with v1 in the path, and inside a version I only add fields; I never remove or rename them.

A strong answer covers

  • Uses nouns for resources and HTTP methods for actions
  • Returns correct status codes, including 201 after a create
  • Paginates every list and can compare cursor with offset
  • Has one error shape for the whole API
  • Has a versioning plan and avoids breaking changes

Likely follow-up

Why is cursor pagination better than offset pagination for a large list that changes often?

What does idempotent mean, and why does it matter for a payment endpoint?

  • Core
Show the model answer

An operation is idempotent when doing it many times has the same effect as doing it once. It matters because networks fail. The client sends a request, the server does the work, and the response is lost. The client cannot know whether it worked, so it retries. If the operation is not idempotent, the user pays twice. GET, PUT and DELETE are idempotent. PUT means: set this resource to this state, so a repeat changes nothing. POST is not: two POST requests create two payments. To make a POST safe to retry, the client creates a unique idempotency key, for example a UUID, and sends it in a header. The server stores the key with the result. When the same key arrives again, it returns the stored result and does not repeat the work. In the frontend I create the key once per user action, so every retry uses it.

A strong answer covers

  • Defines it: many identical calls have the same effect as one
  • Explains the lost response that forces a retry
  • Describes an idempotency key that the server stores with the result
  • Says PUT and DELETE are idempotent and POST is not

Likely follow-up

Where does the server keep idempotency keys, and for how long?

What is the difference between authentication and authorization, and where do you enforce each?

  • Core
Show the model answer

Authentication answers who you are, and authorization answers what you are allowed to do. Authentication happens at login, with a password, a single sign-on provider or a passkey, and the result is a session or a token. With a session, the server stores the state and the browser holds an ID in a cookie, so it is easy to revoke. With a token like a JWT, the server only verifies a signature. That works well across many services, but revoking is harder. Authorization is checked on the server on every request: first the role or permission, then ownership, for example that this order belongs to this user. In NestJS this is the job of guards. The frontend can hide a button, but that is only for a better experience. Anyone can call the API directly, so the server never trusts a role or user ID that the client sends.

A strong answer covers

  • Defines both: identity against permission
  • Connects them to 401 (not authenticated) and 403 (not allowed)
  • Says the server checks every request, including who owns the record
  • Says hiding a button is for experience, not for security

Likely follow-up

A user changes the ID in the URL and sees another user's order. What is wrong, and how do you fix it?

What is the difference between INNER JOIN and LEFT JOIN, and why does this query use LEFT JOIN?

  • Core
SELECT u.id, u.name, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
ORDER BY order_count DESC;
Show the model answer

An INNER JOIN returns only the rows that have a match in both tables. A LEFT JOIN returns every row from the left table, and puts NULL in the columns of the right table when there is no match. This query counts the orders of each user, and it must also show users with no orders, so it uses a LEFT JOIN from users to orders. GROUP BY makes one group for each user, and COUNT counts the rows in each group. It counts o.id and not the star, because COUNT of a column skips NULL. So a user with no orders gets 0. With COUNT star that user would get 1, and with an INNER JOIN the user would not be in the result at all. One common mistake: a condition on the orders table in WHERE removes the rows with NULL. That condition belongs in the ON clause.

A strong answer covers

  • Says INNER JOIN keeps only matching rows and LEFT JOIN keeps all rows of the left table
  • Says LEFT JOIN is used so that users with no orders still appear
  • Explains COUNT(o.id): it skips NULL, so those users get 0
  • Knows that a WHERE condition on the right table removes the unmatched rows

Likely follow-up

How do you change the query to show only users with more than five orders?

What is a database index, and why not put one on every column?

  • Core
Show the model answer

An index is a separate sorted structure, usually a B-tree, that lets the database find rows without reading the whole table. A B-tree lookup takes a few steps even in a very large table, and a full scan reads every row. The cost is on writes: each write must keep every index up to date, and indexes take space. So I add them for the columns in WHERE, JOIN and ORDER BY of frequent queries. In a composite index the column order matters. An index on user_id and then created_at helps a query that filters by user_id, but it does not help much for a query that filters only by created_at. The database can ignore an index. That happens when the column is inside a function, when a LIKE pattern starts with a wildcard, or when the query returns a large part of the table. I check with EXPLAIN ANALYZE.

A strong answer covers

  • Describes an index as a sorted structure (a B-tree) that avoids a full table scan
  • Says reads get faster, writes get slower, and indexes use space
  • Explains column order in a composite index: queries should filter on the leading column
  • Gives a case where the index is not used: a function on the column or a leading wildcard
  • Checks the plan with EXPLAIN

Likely follow-up

What is a covering index, and when does it help?

What does a database transaction guarantee, and how do you stop the double booking in this example?

  • Core
-- Two requests run this at the same time, for two different users
SELECT status FROM seats WHERE id = 17;
-- Both read 'free', so both continue
UPDATE seats SET status = 'booked', user_id = :user WHERE id = 17;
Show the model answer

A transaction makes a group of statements one unit: all of them succeed, or none of them do. ACID names the guarantees. Atomic means all or nothing. Consistent means the rules of the data, such as constraints, still hold at the end. Isolated means transactions that run at the same time do not see each other's unfinished work. Durable means a committed change survives a crash. Here both requests read that the seat is free before either one writes, and at the default isolation level a transaction alone does not stop that. With pessimistic locking, SELECT FOR UPDATE locks the row, so the second request waits and then sees that the seat is taken. With optimistic locking, the UPDATE also checks a version number or the old status, and if it changes no row, someone else was faster. Pessimistic fits frequent conflicts, optimistic fits rare ones.

A strong answer covers

  • Explains ACID in plain words, not only the four letters
  • Describes the race: two requests read free, then both write
  • Gives pessimistic locking (SELECT FOR UPDATE) and optimistic locking (a version check in the UPDATE)
  • Says a transaction at the default isolation level does not stop this race alone
  • Says when each fits: pessimistic for frequent conflicts, optimistic for rare ones

Likely follow-up

What are the isolation levels, and which one does PostgreSQL use by default?

The query log for one page load looks like this. What is the problem, and how do you fix it?

  • Senior
SELECT * FROM posts ORDER BY created_at DESC LIMIT 100;
SELECT * FROM users WHERE id = 7;
SELECT * FROM users WHERE id = 12;
SELECT * FROM users WHERE id = 7;
SELECT * FROM users WHERE id = 31;
-- ... and 96 more queries like these
Show the model answer

This is the N+1 query problem: one query for a list, and then one more query for each item in it, so 100 posts cost 101 queries. An ORM causes it when a relation is loaded lazily or inside a loop: the code fetches the posts, and then for each post it asks for the author. Each query is fast, but together they are slow, mostly because of the round trips. The fix is to load the authors for the whole list together, with a JOIN or with one more query that uses WHERE id IN. In an ORM this is eager loading, with an option such as include or relations. I find the problem in the query log, where the same query repeats with different IDs. EXPLAIN on one query does not show it. I use EXPLAIN afterwards, to check that the new query uses an index.

A strong answer covers

  • Names the N+1 problem: one query for the list plus one for each item
  • Explains how lazy loading or a loop in an ORM causes it
  • Gives the fixes: a JOIN or eager loading, or batching with WHERE IN
  • Says how to spot it: the query log shows the same query many times

Likely follow-up

When is one big JOIN worse than two separate queries?

Where can you cache data in a web application, and how do you keep the cache correct?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

An API answers your client with this response. Why do APIs do this, and how should the client react?

  • Senior
HTTP/1.1 429 Too Many Requests
Retry-After: 30

The model answer to this senior question opens with a year in the app. What a year includes

How do you process webhooks or queue messages reliably when the same one can arrive twice?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

When do you choose REST, an RPC style such as gRPC, or GraphQL for an API?

  • Core
Show the model answer

I choose by who the clients are. REST fits a public API and most web APIs. It uses plain HTTP, every tool understands it, and GET responses can be cached by browsers and CDNs. gRPC fits calls between my own services. The contract is a Protocol Buffers file, the client and server code is generated from it, and the messages are small and binary over HTTP/2. It also has streaming in both directions. The cost is that browsers cannot call it directly without a proxy, and it is harder to read and debug by hand. GraphQL fits a product with many screens and several client apps that need different shapes of the same data. The client asks for exactly the fields it needs in one request. The cost moves to the server: every field needs a resolver, caching is harder because most queries are POST requests, and one deep query can be very expensive, so I limit query depth and cost.

A strong answer covers

  • Matches each to a case: public API, service to service, many different clients
  • Says gRPC uses a Protocol Buffers contract and generated code over HTTP/2
  • Says browsers need a proxy to call gRPC
  • Names the costs of GraphQL: harder HTTP caching, N+1 in resolvers, expensive queries
  • Says one system can use more than one style

Likely follow-up

How do you stop one GraphQL query from asking for so much data that it slows the server down?

How do you change an API that other teams already use without breaking their clients?

  • Core
Show the model answer

First I separate safe changes from breaking ones. Adding an optional field to a request, a new field to a response, or a new endpoint is safe, as long as clients ignore fields they do not know. Removing or renaming a field, changing its type or meaning, making an optional field required, or adding a new value to an enum that clients switch on can all break someone. For a breaking change I use expand and contract. I add the new field or endpoint next to the old one, so both work. I tell clients, mark the old one as deprecated, and can send a Sunset header with the date it will go away. I measure who still calls the old version, and I remove it only when that traffic is gone. A new major version, such as v2 in the path, is for a change that is too big for this, and I keep v1 running for an agreed time.

A strong answer covers

  • Lists safe changes: new optional fields, new endpoints
  • Lists breaking changes: remove, rename, change a type, make a field required
  • Describes expand and contract: old and new side by side, then remove the old
  • Measures real usage of the old version before removing it
  • Says clients must ignore unknown fields

Likely follow-up

Is adding a new value to an enum in a response a breaking change? When?

Walk me through the OAuth 2 authorization code flow with PKCE, step by step.

  • Core
GET https://auth.example.com/authorize
  ?response_type=code
  &client_id=web-app
  &redirect_uri=https://app.example.com/callback
  &scope=openid profile
  &state=af0ifjsldkj
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
Show the model answer

First the app creates a random secret, the code verifier, and keeps it. It hashes it with SHA-256 and encodes it as base64url. That is the code challenge. Then it sends the user to the authorization server, like this request, with the challenge and a random state value. The user logs in there, not in my app, and agrees to the scopes. The server sends the browser back to the redirect URI with a short-lived code and the same state. My app checks that the state matches, so the response belongs to a login it started. Then it sends the code and the original verifier to the token endpoint. The server hashes the verifier and compares it with the challenge. Only then does it return an access token, and often a refresh token and an ID token. PKCE means a stolen code is useless without the verifier. Current best practice uses PKCE for every client, and the redirect URI must match exactly.

A strong answer covers

  • Creates a code verifier and sends only its SHA-256 hash as the challenge
  • Says the user logs in at the authorization server, not in the app
  • Checks the state value on return to stop a forged callback
  • Swaps the code and the verifier for tokens at the token endpoint
  • Says PKCE makes a stolen code useless, and is now used for all clients

Likely follow-up

Why was the implicit flow, which returned the token in the URL, dropped?

You put a CDN in front of your API. Which caching headers do you send, and how do you avoid serving one user's data to another?

  • Core
Show the model answer

I decide per endpoint whether the response is the same for everyone. For public data, such as a product list, I send Cache-Control public with a short max-age for browsers and a longer s-maxage, which only shared caches like the CDN use. stale-while-revalidate lets the CDN serve the old copy while it fetches a new one. I also send an ETag. When a client sends If-None-Match with that value and nothing changed, I answer 304 Not Modified with no body, which saves bandwidth. For anything that depends on the user, I send private, so only the browser may keep it, or no-store for sensitive data. If a response changes with a request header, such as Accept-Language, I list it in Vary, so the CDN keeps separate copies. A shared cache does not store a response to a request with an Authorization header unless I allow it explicitly. When data changes, I purge the CDN by URL or by tag.

A strong answer covers

  • Uses s-maxage for the CDN and max-age for the browser
  • Marks per-user responses private or no-store
  • Explains ETag, If-None-Match and 304 Not Modified
  • Uses Vary for headers that change the response
  • Has a purge plan for when the data changes

Likely follow-up

Why can a Set-Cookie header in a cached response be dangerous?

Your service calls another service. How do you set timeouts and retries, and what is a retry storm?

  • Core
Show the model answer

Every outbound call gets a timeout, because a call with no timeout can hold a thread or a connection forever. I set it from the measured latency of the other service, a bit above its slow tail, and inside the deadline of my own request. I retry only errors that can pass: timeouts, connection errors, 503 and 429. I do not retry a 400, because it will fail again. I retry only idempotent calls, or calls with an idempotency key. Between attempts I use exponential backoff with jitter. The wait doubles each time up to a cap, and a random part spreads the clients out. A retry storm is when a slow service gets more traffic because everyone retries, so it gets even slower. Retries also multiply across layers: three layers that each make three attempts send 27 calls to the bottom service. So I retry in one layer only, keep a retry budget, and add a circuit breaker that stops calls for a while.

A strong answer covers

  • Puts a timeout on every outbound call, based on measured latency
  • Retries only errors that can pass, and only idempotent calls
  • Uses exponential backoff with jitter and a cap
  • Explains how retries multiply across layers into a storm
  • Names a guard: retry in one layer, a retry budget or a circuit breaker

Likely follow-up

How does a circuit breaker decide when to let calls through again?

What do at-most-once, at-least-once and exactly-once delivery mean, and why is exactly-once really idempotent processing?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

A client asks your API to generate a large report that takes several minutes. How do you design that endpoint?

  • Core
POST /reports HTTP/1.1
Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7

HTTP/1.1 202 Accepted
Location: /operations/481
Retry-After: 5

GET /operations/481 HTTP/1.1

HTTP/1.1 200 OK
{"status": "running", "progress": 40}
Show the model answer

I do not keep the HTTP request open for minutes, because proxies and load balancers close idle connections and a failed request leaves the client unsure. Instead the POST saves a job, puts it on a queue, and returns 202 Accepted at once. The Location header points to a status resource for the operation. The client polls that resource, and Retry-After tells it how often. The status is one of a few values, such as queued, running, succeeded or failed. When it succeeds, the status includes a link to the result, for example the report file. When it fails, it includes an error the client can show. If the client is a server, it can give me a callback URL, and I call it when the job finishes. That is a webhook, so I sign it and retry it. The POST takes an idempotency key, so a retry does not start the same report twice.

A strong answer covers

  • Returns 202 Accepted with a Location to a status resource
  • Defines clear states: queued, running, succeeded, failed
  • Links to the result when done and returns an error when failed
  • Offers a signed callback as an option for server clients
  • Makes the create idempotent so retries do not start duplicate jobs

Likely follow-up

How long do you keep finished operations and their results, and who may read them?

What is the difference between a liveness check and a readiness check, and how does a service shut down gracefully?

  • Core
Show the model answer

A liveness check asks whether the process is stuck. If it fails, the platform restarts the container. So it checks only the process itself, and never the database. If the database is down, restarting every instance does not help and can make things worse. A readiness check asks whether this instance can take traffic now. If it fails, the load balancer stops sending requests to it, but it is not restarted. It is right for it to fail during start-up, while caches warm, or when a needed dependency is not reachable. For graceful shutdown, the platform sends SIGTERM and, after a grace period, SIGKILL. In Kubernetes the default grace period is 30 seconds. On SIGTERM I fail readiness, wait a moment so the load balancer notices, stop accepting new connections, let requests in flight finish, stop taking new jobs from queues, close database pools, and exit. A hard timeout makes sure the process exits before SIGKILL arrives.

A strong answer covers

  • Says a failed liveness check restarts and a failed readiness check removes from traffic
  • Keeps dependencies out of the liveness check
  • Describes SIGTERM, a grace period, then SIGKILL
  • Orders the shutdown: fail readiness, drain requests, close connections, exit
  • Stops taking new queue jobs during shutdown

Likely follow-up

Some requests still fail with connection errors during a deploy. What could cause that?

When do you split a monolith into microservices, and when do you keep the monolith?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

An order service must save an order and tell other services about it. How do you keep the data consistent without a transaction across services?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

You stream live updates to browsers. On the server side, what changes between Server-Sent Events, WebSockets and long polling?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

How do you validate the input of an API endpoint, and what do you return when it is invalid?

  • Core
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/errors/validation",
  "title": "The request has invalid fields",
  "status": 422,
  "errors": [
    { "field": "email", "code": "invalid_format", "message": "Enter a valid email" },
    { "field": "quantity", "code": "too_small", "message": "Must be at least 1" }
  ]
}
Show the model answer

I validate at the boundary, before any business code runs, with a schema for the body, the query and the path. The schema checks types, required fields, lengths, ranges and formats, and it rejects or drops fields I do not expect, so a client cannot set a field such as role. After that, the rest of the code works with a typed, trusted object. Business rules that need data, such as whether the product is in stock, come later in the service. For errors I separate two cases. If the body cannot be parsed at all, for example broken JSON, I return 400. If it is well formed but the values are wrong, many APIs return 422, like this. I return all the field errors at once, not only the first. Each error has the field, a stable code that a client can program against, and a message for people. The format here follows Problem Details. I never put stack traces or SQL errors in the response.

A strong answer covers

  • Validates at the boundary with a schema, before business logic
  • Rejects unknown fields so a client cannot set protected ones
  • Separates 400 for unparseable input from 422 for invalid values
  • Returns every field error with a field, a stable code and a message
  • Never leaks stack traces or internal errors

Likely follow-up

Where do you check a rule such as the end date must be after the start date, and why?