12-04 更新 实时
首页/ 技术栈/ 正文

用分布式 KV 缓存智能体技能降低自托管 LLM 成本与延迟

技术栈 来源:AWS Machine Learning 2026-11-21 08:14 2 阅读 机器翻译
用分布式 KV 缓存智能体技能降低自托管 LLM 成本与延迟

客户越来越多地在 GPU 上自托管大语言模型(LLM),以掌控成本、准确性和延迟。然而,自托管往往意味着为冗余的 GPU 计算付费,因为每台服务器上孤立的小型缓存既无法容纳、也无法共享 AI 智能体和聊天应用反复重发的、不断增长的上下文。设想一个法律 AI 助手,它在每次对话中可能累积数十万 Token 的案情历史。当律师午休后回到某个对话线程时,LLM 的响应可能要花上几分钟。承接该请求的 GPU 服务器内存中完全没有这段历史。因此,GPU 在写出第一个字之前,要为所有这些 Token 重新计算键值(KV)注意力状态,这一步称为 prefill。同样的模式也会拖慢被恢复的编码智能体、智能体式 AI 助手和文档问答助手。使用 Amazon ElastiCache 的分布式 KV 缓存可将自托管 LLM 的推理成本降低最多 40%,并将首 Token 时间(TTFT)缩短最多 80%。分布式 KV 缓存通过在你的 GPU 集群旁增加一个共享层来扩展 GPU 本地缓存,使任何服务器都能在数天内跨会话、路由变化和服务器故障复用 KV 状态。《宣布推出面向自托管 LLM 的 Amazon ElastiCache 分布式 KV 缓存》一文深入介绍了技术细节和性能基准测试。

本文详细介绍 Agent Toolkit for AWS 中的分布式 KV 缓存技能(skill)。借助该技能,你只需几个提示词,就能在自己的编码智能体内评估并搭建分布式 KV 缓存。该技能会引导智能体检查你的工作负载是否能从分布式 KV 缓存中获益、为测试或生产工作负载搭建缓存集群,以及对你的 LLM 推理缓存进行故障排查。该技能可与 Kiro、Claude Code、OpenAI Codex 以及其他支持 Agent Skills 的编码智能体配合使用。我们通过四段对话来演示该技能的工作方式:诊断首 Token 延迟过慢、评估缓存规模与成本、完成搭建,以及修复传输失败。

你的工作负载能获得多少收益,取决于所用 LLM 模型、用户流量模式和提示词路由选择等特征,估算起来可能相当复杂。我们开发了 KVTrace 工具,可在你部署任何基础设施之前,基于你自己的模型和流量,对你的工作负载收益做出接近实际的估算,且不额外收费。该技能简化了这一评估与搭建过程,并在做出任何改动之前,引导你的编码智能体遵循以下最佳实践:

这些流程,从收益估算到搭建,都需要以下条件:

我们向智能体输入了这样一段提示词:“我的 vLLM 集群在 p5 实例上为一个法律助手提供服务,上下文长度为 64K Token。回访对话的首 Token 需要 13 秒,因为 GPU 每一轮都会重新计算完整的对话历史。我该怎么解决?”

智能体会把请求与技能进行匹配,并且在 Kiro 中,会在加载该技能之前先请求批准。答案指出,延迟是由冷预填充造成的,而这个答案中有三点对实际部署很关键。首先,它会检查那些无需新增基础设施的修复方案。如果你关闭了前缀缓存,重新开启它可以加快连续多轮对话的速度。如果在会话亲和性下 GPU 前缀缓存命中率已经高于 90%,你可能不需要共享 KV 缓存。其次,它会识别出法律 AI 助手特有的约束。共享 KV 缓存可能让一个租户通过响应时间判断出另一个租户发送了相同的文本。必须保持隔离的案例使用单独的缓存,而共享缓存的租户则把自己的 ID 加入 KV 哈希。第三,它不会去猜测规模。它会询问模型和 TP 规模、KV 数据类型、副本数量和路由方式,以及用户在轮次之间等待多长时间。

图 1:针对法律助手的诊断结果与建议架构

为了估算节省量,我们给智能体提供了一个示例集群:8 个 p5 实例,为一个多轮检索增强生成(RAG)助手提供 64,000 Token 的提示词服务。智能体查询了 GPU 和缓存节点的价格,并根据基准测试推导出预填充速率和 KV 大小。最后,智能体建议使用两个 cache.i8ge.48xlarge 节点进行分布式 KV 缓存。下图展示了智能体的总结及其使用的输入。

图 2:智能体的总结与输入。它在 AWS 价格列表中查询了两者价格,并解释了它如何得出重算这一数字

我们没有提供缓存命中率,也就是缓存能够服务的重算 Token 所占比例。因此,智能体会给出各种场景方案,并建议运行一次 KVTrace 来确定缓存命中率。KVTrace 会记录来自 vLLM 或 SGLang 的 KV 缓存事件,然后离线将这些事件回放到每种候选容量对应的共享 KV 缓存上。记录器绝不会写入 Token ID 或提示词文本。轨迹中保存的是块哈希和 Token 数量。块哈希源自 Token 内容,因此当你的提示词较为敏感时,请传入 --anonymize-key-file。该技能会在每台 GPU 服务器上记录一个有代表性的时间窗口,例如一个完整工作日。智能体还指出,只有当你减少运行的服务器数量,或在同样的服务器上承载更多流量时,释放出来的 GPU 时间才会转化为收益。

图 3:来自合成演示流量的一份 KVTrace 报告的顶部部分。它推荐达到节省上限 90% 的最小容量。

我们向该智能体下达了这样的提示:“从零开始,为 LLM 推理搭建一个共享的 L2 KV 缓存。”在真正创建任何资源之前,智能体会先请求你确认:是否按建议的缓存节点数量、以预估价格在你的可用区内部署。确认之后,它会创建带有 EFA 权限的正确安全组,以及一个 Valkey 9.1 集群,该集群使用带有缓存淘汰策略的自定义参数组。LMCache 会获得专属的缓存用户,密码存放在 AWS Secrets Manager 中。智能体会准备 GPU 服务器,并在每台 GPU 服务器上启动一个 LMCache 服务器。随后,它用一个小的测试对象检查集群,并确认重复的提示词能够通过远程直接内存访问(RDMA)从缓存中加载其 KV 状态。在 GPU 集群上,该技能会将实测的 L2 占比与 KVTrace 的预测值进行比对。如需包含全部命令的完整搭建流程,请参阅 Amazon ElastiCache 文档中的《分布式 KV 缓存入门》。

提示:“我的 LMCache 服务器能连接到 ElastiCache 集群,BLOB.RDMA_HELLO 也成功了,但实际数据传输失败。INFO largeobj 显示 rdma_write_errors 持续上升。问题出在哪里?”

按照该技能的故障排查指南,智能体从症状模式出发进行推理,判断可能的原因是安全组阻止了其成员之间的 EFA 流量。它会给出用于检查并修复该规则的命令。

图 4:智能体解释症状,然后给出用于检查并修复安全组的命令

你可以从 Agent Toolkit for AWS 获取分布式 KV 缓存技能或 AWS MCP Server。然后描述你的问题,或让 AI 智能体降低你的 GPU 机群成本与延迟,即可开始使用。要了解有关使用 ElastiCache 的分布式 KV 缓存及性能基准测试的更多信息,请参阅 AWS 博客。你可以在 Amazon ElastiCache 文档中查看 AWS Command Line Interface (AWS CLI) 入门指南,并在 GitHub 仓库中了解更多关于 KVTrace 的信息。

Ravi 是 AWS 的全球首席专家,负责领导数据与 AI 的市场推广。在加入 AWS 之前,Ravi 曾在 Moody’s、Mesosphere、IBM 和 Cerner 从事产品管理、战略和工程工作。

Neeraj 是 Amazon ElastiCache 的软件开发工程师。他是 valkey-large-object 模块的维护者,专注于为内存数据存储开发分布式系统。他此前在 Amazon Managed Streaming for Apache Kafka (Amazon MSK) 从事数据流工作。

Chaitanya 是 AWS 内存数据库服务的高级技术产品经理,专注于 Amazon ElastiCache for Valkey。此前,他利用生成式 AI、机器学习和图网络构建解决方案。工作之余,Chaitanya 忙于收集各种爱好,目前包括网球、滑板和桨板。

译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(Cut self-hosted LLM cost and latency with the distributed KV caching agent skill)

Customers increasingly self-host large language models (LLMs) on GPUs for control over cost, accuracy, and latency. However, self-hosting often means paying for redundant GPU work because small, isolated caches on each server can’t hold or share the growing context AI agents and chat applications resend. Consider a legal AI assistant that can accumulate hundreds of thousands of tokens of case history in each conversation. When a lawyer returns to a thread after lunch, responses from the LLM can take minutes. The GPU server that picks up the request has none of that history in its memory. So, the GPU recomputes the key-value (KV) attention states for all of those tokens, a step called prefill, before it writes a word. The same pattern slows down resumed coding agents, agentic AI assistants, and document Q&A assistants. Distributed KV caching with Amazon ElastiCache can cut self-hosted LLM inference costs by up to 40% and time to first token (TTFT) by up to 80%. Distributed KV caching extends GPU-local caches with a shared tier beside your GPU fleet so any server can reuse KV state for days across sessions, routing shifts, and server failures. “Announcing distributed KV caching for self-hosted LLMs with Amazon ElastiCache” dives into the technical details and the performance benchmarks.

