Skip to main content

Semantic Caching for LLM Apps: Cut Inference Costs with a Lakebase and MLflow Gateway

Summary

  • Semantic caching: Returns stored responses when questions match in intent, cutting LLM costs.
  • Cache architecture: Hash lookup, semantic similarity, and API calls create a three-tier cache.
  • Hit rate performance: Shared and private partitions achieve 57% hit rate, dropping latency to 225ms.

Semantic Caching for LLM Apps: Cut Inference Costs with a Lakebase and MLflow Gateway

Watch: Semantic Caching for LLM Apps: Cut Inference Costs with a Lakebase and MLflow Gateway
Talk by Ananya Roy, Snr Specialist Solution Architect, Databricks; Brian Law, Sr. Specialist Solutions Architect, Databricks
The cheapest way to reduce LLM and AI agent inference costs at scale is to stop paying for the same answer twice: semantic caching returns a stored response when a new question matches an earlier one in intent, even when the wording differs. This video builds a production semantic cache gateway on Databricks, a FastAPI service on Databricks Apps that tries an exact hash lookup, then a semantic similarity lookup in Lakebase, and only calls the Foundation Model API on a miss, with shared and private cache partitions and measured hit rate and cost savings.
The gateway tries a fast exact hash lookup first, then a semantic similarity lookup in Lakebase, and only calls the Foundation Model API on a miss before writing the answer back to the cache. The demo separates shared and private cache partitions so user-specific questions are not served to the wrong person, and shows a response dropping from about 20,000 milliseconds to 225 milliseconds. You will also see how to track hit rate (57% in the demo), tune the similarity threshold, set cache retention (seven days for shared entries in one example), use MLflow for observability, and decide when semantic caching fits, such as factual Q&A, and when it does not, such as personalized or real-time answers. The talk targets LLM cost reductions of up to 80%.

Chapters

FAQs

How does semantic caching differ from exact-match caching?

Exact-match caching misses paraphrased questions, but semantic caching recognizes intent across different wording. This video shows that a response dropping from 20,000 milliseconds to 225 milliseconds demonstrates dramatic speed improvements.

What architecture does the semantic cache gateway use?

The gateway tries a fast exact hash lookup first, then a semantic similarity lookup in Lakebase, and only calls the Foundation Model API on a miss before caching the result. This video shows how shared and private cache partitions keep user-specific questions separate.

What hit rate and cost savings are realistic?

This video demonstrates a 57% cache hit rate in the demo scenario, targeting LLM cost reductions up to 80%. The gateway tracks hit rate and cost savings with MLflow observability to measure real business impact.

When should I use semantic caching and when not?

This video advises using semantic caching for factual Q&A where cached answers remain valid, but avoiding it for personalized or real-time answers where freshness matters. Cache retention periods can be tuned, with seven days for shared entries in one example.

Full transcript

00:00 Introduction: semantic caching for LLM apps

Hi, everyone. Thanks for making it to this afternoon session. We're here to talk to you today about semantic caching. So firstly, let's look at what's happening with AI. From what you can see is demand is just growing and growing and growing. And likewise, for a lot of you, your token costs are growing just like that as well, which probably your CFOs are not too happy about. So what we need to do is think about what's actually happening, think about how people are using large language models and what's contributing to that bill.

00:39 Why chatbot LLM costs grow at scale

So let's say you go through and you build your HR chatbot or you build your IT help desk chatbot. Then if you've got something like 100,000 employees, maybe they send like 10 questions per day, that's a lot of LLM calls, and that's assuming it's a single question and answer as well. There could be multi-turn conversations, There could be a lot of different topics and searches that need to happen behind each of these interactions with the chatbot as well.
That's all money that is going down the drain. So agents are really good because they can handle ambiguity, because they can understand the intent of people who are asking the questions, but they can also become expensive. There's a lot of costs associated with hosting and running and chatting with them. and then that makes your LLM bill more and more unsustainable. So what we want to do is we want to find ways that we can help with production costs, ways that will apply across various different industries and ways that you can start to control your bill relatively quickly without having to spend a lot of time going through redeveloping your application, redoing your prompting and slowly optimizing your context inside of your agent.
So let's work through an example and see how we can help in addressing the costs for your LLM chatbot. So if we have a customer support agent, then a lot of people will be sending through questions like, how do I log in? How do I return my package? How do I get my package delivered? These are all pretty standard questions that would come through to this kind of experience. and there'll be lots of different ways that it can be said.
Some people might say, I forgot my login. People might just say, forgot login. You'll have typos. You'll have different ways of asking the same question. You can see with all these different ones, we've got a few variations and this is just, I guess, a small slice of what you can see. I was working with an airline customer and people will just put in even single word questions like luggage. and then expect you to be able to work out what they want from that.

02:40 Why exact-match caching misses paraphrased questions

So caching is something that's always been used, particularly on the web side of things and with media like Netflix in order to go through and optimize the delivery of content, the delivery of information. And what caching will do is it'll help you to go through and save out answers and pull it from the cache instead. So if you don't have caching, then every time someone asks the question, you're going to have to go through the full LLM reasoning step.
Each time it's going to go through, generate that call, process those tokens, you're going to have to pay for each one, and even if the question is exactly the same, you're going to get zero reuse out of it. You can do an exact cache, so some of the time that will work, but then you're assuming that everyone asks the question the same way. And remember, when you add a cache, that means an extra database, an extra service that you need to run as well.
So if your questions are not hitting the cache, then you're paying for even more infrastructure without addressing the underlying problem. That's where semantic caching can come in. So when we use semantic caching, that's using an algorithm to try and understand the intent of the question. and then from there we can retrieve the answer without having to go through the LLM process. So we're looking at the meaning of the words.

04:04 What is semantic caching?

We're more resilient to things like typos, things like change in case, things like phrasing. Not sure about multi-language for those of you who are in that space, but it addresses a lot of the common usage patterns. And when you hit the cache, then you don't need to go through the LLM inference. So this is what it would kind of look like in terms of the user experience flow. So we have the question that comes in as per normal.
We're going to go through and search the cache. If we find the cache result, then we can send the cache result direct to the user. We can skip the LLM step. Otherwise, we can still go through, send it through to the LLM, and then finally send the answer back to the user, although we also persist along that journey. So the first part, user ask question, that's exactly the same, so you don't need to go through and change any of your logic in terms of your chain, in terms of your agent.
The next part is the cache search. That's where we're going to have our cache database. We're going to go through and try and match the question to things that we might have stored already. Then we've got to check if it's a close enough match. So there could be some tweaking here at this step where you might try to adjust on the threshold for what you would call similar enough. When it's similar enough, then we'll go through and return the answer as is from our database.
Otherwise, we'll go through and actually do the LLM call. And finally, if it is a new question, if it is the first time we've seen it, we will also go through and write that answer back into the cache so then we can go through and avoid it next time. So then next time we see that question, hopefully you'll get an answer directly from the cache. That will help you lower latency as well because LLM calls are typically expensive, lowers cost, of course.
You save on those precious tokens, and you'll get the same quality of answer as if you had gone through and asked the LLM to generate. So I'll hand it over to my co-presenter, Ananya, to talk through some of the finer technical details and show you a bit of how this works. Thank you, Brian. So now we are going to see how Databricks can help in this case, right? How we want to implement semantic caching in Databricks.

06:28 Architecture: Lakebase, MLflow and Databricks Apps

So how can we do it in Databricks? A couple of different options are there. So the way we would be doing is we would use Lakebase for our semantic cache layer. then we would use Databricks app to host that cache. And then MLflow is going to be working as your reliability layer. So all of the traffic which is flowing through your cache to your final LLM application would be well observed. And then you will be having all the capability of evaluation, monitoring, and the whole responsible AI suite.
And all these three components together are going to be governed end-to-end by Unity Catalog. So let's see how that is done. But before that, let me give you some examples of why we have chosen Lakebase for our caching layer. So those of you who has already built some sort of a cache for any other application, we are talking about here is semantic caching. So what is semantic caching? It's like similarity match. Close enough match, which Brian has already mentioned.
So when you use Lakebase, the Lakebase itself is a PostgreSQL database, so you will get all the structural SQL capability by default, and it is millisecond latency, as we all know, because it is fast, the storage and compute is separate. It also has a default capability of semantic search through PG vector integration, the first one. That you get automatically if you use PostgreSQL. in this case, LakeBase. Now, imagine if you want to build this system separate outside, like Redis or something else, you would need a separate vector database, right?
You do not need that in this case. For LakeBase, it also supports, as part of the semantic search capability, different types of algorithms for search. You got your standard approximate nearest neighbor, HNSW index, which is pretty powerful on generating those semantic similarities. So all of these things are kind of coupled all together. And then you get native OAuth integration, Unity Catalog governance, and your structural capability, your structured data capability.
So all these things, the six different things I talked about, is all encapsulated into LakeBase anyway. You don't have to go and build three different bespoke systems. So that's why it's a really powerful system in its own, and it has what different capability where you can use LakeBase. Semantic caching is one of them. So, we are going to see the architecture a little bit before we jump into the demo and show you how the caching looks like.
So it's the very 10,000-foot view of what your simple caching would do. So user will ask a question. That question will hit the . works app, which is a fast API server, and that is a proxy layer, and then from there, it will talk with an embedding model, which is a database FM API model. In this case, we have used Quen, and then it will hit the semantic cache proxy for similarity search. If it finds the result, then it will return the result directly from cache.
It will not go into your FM API, and then you'll get the response back. And if no match is found, then finally, if it's a miss, it will go to the FM API endpoint. It will give the result back, and then it will also store the result. So this is, again, the high-level view. Let me go one step further and show you a detailed view of what actually happening under the hood for this particular implementation. Now, nobody is saying, like, you have to build it in this way.
This is what we found is going to be helpful, so that is how we have built it. But it's a completely flexible architecture, however you build. The idea is that you can build semantic layer with LakeBase. So what's happening? Your client app is sitting in the Outerworks app, and then it is hitting a middleware layer. Then the control flow is checking whether I need to skip cache or not. Now, caching is not required for all of your application.
There will be very specific use cases where caching makes sense, and there are other use cases where caching doesn't make sense at all, and in fact, it will be dangerous. And we are going to cover that in a moment. So if we decide that we would do caching, so we would not skip it, then it goes to this cache layer. Then how we have implemented is, what is our ultimate goal here? We want to save cost. We want to make it faster.

11:32 Exact match then semantic similarity lookup in Lakebase

So the first phase is performing an exact match. Say I have asked a question to this application. Brian asked the same question in a couple of hours later. But the question is same. So then it becomes an exact match. So we can do some sort of a hash mapping. Once it is, and this is way faster than your semantic caching as well. So once that is done, then we say we have not found any match, then it will go into semantic matching.
If it finds a match, then the response will directly be returned to your final client, and you'll get the response directly from any one of the caching layer. And the way the semantic matching is happening is in Lakebase, we have got two tables, entries and events, which are holding all of the information and telemetry of what is the cache, when it happened, how it happened, whatnot. And then if none of them matches, then we go and call the FMAPI.
Once it is called, our job is not done. We need to save the result for future reference so the response will be saved in Lakebase so that subsequent call can take reference of that cache. But a few key things to note here is that LakeBase is pretty powerful. It is well-governed. So for that, it comes with other capability of it has to match the token refreshing. We need to do some sort of token management. So those things are done with Databricks SDK as part of our application.
We have used the foundation model, as I mentioned, and app is handling all of the client and server hosting, talking between them, whatnot. So this is the overall architecture. But before jumping there, I want to mention that when we create what to cache, when to cache, and when to retire from the cache is also really important. So how we manage the time to live is going to be important on any one of the caching applications which you build for production.

13:36 Demo: cache hits and misses

So with that said, let's see a demo. So this is my app, vanilla version of an app, which is a React front-end, and then I've created two users. So this, you can imagine that I have created here two different user-level isolations. So my information and Brian's informations are completely separate. Imagine, like, it is a production-scale application where multiple users are using. Everyone has their own set of cache, And then we want to have a shared case also, so that genetic questions can be answered one from another.
But we also want to separate some highly sensitive user-specific question. So let's see that in practice. This is pretty small. Maybe let me make it a little bit bigger. So I am in my session, and there are a bunch of questions. Say, for example, the first question I ask is, what is Databricks Unity Catalog, and how does this work? Now, this time, my cache is empty, so it's fresh. It does not have any information whatsoever.
So my model will run. It'll take some time. It'll fetch. Under the hood, I'm running Claude here. So it is going to fetch some information, and it is going to give me an answer, and with some additional telemetry, if it runs. Wow. Okay, let me try one more time. If not, I also have a backup, so we can see how it works. Let me make it a little bit bigger and say I have asked a question. Very similar situation. So I have asked the question to this app of how does Apache Spark handle data partitioning?
So this is the first time I have asked and my model will run. Again, it will synthesize all of this different information and it will give me an answer. This took a little bit of a while because it gave me a very detailed, verbose answer. The thing which you can see here is that my entire agent ran and it gave me the answer itself, which is fine, but focus your attention on this part. The first one is a cache miss. Then it has stored the information in a shared repository.

16:19 Shared vs private cache partitions

So I've created two different partitions, shared and private, and then the time it took was around 20,000 millisecond, which is quite a lot, right? And then this is the same question which Brian has asked in his next session. So Brian gone to his session, so we are simulating, and then he asked the same question. And you can see that it is a cache hit directly from the shared 100% match, because we are talking about exact match here, and the time it took was 225 millisecond.
225 millisecond altogether. So it's pretty fast. We are seeing performance improvement from 20,000 milliseconds to 225. So more than around 90% gain for a particular question. The reason this one is super fast is because we are hitting an exact match. Now, say, for example, I want to... So this is the first phase. Now, second is my semantic similarity match. So we both are from Australia, and we want to explore San Francisco a little bit more.
So I asked a question about, tell me top five places to eat in San Francisco. So again, in very similar concept, the question is not asked before. So first time we will have a miss, and then it will be stored in my shared repository. And then if Brian asks the same question, he will get the same response, but you will see something different. And let's get to that question. So you can see it's a little bit small. Yeah, I'm visiting and want some suggestions on top places to eat in San Fran.
So he got the result, but you can see there is a hit. It is coming from the shared session, but it is 84% match. So what's happening? The questions are a little bit different. It's not exact match. So under the hood, the question went to the cache. Lake base index was hit. Similarity match was done. There was an 84% similarity. I have a threshold currently I have given as 82%, and then the response was coming. So that's how we can actually see the real performance gain when we are talking about exact match versus semantic similarity.
Right? So let me see if I can show you the other part, which I have already run, or not. Let's see. Okay, cool. So this one works. So in order to show you the actual performance or quantitative gain, I have run a load test. So what I have done is I have asked a bunch of questions for the first time, and then I have simulated similar questions, non-similar questions for the second one. And what I see here is that in this case, there was 57% hit rate for Kish.

19:48 Measuring cache hit rate and cost savings

And that has resulted into quite a significant cost as well as performance gain. So for some simulation, if you are running 100 queries per day, without cache, you are going to spend around $13. 2. With cache, it's $5. And that is a gain of $7. And as the number exponentially grows, your saving is also growing. So in 10,000 queries, which is a very small number, I would say you are saving around 57%. Imagine if you are running 100 million queries per day or so.
You would be spending in millions. So consider not only cost, but also the user experience they will get. They will get super fast response, right response at the right time. So that's why we need to think about building some sort of caching layer if it suits. And why I'm mentioning if it suits, let's get back to that one. But before that, I want to show you the last part, is the architecture a little bit more. So we have seen how it works.
The first time when the model, the messages came, it is using an open AI format. First here is the exact hash lookup, the lightning fast response which you have seen. And then if it misses, then it is going to the semantic similarity lookup, which is typically within the range of 50 milliseconds. or so. And then if it misses, then it is finally going into your standard LLM call. Now, the thing to consider is why I have created these two different sections of private versus shared.
So imagine a question Brian is asking about, okay, why my order is delayed on this app. And I am asking why my order is delayed. Imagine if it's a shared cache and both of us are getting the same answer. Is it right? It's not right, because both of us are coming from a completely different context. So that's why context matters. Which one, even though apparently similar questions, can give completely different results?
So we need to have an intelligence layer in between, which will decide whether to go in a shared repository, whether to go into a private repository. So general, for this demo, we have kept it pretty simple, but for production, you might need to think a little bit more about what should be going in this versus the other one. And the last one is cache storage. So we earlier discussed when we have looked at all of this data and then the LLM call has happened, we need to store it. storing is as important as to decide how much long this information will be living.
Because it is as dangerous as not providing any information than to stale information. So, for example, in this case, I have mentioned for private entries, you have a time to live for 24 hours. And if it's shared, you keep it for seven days. But this will differ from business use case to use case. So this is something to consider for. So, in terms of the technology stack, the one we have implemented, the gateway is your FastAPI and Databricks hosted app.
Cache is happening with LakeBase, which is giving you that structured data as well as PG vector. Gwen is doing all the embeddings, which is taking the user question, creating the embedding, performing the similarity search, and then Foundation Model API, and then this is the front end. So very simple one in terms of how it is done. So let's get back to our topic. And let's understand... We have already seen the impacts and the numbers, so I'm not going to go through in detail.
But some things to consider when we are building any sort of cache, whether it is Databricks, whether it is outside of Databricks. Threshold is really, really important. So for the purpose of the demo, we have created a threshold of 0. 82, but it depends on what use case you are using. So if you make it pretty low, then any questions will consider a match, whether it is wrong or right. So having a too low threshold is also dangerous.

