Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

Where should validation happen: in the controller, the service, the entity or the database? Explain the role of each.

Each layer validates what it is best placed to know. The controller checks the shape of the input, such as required fields and formats, and answers 400 with details. The service checks business rules that need context, such as stock, limits or permissions. The entity and the database enforce invariants such as not null, unique and foreign keys as the last guard. Client-side checks are only for the user's convenience, and complex rules should live in one place rather than being copied into every layer.

Why this question is asked

Ask five developers where validation belongs and we may get five answers, and a codebase that follows all five at once: the same rule written in a React form, a DTO annotation, a service if statement and a database trigger, each slightly different. Interviewers ask this question to see whether we can reason about responsibility rather than recite annotations. In this answer, we will follow one order request through the layers, see what each layer can and cannot know, show the checks in code, and decide how to avoid duplicating complex rules.

1A Quick Recap of the Layers

A typical Spring application has a controller that turns HTTP requests into Java objects, a service that runs the business logic inside a transaction, entities that JPA maps to tables, and the database itself. Each layer sees different information. The controller sees only the request. The service sees the request plus everything it can load: the customer, the product, the current stock. The database sees every write from every application and every script, including the ones that bypass our Java code.

So the question is not which layer is right, but which layer knows enough to check a given rule. That gives a clear division.

Step throughWhat each layer validates
  1. Browser or mobile clientinstant feedback for the user, never trusted
  2. Controllershape: required fields, formats, lengths -> 400
  3. Servicebusiness rules with context: stock, limits, permissions -> 409 or 422
  4. Entityinvariants of the object itself, checked before saving
  5. DatabaseNOT NULL, UNIQUE, foreign keys, CHECK: the last guard

5 layers, from the top down. Step through them one at a time.

2The Controller Checks the Shape of the Input

At the edge we reject requests that are malformed on their face: a missing product id, a quantity of minus three, an email without an @. These checks need nothing but the request itself, so Bean Validation annotations on the DTO are the natural tool.

Java
public record PlaceOrder(
@NotNull Long productId,
@Positive int quantity,
@Size(max = 500) String note) {}
@PostMapping("/orders")
ResponseEntity<OrderDto> place(@Valid @RequestBody PlaceOrder req) { ... }
// {"quantity": -3} -> 400 Bad Request
// productId: must not be null
// quantity: must be greater than 0

The reason to stop these requests here is cost and clarity. They never open a transaction or touch the database, and the client gets a 400 that lists every field problem at once, which is exactly what a form needs to show errors.

3The Service Checks Rules That Need Context

Whether there are enough items in stock, whether this customer may order this product, whether the order exceeds a credit limit: none of this can be known from the request alone. It needs data loaded inside the transaction, so it belongs in the service.

Java
@Transactional
public Order place(PlaceOrder req, User user) {
Product p = products.findById(req.productId()).orElseThrow(() -> new NotFound("product"));
if (!p.isSellableTo(user.country())) throw new BusinessRuleViolation("NOT_SOLD_IN_COUNTRY");
if (p.stock() < req.quantity()) throw new BusinessRuleViolation("INSUFFICIENT_STOCK");
return orders.save(Order.create(p, req.quantity(), user));
}
// quantity 5, stock 2 -> 409 Conflict {"code": "INSUFFICIENT_STOCK"}

Notice that these errors are different in kind from the 400s. The request was well formed; the world just does not allow it right now. That is why they map to 409 or 422 with a business error code, and why they should be tested as business logic, not as input validation.

4The Entity and the Database Guard the Invariants

An invariant is something that must always be true, whatever code path wrote the data: an order always has a customer, an email is unique per account, a quantity is never negative. The entity can protect some of these in its constructor or methods, and JPA can run Bean Validation on entities before insert and update. But the only layer that sees every write, including batch jobs, migrations and other services, is the database.

Java
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(id),
quantity int NOT NULL CHECK (quantity > 0)
);
CREATE UNIQUE INDEX ux_account_email ON accounts (lower(email));
-- INSERT with quantity 0 -> ERROR: violates check constraint "orders_quantity_check"

Database constraints are also the only reliable answer to races. Two requests can both check that an email is free and both insert it; only the unique index stops the second one. So the service check gives a friendly error for the common case, and the constraint guarantees correctness, with the resulting DataIntegrityViolationException mapped to 409.

5Do Not Trust the Client, Do Not Copy Complex Rules

Client-side validation is valuable for the user, who sees an error before pressing submit, but it is not security. Anyone can call the API with curl, so every rule the client checks must also be checked on the server.

Simple shape rules, like a maximum length of 100, may appear in the form, the DTO and the column, and that duplication is cheap and useful because each layer protects itself. Complex rules are different. A discount eligibility rule written in three places will drift until the three versions disagree. Such a rule should have one home, usually the service that owns the data, and other layers ask it, for example through an endpoint that returns whether an order is eligible, rather than reimplementing it.

6Follow-up questions

Should entities carry Bean Validation annotations too?

They can, and Hibernate will check them before insert and update, which catches bugs in code paths that bypass the DTOs. But entity annotations should express invariants of the data, such as not null and length, not request rules like a password confirmation field. Mixing the two leads to entities that cannot be saved by batch jobs.

Why not put everything in the database with constraints and triggers?

The database is a strong last guard but a poor place for business logic. Errors come back as generic constraint violations that are hard to turn into helpful messages, triggers are hard to test and version, and rules that need data from other services cannot be checked there at all.

How do we return validation errors consistently across layers?

Use one error format, for example RFC 9457 ProblemDetail, with a type, a message and a list of field errors or a business code. A @ControllerAdvice maps MethodArgumentNotValidException to 400, business exceptions to 409 or 422, and DataIntegrityViolationException to 409, so clients handle every layer's error the same way.

7Conclusion

In this answer, we divided validation by what each layer knows. The controller checks the shape of the input and returns 400 with field details, the service checks business rules that need context such as stock and permissions, and the entity and database enforce invariants such as not null, unique and foreign keys as the last guard, including against races. Client-side checks are for the user only, and complex rules get one home instead of copies in every layer.

What to say in the interviewAbout 80 seconds aloud

Open with

I decide by asking which layer knows enough to check the rule. The controller only knows the request, so it checks the shape: required fields, formats, lengths and ranges, with Bean Validation annotations and @Valid, and returns 400 with all the field errors at once.

Then, if they want more

That is cheap and gives the client clear messages. The service knows the context, because it can load data inside the transaction, so business rules live there: enough stock, the customer is allowed to buy this, the credit limit is not exceeded. Those failures are a different kind of error, usually 409 or 422 with a business code.

The entity and the database protect invariants, things that must always be true no matter who writes the data, like not null, unique email or a positive quantity. The database is the only layer that sees batch jobs, scripts and other services, and it is the only real protection against races, so a unique index backs up any service check.

Client-side validation is only for the user's experience and never trusted. Simple rules like max length can repeat in each layer, but complex rules should have one home, the owning service, rather than being copied.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Where should validation happen: in the controller, the service, the entity or the...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/e646541813/