Building a Production-Safe AI Endpoint with Java 21, Spring Boot, and Amazon Bedrock
Learn how to integrate Amazon Bedrock into a Java 21 and Spring Boot backend without exposing API keys or risking runaway token bills. This practical guide covers IAM authentication, Spring AI integration, token limits, and timeout guardrails.
Ingeniero de software | Desarrollador Java & Spring Boot
Most tutorials show how to call an LLM in ten lines of Python using a hardcoded API key. When you bring that pattern into a real Java 21 and Spring Boot backend, three production problems appear immediately: managing static API keys, blocking threads on slow model responses, and preventing a single user request from draining your monthly token budget.
By using Amazon Bedrock with Spring AI and IAM Roles, you can expose a clean, governed AI endpoint inside your existing Spring Boot microservice with zero external API keys.
1. Why Amazon Bedrock Fits a Java Backend
Instead of managing third-party vendor keys and separate billing accounts, Bedrock runs inside your AWS boundary:
Concern | External LLM API | Amazon Bedrock + Spring Boot |
|---|---|---|
Authentication | Static API key in .env | IAM Role (zero credentials in code) |
Data Privacy | Prompts leave your cloud | Prompts stay inside your AWS account |
Model Switching | Rewrite SDK client per vendor | Change one model ID in application.yml |
Cost Control | Separate billing dashboard | Native AWS Budgets and CloudWatch alarms |
2. Add Spring AI Bedrock Starter to pom.xml
Spring AI provides a native starter for the Amazon Bedrock Converse API, which works across models like Amazon Nova and Anthropic Claude without changing your Java code.
Add the Spring AI BOM and Bedrock starter to your
pom.xml :<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-bedrock-converse</artifactId>
</dependency>
</dependencies>
3. Configure Model Guardrails in application.yml
Never leave
max-tokens unbounded in production. Set explicit defaults for the region, model ID, temperature, and maximum output tokens in application.yml :spring:
ai:
bedrock:
aws:
region: us-east-1
converse:
chat:
options:
model: amazon.nova-lite-v1:0
temperature: 0.3
max-tokens: 500Using a lightweight model like Amazon Nova Lite with
max-tokens: 500 keeps latency low and prevents runaway responses while you test and scale.
4. Build a Bounded REST Controller
Keep your AI logic behind a clean service layer with input length validation. If a client sends a 50,000-character payload, reject it at the API boundary before it ever reaches Bedrock:
@RestController
@RequestMapping("/api/v1/assistant")
public class AssistantController {
private final ChatClient chatClient;
public AssistantController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder
.defaultSystem("You are a concise technical assistant. Answer in under 150 words.")
.build();
}
@PostMapping("/summarize")
public ResponseEntity> summarize(@RequestBody PromptRequest request) {
if (request.text() == null || request.text().isBlank() || request.text().length() > 4000) {
return ResponseEntity.badRequest()
.body(Map.of("error", "Input must be between 1 and 4,000 characters."));
}
String reply = chatClient.prompt()
.user(request.text())
.call()
.content();
return ResponseEntity.ok(Map.of("summary", reply));
}
public record PromptRequest(String text) {}
}
5. Scope the IAM Role Strictly
Attach an IAM Role to your EC2 instance or ECS task with permission to invoke only the specific foundation model you configured—never
bedrock:* :{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "InvokeSpecificBedrockModel",
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0"
}
]
}
6. Three Production Gotchas to Watch Out For
- Model Access Activation: Before your first call, open the Amazon Bedrock console → Model access in your target region and ensure the model status is enabled, or your app will throw an
AccessDeniedException.
- HTTP Client Timeouts: LLM responses take seconds, not milliseconds. Configure explicit read timeouts on your underlying AWS SDK HTTP client so slow generations do not tie up your Tomcat worker threads indefinitely.
- Structured Logging for Tokens: Log input character counts and response latency per request so you can spot expensive prompts early in CloudWatch.
Over to You
For backend engineers integrating generative AI into existing REST APIs:
- Are you calling Amazon Bedrock directly from your main backend service, or isolating AI calls into a separate worker/Lambda?
- Which foundation model has given you the best speed-to-cost ratio in production?
Share your architecture or lessons learned in the comments—I would love to compare setups!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article