eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

When working with large prompts, repeatedly sending the same context to the model can increase both latency and costs. This becomes especially noticeable when applications reuse large system instructions, documents, or conversation context across requests.

Prompt Caching in Spring AI with Anthropic addresses this by allowing frequently reused parts of a prompt to be cached and reused across requests, reducing the amount of work the model needs to process each time. This can improve response latency while lowering input-token costs.

In this tutorial, we’ll explain how prompt caching works, the limitations and requirements for different Claude models, and how to use it with Spring AI. We’ll also cover the main configuration options and practical considerations when applying caching in an application.

2. Dependencies

Let’s start by defining the minimum dependencies possible for demonstrating the Prompt Caching in Spring AI. We’ll only need spring-boot-starter-web and the spring-ai-starter-model-anthropic. The first is for the basic Spring Boot Application and auto-configuration. The latter contains the tools we’re exploring in this article, including Spring AI. The minimum version for Prompt Caching is 1.0.3, so we can go with:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.5.13</version>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-anthropic</artifactId>
    <version>2.0.1</version>
</dependency>

 3. Prompt Caching

Let’s start by understanding what Prompt Caching is. Prompt Caching allows Claude to reuse a previously processed prefix of a prompt instead of processing the same content from scratch on every request. This is particularly useful for large system instructions, tool definitions, documents, and other context that remains unchanged across requests.

The main benefit we get is reduced latency and input-token cost. Anthropic currently charges cache reads at 10% of the regular input-token price for most Claude models. While the initial cache write costs 25% more than the base input price for a 5-minute cache, the savings increase as the same prompt prefix is reused.

There are, however, some limitations to consider:

  • the minimum cacheable prompt size depends on the model
  • the cache uses a limited TTL
  • we can define only up to four cache breakpoints
  • changes we make to the cached prefix can invalidate the cache
  • a cache entry is also only available after the first response begins, which matters when sending concurrent requests

Next, we need to understand the Prompt Caching Hierarchy for other concepts, like Strategies, to make sense. Prompt caching follows the hierarchy: tools → system → messages. Claude processes these sections in this order, and each level builds on the previous one.

Invalidation also follows this hierarchy. If we change the tools, this invalidates the tools cache and everything below it. If we change the system prompt, this leaves the tools cache intact but invalidates the system and message caches. When we change messages, only the message cache gets invalidated.

The idea is therefore simple: keep stable content as high in the hierarchy as possible and frequently changing content as low as possible. This allows the largest possible portion of the prompt to remain cached between requests.

4. Prompt Caching Strategies

The hierarchy and invalidation rules naturally lead to different caching strategies. The goal is to place cache breakpoints where they provide the most reuse while minimizing the amount of content that gets invalidated when something changes.

A cache breakpoint tells Anthropic where to create a cache entry. Each breakpoint caches the prompt content up to that point, following the request hierarchy of tools → system → messages. Anthropic currently allows a maximum of four cache breakpoints per request, so they should be placed deliberately rather than on every possible section.

Spring AI provides five Prompt Caching Strategies through AnthropicCacheStrategy:

Strategy Breakpoints Cached Content Typical Use Case
NONE 0 Nothing  One-off requests, testing
SYSTEM_ONLY 1 Tools + system message Stable system prompts
TOOLS_ONLY 1 Tool definitions Large, shared tools with dynamic system prompts
SYSTEM_AND_TOOLS 2 Tools + system message Tools and system prompt need independent caching
CONVERSATION_HISTORY 1–4 Conversation history Conversation history Multi-turn conversations

The number and placement of breakpoints also affect invalidation. With a single breakpoint at the system message, for example, a change to the tools invalidates the whole cached prefix. With SYSTEM_AND_TOOLS, Spring AI places separate breakpoints after the tools and system message, allowing the tool cache to remain valid when only the system prompt changes.

Choosing the right strategy therefore depends on how stable each part of the request is. The more frequently a section changes, the more carefully its breakpoint should be separated from stable content.

5. Prompt Caching In Practice

Last, let’s put what we’ve learned so far into practice. First, we’ll apply the theory in a Spring Boot application, and then we’ll run some tests to see prompt caching in action.

5.1. Spring Boot Application with Prompt Caching

As we’ve seen before, we can use Spring properties to set up the model:

spring:
  ai:
    anthropic:
      api-key: ${ANTHROPIC_API_KEY}
      chat:
        options:
          model: claude-sonnet-4-6
          max-tokens: 500
        cache-options:
          strategy: SYSTEM_ONLY