This post details the distributed KV caching skill in the Agent Toolkit for AWS. With this skill, you can evaluate and set up distributed KV caching from within your coding agent in a few prompts. The skill guides the agent through checking whether your workload benefits from distributed KV caching, setting up a cache cluster for testing or production workload, and troubleshooting your LLM inference caching. The skill works with Kiro, Claude Code, OpenAI Codex, and other coding agents that support Agent Skills. We walk through how the skill works with four conversations: diagnosing a slow first token, sizing and pricing the cache, setting it up, and fixing a failed transfer.

Why a skill for KV caching and what can it do?

The benefits for your workload depend on characteristics such as LLM models used, user traffic patterns, and prompt routing choices, and can be complex to estimate. We created the KVTrace tool to get close estimates of the benefits for your workload, from your own model and traffic before you deploy any infrastructure, at no additional charge. The skill simplifies this evaluation and the setup, and guides your coding agent through the following best practices before changing anything:

  • A fit check before any spend. The agent reads your GPU fleet with a read-only describe-instances call and counts Elastic Fabric Adapter (EFA) interfaces. It asks only for what it can’t see: engine, model, tensor-parallel (TP) size, KV data type, server price, and how often prompts repeat. It stops and explains when something doesn’t fit.
  • Numbers from your workload. For short prompts, loading KV state can take longer than computing it again. Above a certain prompt length (the cutover point), the read wins. That cutover and how often your prompts repeat decide whether the cache is worth its price. The agent estimates savings from your own traffic with KVTrace, at no additional charge, and stops if they don’t cover the cache’s cost. Every number says where it came from.
  • Manage configuration across inference servers with the stack you already run. The agent adds the LMCache connector to your existing vLLM or SGLang engine, including vLLM workers under serving frameworks such as llm-d and Ray Serve. It keeps your routing and the engine’s settings and sets the servers in your inference fleet to one KV ID mechanism (hash and seed) and an explicit KV data type. Matching settings avoid key mismatches, where each server writes KV state the others can’t find.
  • Implements best practices. Before production traffic, the agent empties the local tiers and checks that two cache-loaded runs give the same output, because a layout mismatch can produce healthy hit counters and wrong answers. The skill guides the agent to seek explicit approval for high-impact operations such as creating, changing, or deleting resources.

Prerequisites

These flows, from estimating benefits to setup, require the following:

  • A coding agent that supports Agent Skills, such as Kiro or Claude Code.
  • GPU instances that support EFA RDMA write, such as p5.
  • LMCache 0.5.8rc1 or later and vLLM 0.11.1 or later (SGLang 0.5.13 or later).
  • ElastiCache for Valkey 9.1 or later, on cache.i8ge.48xlarge nodes (if setting up the cache).

Flow 1: Can distributed KV caching help?

We gave the agent this prompt: “My vLLM fleet serves a legal assistant with 64K-token contexts on p5 instances. Returning conversations take 13 seconds for the first token because the GPU recomputes the full conversation history every turn. How do I fix this?”

The agent matches the request to the skill and, in Kiro, asks for approval before loading it. The answer identifies that the latency was caused by cold prefill, and three things in the answer matter for a real deployment. First, it checks for fixes that need no new infrastructure. If you turned off prefix caching, turning it back on can speed up back-to-back turns. If the GPU prefix cache hit rate is already above 90% with session affinity, you might not need a shared KV cache. Second, it identifies constraints specific to the legal AI assistant. A shared KV cache can let one tenant tell from response times whether another tenant sent the same text. Cases that must stay isolated get separate caches, and tenants that share a cache add their own ID to the KV hash. Third, it doesn’t guess the size. It asks for the model and TP size, KV data type, replica count and routing, and how long users wait between turns.

Diagram of the agent’s diagnosis and the proposed distributed KV caching architecture for the legal assistant

Figure 1: The diagnosis and proposed architecture for the legal assistant

Flow 2: Estimating savings

To size the savings, we gave the agent an example fleet of 8 p5 instances that serve 64,000-token prompts for a multi-turn retrieval-augmented generation (RAG) assistant. The agent looked up the GPU and cache node prices and derived the prefill rate and KV size from benchmarks. Finally, the agent recommended two cache.i8ge.48xlarge nodes for distributed KV caching. The following figure shows the agent’s summary and the inputs it used.

The agent’s cost summary showing the GPU and cache node prices it looked up and the two recommended cache.i8ge.48xlarge nodes

Figure 2: The agent’s summary and inputs. It looked up both prices in the AWS price list and explains how it arrived at the recompute figure

We didn’t provide a cache hit rate, which is the share of recomputed tokens the cache would serve. The agent therefore presents scenarios and recommends a KVTrace run to identify the cache hit rate. KVTrace records the KV cache events from vLLM or SGLang. It then replays them offline against a shared KV cache of each candidate size. The recorder never writes token IDs or prompt text. Traces hold block hashes and token counts. Block hashes come from token content, so pass --anonymize-key-file when your prompts are sensitive. The skill records on every GPU server for a representative window, such as a full business day. The agent also notes that freed GPU time turns into dollars only if you run fewer servers or serve more traffic on the same ones.

KVTrace report showing net savings at four cache hit shares, TTFT benchmarks, and the recommended shard count

Figure 3: The top of a KVTrace report from synthetic demo traffic. It recommends the smallest capacity that reaches 90% of the savings ceiling.

Flow 3: Setting up a distributed KV cache

We prompted the agent with: “Set up a shared L2 KV cache for LLM inference, starting from scratch.” Before it creates anything, the agent requests your confirmation to set up the suggested cache node count in your Availability Zone, at the estimated price. Once confirmed, it creates the right security group with EFA permissions, and a Valkey 9.1 cluster that uses a custom parameter group with caching eviction policies. LMCache gets its own cache user, with the password in AWS Secrets Manager. The agent prepares the GPU servers and starts one LMCache server per GPU server. Then it checks the cluster with a small test object and confirms that repeated prompts load their KV state from the cache over Remote Direct Memory Access (RDMA). On a GPU fleet, the skill checks the measured L2 share against the KVTrace prediction. For the full setup with every command, see Getting started with distributed KV caching in the Amazon ElastiCache documentation.

Flow 4: Troubleshooting

Prompt: “My LMCache server connects to the ElastiCache cluster and BLOB.RDMA_HELLO succeeds, but actual data transfers are failing. INFO largeobj shows rdma_write_errors climbing. What’s wrong?”

Following the skill’s troubleshooting guide, the agent reasons from the symptom pattern and identifies the likely cause as a security group that blocks EFA traffic between its own members. It provides you commands to check and fix the rule.

The agent’s troubleshooting answer: the most likely cause is a missing self-referencing egress rule. It explains why HELLO succeeds while RDMA transfers fail, gives a describe-security-groups command to check the rules and authorize-security-group-egress and ingress commands to fix them, and lists four checks to run if the rules are already correct.

Figure 4: The agent explains the symptom, then gives commands to check and fix the security group

Get started

You can get the distributed KV caching skill or the AWS MCP Server from the Agent Toolkit for AWS. Then describe your problem or ask your AI agent to cut costs and latency on your GPU fleet to get started. To learn more about distributed KV caching with ElastiCache and the performance benchmarks see the AWS blog. You can see getting started with the AWS Command Line Interface (AWS CLI) at Amazon ElastiCache documentation and learn more about KVTrace at the GitHub repo.


About the authors

Ravi Yadav

Ravi Yadav

Ravi is a Principal WW Specialist at AWS where he leads go-to-market for Data and AI. Before AWS, Ravi worked in product management, strategy, and engineering at Moody’s, Mesosphere, IBM, and Cerner.

Neeraj Ramachandran

Neeraj Ramachandran

Neeraj is a Software Development Engineer at Amazon ElastiCache. He is a maintainer of the valkey-large-object module with a focus on developing distributed systems for in-memory data stores. He previously worked on data streaming at Amazon Managed Streaming for Apache Kafka (Amazon MSK).

Chaitanya Nuthalapati

Chaitanya Nuthalapati

Chaitanya is a Senior Technical Product Manager in AWS In-Memory Database Services, focused on Amazon ElastiCache for Valkey. Previously, he built solutions with generative AI, machine learning, and graph networks. Off the clock, Chaitanya is busy collecting hobbies, which currently include tennis, skateboarding, and paddle-boarding.

正文保留英文原文,标题与摘要由机器翻译。

本文由采集器自动同步

原文发布于 AWS Machine Learning(Cut self-hosted LLM cost and latency with the distributed KV caching agent skill),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