24:15 Tuning the similarity threshold and monitoring

Having a too high threshold also comes with this possibility that you might not find any match at all. So there should be a sweet spot based on your use case, which one is your optimum. So generally what I have seen is 0. 9 to 0. 92 is a good one. Now, we are talking about something important which can have direct impact to customer. So not only just building, but having the right monitoring is also as important as having the solution built.
So monitoring the track hit rate, if something goes break, then you should be having some sort of alerting mechanism so that you can fix it. Cache warming, so that you can pre-populate with frequent questions, so user can get that seamless integration and seamless benefit all the time. Tenant isolation, I have already mentioned. And then time to live strategy. So these are some of the things which we should consider when we are building cache.

25:32 When to use semantic caching and when not to

Now, what are the good versus bad use case? So some of the good use case would be when you are building some application which is highly repetitive. So they have a question. So your typical customer support chatbot where you are asking questions where maybe 40 to 50% of your users are asking the same question. Then semantication makes sense. is a good use case. Agentic rag workflows where majority of the questions will have similar answers.
That is good. But what is not suitable? Personalized agent where every individual response is going to be different based on the user. Any agent which requires time-sensitive quantitative information. So what is the status today? And the same question might be giving a completely different result tomorrow. So caching might not be right for them. So all these things together kind of like need to be designed beforehand when you are deciding whether you should be building some sort of a cache layer or not.
The last one, what we want to say is that what are the best practices when you are building any type of semantic cache? First is any type of factual question and answer type of data point should be considered as cache. So typically you have the same intent and same answer. Tool routing. So it is predicted and determined that based on same call, you would be going into either path one or path two. So that can be a good use case.
Text to SQL, when the result is predictable. For this type of question, this is the specific SQL query that needs to be executed. But what are the ones that should be avoided? Anywhere there is a novelty involved. So creative writing, real-time data, personalized output, those things are not candidate for semantic caching. So just the golden rule is if you ask the same question twice and expect a different answer, so don't cache it.
So what I would say is that you have got a very high-level glimpse of why caching matters. The reason is you should be able to, if you build the right use case for right caching, you would save your money, you would save performance gain, you will ultimately get a better customer experience altogether. But be vigilant when you are designing, because if it goes wrong, there are chances that it might be detrimental. So consider that, and from Databricks perspective, Lakebase is giving you, because I have built this entire thing in a very short amount of time.
So Lakebase itself is quite capable. That's why it enabled developers like us to build something quickly. So Lakebase provides you with all these capabilities, which I have mentioned, to build something up and running. And that's pretty much it. I would say whatever you have learned, we hope we have given you a glimpse of why it matters, how it matters, and just would encourage every one of you to go and build and see the actual benefit.
With that said, thank you, everyone. It was a short one, but hopefully you enjoy the rest of your day. Thank you so much.

Learn more about the Databricks Data and AI platform.

The information provided herein is for general informational purposes only and may not reflect the most current product capabilities or configurations.