At this moment, claude-sonnet models before 3.5 are no longer available. We set 4-6 and max-tokens to 500 as a guardrail to control the cost, and we’ll use SYSTEM_ONLY as the strategy in our application. The minimum cacheable prompt for claude-sonnet-4-6 is 1024 tokens.

Then, all we need is a service using this model:

public class ChatWithPromptCachingService {

    private final ChatClient chatClient;

    // ... constructors, etc

    public ChatResponseWithMetadataDto chat(String userMessage, String systemPrompt) {
        ChatResponse response = chatClient
          .prompt()
          .system(systemPrompt)
          .user(userMessage)
          .call()
          .chatClientResponse()
          .chatResponse();

        if (response == null || response.getResult() == null) {
            throw new RuntimeException("Client response has no results");
        }

        return ChatResponseWithMetadataDto.fromChatResponse(response);
    }
}

The chat() method accepts a system prompt and a user message and requests our chat-client. Then, it returns the ChatResponseWithMetadataDto:

public record ChatResponseWithMetadataDto(
  String responseText,
  Integer promptTokens,
  Integer completionTokens,
  Long cacheReadInputTokens,
  Long cacheWriteInputTokens) {
    public static ChatResponseWithMetadataDto fromChatResponse(ChatResponse chatResponse) {
        // ... implementation of the mapper
    }
}

ChatResponseWithMetadataDto only holds the information we need: responseText, promptTokens, completionTokens, cacheReadInputTokens, and cacheWriteInputTokens.

5.2. Testing the Prompt Caching Application

To make sure that prompts are truly cached, let’s first have a test with strategy set to NONE and run the test:

@Test
void chat_whenPromptCachingDisabled_returnsResponse() {
    String chatMessage = "hello there";

    ChatResponseWithMetadataDto response = service.chat(chatMessage, PromptsUtils.LONG_SYSTEM_PROMPT);

    assertThat(response).isNotNull();
    assertThat(response.promptTokens()).isGreaterThan(1030);
    assertThat(response.cacheReadInputTokens()).isEqualTo(0);

    response = service.chat(chatMessage + " again", PromptsUtils.LONG_SYSTEM_PROMPT);

    assertThat(response).isNotNull();
    assertThat(response.promptTokens()).isGreaterThan(1030);
    assertThat(response.cacheReadInputTokens()).isEqualTo(0);
}

In this test, we request a dummy message and the default PromptsUtils.LONG_SYSTEM_PROMPT, which is just a bit longer than 1024 tokens. As expected, for caching strategy NONE, we see that the prompt tokens are a full 1030 tokens, and there is no cached token recorded.

Next, let’s try the same test with the default caching strategy of our application (SYSTEM_ONLY):

@Test
void chat_whenPromptCachingEnabled_returnsResponse() {
    String chatMessage = "hello there";
    UUID testId = UUID.randomUUID();

    ChatResponseWithMetadataDto response = service.chat(
      chatMessage,
      PromptsUtils.LONG_SYSTEM_PROMPT + "\nTEST_ID=" + testId);

    assertThat(response).isNotNull();
    assertThat(response.promptTokens()).isLessThan(50);
    assertThat(response.cacheWriteInputTokens()).isGreaterThan(1000);
    assertThat(response.cacheReadInputTokens()).isEqualTo(0);


    response = service.chat(chatMessage + " again", PromptsUtils.LONG_SYSTEM_PROMPT + "\nTEST_ID=" + testId);

    assertThat(response).isNotNull();
    assertThat(response.promptTokens()).isLessThan(50);
    assertThat(response.cacheWriteInputTokens()).isEqualTo(0);
    assertThat(response.cacheReadInputTokens()).isGreaterThan(1000);
}

Now we see Prompt Caching effects! In the first request, the response tells us that cacheWriteInputTokens is over 1000, which means it just wrote to the cache. Moreover, promptTokens is low, just the user message, and cacheReadInputTokens is 0 cause there was no cache hit.

In the second request, promptTokens is low, but this time cacheWriteInputTokens is 0 (no new tokens cached). CacheReadInputTokens is now over 1000, which shows there was a cache hit!

The prompt in this test also uses a TEST_ID to make sure no previous tests will affect the next execution. It’s a trick to use different caches between test executions.

6. Conclusion

In this article, we explained how Prompt Caching Support in Spring AI with Anthropic Claude works. We walked through how it works, configuration options, and the limitations. Then we saw the Prompt Caching Strategies. Finally, we used Spring AI to demonstrate it in practice.

As always, the source code of the examples can be found over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest