Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

A security review found that some services validate only in the controller, while internal message consumers and batch jobs call the same services without validation. What would you change?

I would stop treating the controller as the only gate and validate at every entry point: HTTP, message consumers and batch jobs. The application services get method validation with @Validated so any caller is checked, the core rules move into the domain objects so they hold no matter who calls, each entry point gets tests that send invalid input, and new entry points are reviewed for validation as part of design reviews.

Why this question is asked

Security reviews often find this pattern. The team validated carefully in the REST controllers, because that is where the tutorials put @Valid. Later, someone added a Kafka consumer and a nightly import job that call the same service directly, and those paths accept anything. An attacker, or simply a buggy upstream system, can then push a negative amount or an oversized string through the side door. Interviewers ask this scenario to see whether we think of validation as a property of the system rather than of one framework layer. In this answer, we will look at why controller-only validation leaves gaps, then go through the layers we add: entry point validation, method validation on services, domain invariants, tests and design reviews.

1Why Validating Only in the Controller Leaves Gaps

An entry point is any place where data from outside our code enters the system: an HTTP endpoint, a message listener, a batch reader that parses a file, a scheduled job that reads another team's table, or a gRPC method. Each one is a trust boundary, because the data comes from someone we do not control.

When validation lives only in the controller, the rule effectively belongs to HTTP, not to the business operation. The service method assumes its input is clean because, on the day it was written, the only caller was the controller. The message consumer and the batch job break that assumption silently, and nothing fails until bad data is already in the database.

Step throughWhere checks belong
  1. Entry pointsHTTP, Kafka listener, batch reader: shape and size of the input
  2. Application service@Validated methods: the operation's input contract for every caller
  3. Domain objectsconstructors and methods keep invariants that must always hold
  4. DatabaseNOT NULL, CHECK and unique constraints as the last safety net

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

Each layer catches what the one above might miss; no single layer is trusted alone.

2Validate at Every Entry Point

Each entry point checks the shape of what it received before doing anything else: required fields, sizes, formats. For HTTP we keep @Valid on request bodies. For a Kafka consumer we validate the deserialized payload, either with an injected Validator or with the framework's support for validating listener payloads (Spring for Apache Kafka can be given a validator for @Valid payloads; check your version). Invalid messages are not retried forever; they go to a dead-letter topic with the reason. For Spring Batch, a BeanValidatingItemProcessor validates each item, and the step's skip policy decides whether a bad row is skipped and logged or fails the job.

Java
@KafkaListener(topics = "transfers")
void onTransfer(TransferMessage msg) {
Set<ConstraintViolation<TransferMessage>> errors = validator.validate(msg);
if (!errors.isEmpty()) {
throw new InvalidMessageException(errors); // error handler sends it to transfers.DLT, no retry
}
transferService.transfer(msg.from(), msg.amount());
}

Notice that the entry point check is about the message format. It cannot know every business rule, and it should not have to, which is why the next layer exists.

3Method Validation on Application Services

The application service is the one place every entry point passes through, so its method contract should be enforced there. We annotate the service class with @Validated and put constraints on its parameters. Spring Boot's MethodValidationPostProcessor then wraps the bean in a proxy that validates every call, whoever makes it, and throws ConstraintViolationException on failure.

Java
@Service
@Validated
public class TransferService {
public void transfer(@NotBlank @Size(max = 34) String from,
@NotNull @Positive @Digits(integer = 12, fraction = 2) BigDecimal amount) {
...
}
}
transferService.transfer("ACC-1", new BigDecimal("-10")); // ConstraintViolationException from any caller

Two details matter. A call from inside the same class skips the proxy, so internal helper methods are not checked; that is acceptable when the public method already validated. And a ConstraintViolationException from a service should be logged and counted, because once the entry points validate properly, it usually means a caller has a bug.

4Keep Domain Invariants in the Domain Objects

Annotations can be bypassed: someone can construct an object directly, a test can skip the proxy, a new framework may not run the validator. The rules that must always be true, called invariants, are safest inside the objects themselves. A Money value object that refuses to exist with a negative amount protects every code path, including ones written next year.

Java
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(currency, "currency");
if (amount == null || amount.signum() <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
if (amount.scale() > currency.getDefaultFractionDigits()) {
throw new IllegalArgumentException("too many decimals for " + currency);
}
}
}
new Money(new BigDecimal("10.00"), Currency.getInstance("EUR")); // ok
new Money(new BigDecimal("10.001"), Currency.getInstance("EUR")); // IllegalArgumentException

So the layers work together. The entry point rejects malformed input early with a clear error for the sender. The service validates its contract for every caller. The domain object makes the invalid state impossible to represent, and database constraints catch whatever still slips through.

5Tests for Each Entry Point and Reviews for New Ones

The review found the gap because no test sent bad data through the consumer or the job. So we add one test per entry point that sends invalid input and checks the outcome: a 400 for HTTP, a dead-letter record for Kafka, a skipped and logged row for batch. These tests are cheap and they turn the security finding into a rule the build enforces.

Finally, we make it part of the process. The design review template for any new entry point asks where its input is validated, what happens to invalid input, and whether it goes through the validated service. A new consumer then cannot quietly repeat the mistake that the review found.

6Follow-up questions

Is it not wasteful to validate the same data in several layers?

The cost is small: a few microseconds per check, against a database write or a network call that takes milliseconds. What we gain is that each layer can be trusted on its own. The checks are also not exactly the same: the entry point checks format, the service checks its contract, and the domain checks invariants, so duplication is less than it looks.

What should a consumer do with a message that fails validation?

It should not retry it, because retrying invalid data never succeeds and only blocks the partition. We send it to a dead-letter topic with the reason, increment a metric, and alert when the rate rises. Someone can then fix the producer and replay the messages if needed.

Where do rules that need the database belong, such as whether an account exists?

In the service layer, as business rules with typed errors such as AccountNotFoundException. They need data and transactions, so they do not fit in annotation-based validation, which should stay fast and free of side effects.

7Conclusion

In this answer, we treated the review finding as a system problem rather than a controller problem. We validated at every entry point, put method validation on application services so that every caller is checked, moved the rules that must always hold into domain objects, added tests that send bad input through each entry point, and made validation a standing question in design reviews for new entry points.

What to say in the interviewAbout 80 seconds aloud

Open with

The root problem is that validation was tied to HTTP instead of to the operation. I'd fix it in layers. First, every entry point validates what it receives: controllers keep @Valid, Kafka consumers validate the payload and send invalid messages to a dead-letter topic instead of retrying them, and batch jobs use a validating item processor with a skip policy.

Then, if they want more

Second, the application services get @Validated with constraints on their parameters, so Spring's method validation proxy checks every call no matter where it came from. I'd log those violations, because once entry points validate, a violation at the service means a caller has a bug.

Third, the rules that must always be true, like a positive amount with the right number of decimals, go into domain objects such as a Money value object that throws in its constructor, so even code that bypasses Spring can't create invalid state; database constraints are the last net.

Then I'd add one test per entry point that sends bad input and checks the outcome, so the build enforces what the review found. And I'd add a question to the design review template for any new entry point: where is the input validated and what happens to invalid input.

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 "A security review found that some services validate only in the controller, while...": https://scrivio-interview-library.netlify.app/spring-boot/request-validation/084a67eb36/