Skip to the page

Spring REST APIs · senior

Idempotency keys and large uploads

Retries can charge twice unless the server remembers the request. Large uploads should not pass through the API's memory.

The notes

What you must know

  • Table idempotency_keys with a unique constraint on (user_id, key) and columns for request hash, status, response code and response body.
  • Flow: insert the key as IN_PROGRESS in a short transaction. If the insert hits the unique constraint (DataIntegrityViolationException), load the row: same hash and done gives the saved response; in progress gives 409; different hash gives 422.
  • Validate the header (present, length limit, UUID format) and scope keys per user. Keep keys 24 to 48 hours and delete old ones with a scheduled job.
  • Redis SET key value NX EX can be a fast lock, but the durable record belongs in the database. Test: two threads with the same key give exactly one charge.
  • Multipart defaults: spring.servlet.multipart.max-file-size is 1 MB and max-request-size is 10 MB. Bigger uploads throw MaxUploadSizeExceededException.
  • file.getBytes() loads the whole file into the heap. A few big uploads at once exhaust memory.
  • Better: the client uploads straight to object storage with a pre-signed URL (multipart, resumable). The API stores metadata and checks the result.
  • Check content by its bytes (file signatures, Apache Tika), not by file name or Content-Type. Scan for malware. The ingress body limit and timeouts must also allow big uploads.

The red pen

Common traps: mistake → fix

  • Mistake: Retrying a POST is always safe

    Fix: without an idempotency key it can repeat the action.

  • Mistake: Raising the upload limit solves it

    Fix: it moves the problem to memory.

  • Mistake: Content-Type tells me the file type

    Fix: the client controls it; check the bytes.

Easy to hard

Questions interviewers ask, easy to hard

  1. Mobile clients retry POST /payments and customers are charged twice. How do you fix it?
  2. What does the server do when the same key arrives while the first request is still running?
  3. Uploads over 1 MB fail. After raising the limit, pods run out of memory. Why?
  4. How would you design video upload for sellers?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview