API Design interview question · Most asked
Write an Express or FastAPI endpoint that creates an order idempotently.
Hands-on Asked in Backend Engineer · Full Stack Engineer · Native AI Engineer · Forward Deployed Engineer (FDE) · QA Engineer / SDET · Tech Lead interviews
Summary
Require an Idempotency-Key header, store the key with the request's result in the same transaction that creates
the order, and return the stored result when the same key arrives again. A unique constraint on the key makes
concurrent duplicates fail safely instead of creating two orders.
Longer Answer
Points to explain: scope keys per client, expire them after a day or so, return 409 if the same key is reused
with a different body, and do the work and the key insert in one transaction so a crash can't leave one without
the other.
Example
import hashlib, json
from fastapi import FastAPI, Header, HTTPException
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
app = FastAPI()
@app.post("/orders", status_code=201)
async def create_order(body: OrderIn, idempotency_key: str = Header(...), db: AsyncSession = Depends(get_db)):
fingerprint = hashlib.sha256(json.dumps(body.model_dump(), sort_keys=True).encode()).hexdigest()
existing = await db.scalar(select(IdempotentRequest).where(IdempotentRequest.key == idempotency_key))
if existing:
if existing.fingerprint != fingerprint:
raise HTTPException(409, "Idempotency key reused with a different request")
return existing.response
try:
order = Order(customer_id=body.customer_id, items=body.items, total=price(body.items))
db.add(order)
await db.flush()
response = {"id": order.id, "total": str(order.total)}
db.add(IdempotentRequest(key=idempotency_key, fingerprint=fingerprint, response=response))
await db.commit()
except IntegrityError: # a concurrent request with the same key won
await db.rollback()
existing = await db.scalar(select(IdempotentRequest).where(IdempotentRequest.key == idempotency_key))
return existing.response
return response
Key Points
- Client sends an Idempotency-Key.
- Unique constraint stops concurrent duplicates.
- Store the response; replay it on retry.
- Reject reuse with a different body.
Explanation
What interviewers look for
A correct, concurrency-safe implementation and the reasoning around it.
More API Design questions
- What makes an API RESTful, and what are good REST design practices?
- Compare offset pagination and cursor (keyset) pagination.
- An API endpoint that was fast is now taking seconds under load. Walk through your investigation.
- Write a SQL query that returns each customer's three most recent orders.
- Which HTTP methods are safe and idempotent, and why does it matter?
- Which HTTP status codes should an API use, and when?
- How do idempotency keys work for POST requests?
- How should you version an API?