Quick revision
The short answer
Input guardrails check what the user sends before the model is called, such as size limits, personal data detection, banned topics and prompt injection heuristics. Output guardrails check the model's answer before the user sees it, such as validating structured output against a schema, catching leaked personal data or secrets, policy topics, and links or ids that do not exist. Three concrete checks in Java are parsing JSON output into a record and rejecting it on failure, regex plus Luhn checksum detection of card numbers, and verifying that cited ids exist in the retrieved set; on failure we retry with feedback, fall back to a safe answer or escalate to a person.
What to remember
In this answer, we saw that input guardrails check user input before the model call, with size limits, personal data detection, banned topics and injection heuristics, and output guardrails check the answer with schema validation, leak detection, policy checks and verification of links and ids. We wrote three Java checks, parsing JSON into a validated record, regex plus Luhn for card numbers, and checking cited ids against the retrieved set, placed them in LangChain4j guardrails or Spring AI advisors, and chose between retrying, falling back and escalating when they fail.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Input guardrails check what the user sends before the model is called, such as size limits, personal data detection, banned topics and prompt injection heuristics. Output guardrails check the model's answer before the user sees it, such as validating structured output against a schema, catching leaked personal data or secrets, policy topics, and links or ids that do not exist. Three concrete checks in Java are parsing JSON output into a record and rejecting it on failure, regex plus Luhn checksum detection of card numbers, and verifying that cited ids exist in the retrieved set; on failure we retry with feedback, fall back to a safe answer or escalate to a person.
Why this question is asked
A model's output is probabilistic, and users' input can be anything, including attempts to misuse the system. Guardrails are the ordinary code we put around the model call so that obviously bad input never reaches it and bad output never reaches the user. Interviewers ask this because it separates teams that ship an LLM demo from teams that ship a product. In this answer, we will define the two kinds of guardrails, write three output checks in Java, see how they fit into Spring AI and LangChain4j, and decide what to do when a check fails.
1A Quick Recap: Where Guardrails Sit
A guardrail is a check that runs before or after the model call and can block, change or flag the request or the answer. Input guardrails protect the model and the business from what users send. Output guardrails protect users and the business from what the model produces. Both are deterministic code where possible, with a model-based classifier only for judgements code cannot make.
- User message
- Input checks pass? (size, PII, topics, injection)YesCall the modelNoRefuse or redact, then answer safely
- Model answer
- Output checks pass? (schema, leaks, policy, ids)YesShow the answerNoRetry with feedback, fall back or escalate
4 steps in order. Play them, or step through them one at a time.
2Input Guardrails
Size limits come first: a cap on message length, for example 4,000 characters, protects cost and makes some attacks harder. Personal data detection looks for things like card numbers, national id numbers or health details that should not be sent to an external model, and either redacts them or asks the user not to share them. Banned topics are subjects the product must not handle, such as medical or legal advice in a shopping assistant, detected by keywords or a small classifier. Prompt injection heuristics flag text such as 'ignore your previous instructions' or attempts to make the bot reveal its system prompt.
Notice that heuristics for injection catch only the obvious cases. They are a useful filter, but the real protection against injection is limiting what the model can do, so input checks are one layer, not the whole defence.
3Check 1: Parse Structured Output Into a Record
When we ask the model for JSON, we must not trust that we got valid JSON with the right fields. Parsing it into a Java record with validation turns 'probably right' into 'definitely right or rejected'.
Spring AI's entity() and LangChain4j's typed return values do the parsing for us, but they throw on failure, so we still need to decide what happens then. Adding Jakarta Bean Validation catches values that parse but make no sense, like a confidence of 7.
4Check 2: Catch Card Numbers With Regex and a Checksum
A model might repeat a card number from a document or from earlier in the conversation. A regular expression finds candidate sequences of 13 to 19 digits, possibly with spaces or dashes, and the Luhn checksum, the check digit algorithm card numbers use, removes most false positives such as order numbers.
The same idea, a pattern plus a validity check, works for API keys with known prefixes and other secrets. When a match is found we mask it, for example showing only the last four digits, or block the answer.
5Check 3: Verify That Cited Ids Exist
In a retrieval-based answer, the model cites the sources it used. A model can invent a citation that looks real, such as a document id we never gave it, or a product link that does not exist. The check is simple: every cited id must be in the set of ids we actually retrieved for this request.
The same check applies to product ids, order ids and URLs in the answer: compare them with the catalogue or with the tool results of this request.
6Guardrails in Spring AI and LangChain4j
Both frameworks give these checks a home. LangChain4j has guardrail interfaces for inputs and outputs that can be attached to an AI service, and an output guardrail can ask for a retry with a message explaining what was wrong. Spring AI uses advisors, components that wrap each ChatClient call, so a custom advisor can inspect the request before the call and the response after it; it also ships a simple safeguard advisor for blocking sensitive words. The exact interfaces have changed between releases, so check your version. Whether we use the framework hooks or plain code around the call, the checks themselves are ordinary Java, which makes them easy to unit test.
7What to Do When a Check Fails
There are three responses, chosen per check. Retry with feedback: for a format problem, call the model again with a message such as 'your answer was not valid JSON, return only the JSON object', usually once or twice at most. Fall back to a safe answer: for a policy or leakage problem, replace the answer with a fixed message such as 'I cannot help with that here', or mask the sensitive part. Escalate to a human: for high-impact cases, such as a customer complaint or a repeated failure, pass the conversation to a person. Every failure is logged, because the failure rates tell us which prompts, models or features need work.
8Follow-up questions
Should guardrails use a model or plain code?
Plain code wherever the check can be expressed precisely: schemas, patterns, checksums, id lookups, length limits. Use a small classifier model for fuzzy judgements such as topic or tone, and accept that those are probabilistic, so they suit flagging rather than being the only safeguard.
Do guardrails add much latency?
Deterministic checks take microseconds to milliseconds. Classifier calls add a model round trip, so run them in parallel with the main call where possible, or only on risky routes.
Can output guardrails work with streaming responses?
Partly. Some checks, such as JSON validation, need the full answer, so structured outputs are usually not streamed. For streamed text, we can check chunks as they arrive for patterns like card numbers and stop the stream, and run full checks at the end.
9Conclusion
In this answer, we saw that input guardrails check user input before the model call, with size limits, personal data detection, banned topics and injection heuristics, and output guardrails check the answer with schema validation, leak detection, policy checks and verification of links and ids. We wrote three Java checks, parsing JSON into a validated record, regex plus Luhn for card numbers, and checking cited ids against the retrieved set, placed them in LangChain4j guardrails or Spring AI advisors, and chose between retrying, falling back and escalating when they fail.
Open with
Guardrails are checks around the model call. Input guardrails run before the call: a size limit on the message, detection of personal data like card or national id numbers so we redact it or warn the user, banned topics the product should not handle, and heuristics for prompt injection such as ignore your instructions, knowing those only catch obvious attacks.
Then, if they want more
Output guardrails run before we show the answer. Three checks I would implement in Java: first, parse structured output into a record with Jackson and Bean Validation and reject it if parsing or validation fails.
Second, scan the answer for card numbers with a regex for 13 to 19 digits and confirm with the Luhn checksum, so order numbers do not trigger it, then mask or block.
Third, in a RAG answer, check that every cited source id is in the set we actually retrieved for this request, and the same for product ids or links, so invented citations never reach the user.
In LangChain4j these can be input and output guardrails on an AI service, and in Spring AI they fit into advisors around ChatClient; I would check the exact interfaces for our version.
When a check fails I choose per check: retry once with feedback for format errors, fall back to a safe message for leaks or policy, or escalate to a person for high-impact cases, and log every failure.
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.
- Official documentation
- Spring AI reference
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 "What are input and output guardrails for an LLM application, and give three concrete...": https://scrivio-interview-library.netlify.app/spring-boot/ai-agents-and-mcp/d903226665/