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

Members can save this page, take notes and track progress. See membership · Sign in

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

← All API Design questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake