Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
Chaturmind
← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 8+ Years (Senior & Lead)Testing Strategy & API Design
✓ FreeAdvanced· 12 min read

REST Principles, Status Codes & Resource Design — Interview Questions

What makes an API truly RESTful (Richardson Maturity Model), REST vs "RESTful" services, statelessness trade-offs, partial updates, idempotency, modelling many-to-many relationships, nested resources, pagination (offset vs cursor), HATEOAS, API-first design, and choosing status codes — 201 vs 202, validation failures (400 vs 422), 401 vs 403, 204 for DELETE and whether DELETE returns a body, GET with a body, 409 Conflict, idempotent POST responses, PUT returning 201, and 503 with Retry-After.

Published September 25, 2026


How to use this lesson

API design questions reward consistency and client empathy. Pick conventions, explain why, and make them uniform across services (a style guide, linting with Spectral). Status codes matter, because clients, gateways and retry logic depend on them.

Q1. What makes an API truly RESTful? Explain the Richardson Maturity Model. What's the difference between "REST services" and "RESTful web services"?

Short answer: REST (Roy Fielding) is an architectural style, with these constraints:

  • client-server;
  • stateless requests;
  • cacheable responses;
  • a uniform interface: resources identified by URIs, manipulated through representations, self-descriptive messages, and HATEOAS (hypermedia as the engine of application state);
  • a layered system;
  • optionally, code on demand.

The Richardson Maturity Model grades HTTP APIs:

  • Level 0: one endpoint and one method (RPC over HTTP, SOAP-style POST to /api).
  • Level 1: resources, with distinct URIs (/orders/42).
  • Level 2: HTTP verbs and status codes used properly (GET, POST, PUT, PATCH, DELETE; 201, 404, 409…). Most "REST APIs" in practice live here.
  • Level 3: hypermedia controls: responses include links telling clients what they can do next.

"REST service" vs "RESTful web service": they're used interchangeably. Strictly, "RESTful" means adhering to the REST constraints, while many APIs called "REST" are just JSON over HTTP (Level 1–2). Being honest about that nuance is a good answer.

Learn it in depth → API Contract Design

Q2. Why does statelessness matter in REST? What are its pros and cons?

Short answer: Stateless means that each request carries everything the server needs (authentication token, parameters). The server keeps no client session state between requests; the resource state lives in the database.

  • Pros:
    • horizontal scalability (any instance can serve any request, with no sticky sessions);
    • resilience (instances can die freely);
    • cacheability;
    • simpler load balancing;
    • easier reasoning and retries.
  • Cons:
    • bigger requests (tokens on every call);
    • repeated work (re-validating tokens, re-loading context), mitigated with caching;
    • multi-step workflows need state in resources (a draft order, a checkout session resource) or client-held state;
    • token revocation is harder than for server sessions.

Q3. How would you design an endpoint for partially updating a resource?

Short answer: Use PATCH /resources/{id}, with an explicit patch format:

  • JSON Merge Patch (RFC 7396, application/merge-patch+json): send only the changed fields, and null removes a field. It's simple, but it can't express "set to null" vs "remove" distinctly, or array element operations.
  • JSON Patch (RFC 6902, application/json-patch+json): a list of operations (add, remove, replace, move, test). It's precise, with array support, and test gives conditional updates.

Design points:

  • validate the merged result (not just the patch);
  • use optimistic concurrency (If-Match with an ETag, returning 412 on mismatch, or 428 if it's required and missing);
  • enforce field-level authorisation (which fields a caller may change);
  • for state transitions, prefer action sub-resources (POST /orders/{id}/cancel), not a PATCH of status;
  • return 200 with the updated representation, or 204.

Q4. How do you ensure idempotency in RESTful services? What's the correct response to an idempotent POST?

Short answer:

  • By method: GET, HEAD, OPTIONS, PUT and DELETE are idempotent by definition. Implement them so that repeats have no extra effect: PUT replaces the full state, and DELETE of an already-deleted resource returns 204 or 404, with the same resulting state.
  • Making POST idempotent (creation and payments): require an Idempotency-Key header (a client-generated UUID):
    1. the server stores (key, request fingerprint, response status and body) atomically, with a TTL;
    2. the first request processes normally;
    3. retries with the same key get the stored response replayed (for example the same 201 with the same Location and body). In-flight duplicates get 409, or wait;
    4. the same key with a different payload gets 422/409.
  • Alternatives:
    • client-generated IDs with PUT /orders/{uuid} (naturally idempotent);
    • natural keys with unique constraints (an external reference).
  • Downstream: propagate the idempotency keys to payment providers and message consumers.

Q5. How would you model a many-to-many relationship in a REST API?

Short answer: Either:

  • As a sub-collection of links: PUT /users/{userId}/roles/{roleId} (idempotently add), DELETE /users/{userId}/roles/{roleId} (remove), GET /users/{userId}/roles (list), and the reverse GET /roles/{roleId}/users if it's needed;
  • As a first-class association resource, when the relationship has its own data (enrolment date, grade, membership role): POST /enrollments {studentId, courseId, …}, GET /enrollments?studentId=…, DELETE /enrollments/{id}.

Choose the association resource whenever the link has attributes, a lifecycle or permissions of its own. Support bulk operations for large link sets.

Q6. Should DELETE return a body? Is 204 No Content correct for DELETE?

Short answer:

  • 204 No Content is the most common and correct response for a successful DELETE with nothing useful to return.
  • 200 OK with a body is fine when you return something meaningful: the deleted representation, or a status ("scheduled for deletion").
  • 202 Accepted is for asynchronous deletion (a job ID, or a status URL).
  • Repeated DELETEs: return 204 (the state is already achieved: an idempotent outcome), or 404 (the resource doesn't exist). Both are acceptable; pick one convention, and document it. Soft deletes often return 204.

Q7. How do you structure nested resources (such as /users/{id}/orders)?

Short answer:

  • Nest to express ownership or containment, one or two levels deep: /users/{userId}/orders (the user's orders), /orders/{orderId}/lines.
  • Avoid deep nesting (/users/1/orders/2/lines/3/discounts/4). Once a child has a globally unique ID, give it a top-level URI too (/orders/{orderId}), and use query filters for other views (/orders?userId=1&status=PAID).
  • Authorisation: nested paths must still check that the parent really owns the child (/users/1/orders/99 must not expose user 2's order 99).
  • Consistency: use plural nouns, kebab-case, no verbs in paths (except for action sub-resources like /cancel), and a stable ID format.

Q8. How do you design pagination in REST APIs? Cursor vs offset?

Short answer:

  • Offset/limit (?page=3&size=50, or offset/limit):
    • easy, and supports jumping to arbitrary pages and total counts;
    • slow for deep pages (the database scans and discards the offset rows);
    • inconsistent under concurrent inserts or deletes (duplicates or skipped items).
    • Good for small admin lists.
  • Cursor (keyset) pagination (?limit=50&cursor=eyJjcmVhdGVkQXQiOi4uLn0):
    • the cursor encodes the last item's sort key(s) (for example createdAt plus id), and the next page queries WHERE (created_at, id) < (:ts, :id) ORDER BY created_at DESC, id DESC LIMIT 50;
    • fast at any depth (it uses the index);
    • stable under inserts;
    • but no random access and no cheap total count.
    • Good for feeds, large lists, and infinite scroll.
  • The response shape: include items, nextCursor (opaque, base64 or signed), and optionally prevCursor/hasMore, or Link headers (rel="next"). Cap the page size, and document the sort order.

Q9. What is HATEOAS, and what are its practical uses?

Short answer: Hypermedia As The Engine Of Application State: responses include links (and affordances) describing the available next actions and related resources, so clients discover transitions, instead of hard-coding URLs and business rules:

{ "id": "42", "status": "PAID",
  "_links": { "self": {"href": "/orders/42"},
              "cancel": {"href": "/orders/42/cancel", "method": "POST"},
              "invoice": {"href": "/orders/42/invoice"} } }

Practical uses:

  • state-dependent actions (show "cancel" only when cancellable);
  • pagination links;
  • discoverable, evolvable APIs (URLs can change);
  • public APIs with generic clients.

Spring supports it through Spring HATEOAS (HAL, HAL-FORMS). The reality: most internal APIs stay at Level 2, because clients are generated from OpenAPI, and hypermedia adds payload and complexity. It's valuable when workflow logic should be server-driven.

Q10. When should you return 201 or 202?

Short answer:

  • 201 Created: the resource was created synchronously. Return a Location header with the new URI (and usually the representation).
  • 202 Accepted: the request was accepted for asynchronous processing, and isn't complete yet (a long-running import, report generation, an order sent to a queue). Return a status monitor resource (Location: /jobs/123, or a body with the job ID and a status URL), where the client polls, or gets a webhook.

Common trap: returning 201 for work that is only queued. Clients then assume the resource exists.

Q11. Which status code is best for a failed validation? When should you use 422?

Short answer:

  • 400 Bad Request: the request is malformed, or fails syntactic or schema validation (invalid JSON, wrong types, missing required fields, out-of-range values). It's Spring's default for MethodArgumentNotValidException.
  • 422 Unprocessable Content (RFC 9110): the request is well-formed and understood, but semantically invalid: business rule violations (end date before start date, an insufficient balance for this operation, an unknown SKU reference).

Many APIs use 400 for all validation errors, and some use 422 for semantic ones. Consistency matters most. Return Problem Details with field-level errors either way.

Q12. What's the difference between 401 and 403?

Short answer:

  • 401 Unauthorized (really "unauthenticated"): no valid authentication was provided (a missing, expired or invalid token). It must include a WWW-Authenticate header describing how to authenticate. The client should log in or refresh the token.
  • 403 Forbidden: the client is authenticated (or it doesn't matter), but not allowed to perform this action on this resource (a missing role or scope, or not the owner). Re-authenticating won't help.

Security nuance: for resources that the caller shouldn't even know exist, return 404 instead of 403, to avoid leaking their existence.

Q13. Can a GET request have a body? Why is it discouraged?

Short answer: HTTP doesn't forbid it, but a body on a GET has no defined semantics (RFC 9110). Proxies, caches, CDNs, load balancers and some clients may drop it, or reject it, and caching keys ignore bodies, so you get unpredictable behaviour. Elasticsearch famously accepts GET bodies, but also accepts POST for the same search. The alternatives for complex queries:

  • query parameters (with a reasonable length);
  • POST /search (a query resource), accepting that it's not cacheable by default;
  • the new QUERY HTTP method (an IETF draft) for safe, idempotent requests with bodies, once support spreads.

Q14. When should you return 409 Conflict?

Short answer: When the request conflicts with the current state of the resource:

  • duplicate creation (a unique email or username already exists);
  • invalid state transitions (cancelling an already-shipped order; some teams use 422 for this);
  • optimistic concurrency conflicts without conditional headers (a version mismatch in the body). With If-Match, prefer 412 Precondition Failed;
  • concurrent idempotency-key processing.

Include details in Problem Details (the conflicting field, or the current state), so the client can resolve it.

Q15. Can PUT return 201 Created? When?

Short answer: Yes. PUT has create-or-replace semantics on a client-specified URI. If the resource didn't exist, and PUT created it, return 201 Created. If it replaced an existing resource, return 200 OK (with the body) or 204 No Content. For example, PUT /configurations/{tenantId}/theme, or PUT /orders/{clientGeneratedUuid}. This also gives natural idempotent creation.

Q16. What does 503 mean, and when would you use the Retry-After header?

Short answer: 503 Service Unavailable means the server is temporarily unable to handle the request: overload, maintenance, a dependency outage or circuit breaker open, or a readiness failure. It signals that the problem is transient, so clients may retry. Retry-After (seconds, or an HTTP date) tells clients when to retry. It's used with 503 (maintenance windows, load shedding) and 429 Too Many Requests (rate limits). Well-behaved clients and SDKs honour it, instead of hammering the server. Distinguish it from 502/504 (upstream gateway errors) and 500 (unexpected server bugs, which usually aren't worth blind retries).

Q17. What is API-first design?

Short answer: Designing the API contract before implementing it:

  1. write an OpenAPI (or AsyncAPI, for events) specification collaboratively with the consumers;
  2. review it for consistency (style guides, linting with Spectral);
  3. mock it (Prism, WireMock), so the frontend and other teams can start in parallel;
  4. generate server interfaces or stubs and client SDKs (OpenAPI Generator);
  5. implement against the contract, and verify conformance in CI (contract tests, request and response validation).

The benefits:

  • consumer-centred APIs;
  • parallel development;
  • consistent conventions across teams;
  • earlier detection of design problems;
  • documentation and SDKs for free;
  • a clear place to manage versioning and breaking-change checks (openapi-diff in CI).

Follow-up questions this topic invites — and their answers

Q: What's the difference between 200 and 204 for updates? A: 200 returns the updated representation in the body (convenient for clients). 204 returns nothing (less payload). Choose per API style, and be consistent.

Q: How should errors be formatted? A: RFC 9457 Problem Details (application/problem+json): type, title, status, detail, instance, plus extensions (errors, traceId, code). Use a consistent format across all services.

Q: What are ETags for? A: Caching (If-None-Match gives 304 Not Modified) and optimistic concurrency (If-Match gives 412 on mismatch). Spring supports shallow ETags with ShallowEtagHeaderFilter, or explicit ETags through ResponseEntity.eTag(...).

Q: What status code do you use when a rate limit is hit? A: 429 Too Many Requests, with Retry-After, and optionally RateLimit-* headers (an IETF draft) describing the quota and reset time.

Previous

MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions

Next

OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

AI Tutor

Lesson: REST Principles, Status Codes & Resource Design — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.