Enable LLM request caching in ASM

Updated at:

While large language model (LLM) applications offer powerful capabilities, they often incur high computational costs and latency. To address these challenges, improve model invocation efficiency, and reduce latency, more LLM applications are adopting caching. By storing and reusing LLM computation results, LLM request caching can significantly reduce redundant calculations, optimize response time, and enhance overall system performance. This topic describes how to quickly enable LLM request caching in Service Mesh (ASM).

How it works

The LLM request caching feature in ASM uses a WebAssembly (Wasm) extension. When the mesh proxy processes an LLM request, the LLM request caching plug-in first queries your custom cache service. If a cached result is found, the plug-in directly returns the cached result without forwarding the request to the external LLM service. If no cached result is found in the cache service, the plug-in marks the request for a cache update. When the external LLM service returns a response, the LLM request caching plug-in sends the response to the cache service for storage. The following diagram illustrates how the LLM request caching plug-in works at the gateway level:

image

To help you get started quickly, ASM provides a default cache service implementation based on string matching, which uses Redis as the underlying storage. The mesh proxy calls your custom cache service using standard HTTP requests. This allows you to fully customize the matching logic and storage format for LLM request caching. This topic uses this default cache service as an example to demonstrate how to enable LLM request caching in ASM.

Prerequisites

Step 1: Deploy the default LLM cache service

  1. Create a file named cache.yaml with the following content.

    YAML content

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: asm-wasm-cache-service-example
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: asm-wasm-cache-service-example
      labels:
        app: asm-wasm-cache-service-example
        service: asm-wasm-cache-service-example
    spec:
      ports:
      - name: http
        port: 80
        targetPort: 8080
      selector:
        app: asm-wasm-cache-service-example
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: asm-wasm-cache-service-example
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: asm-wasm-cache-service-example
          version: v1
      template:
        metadata:
          labels:
            app: asm-wasm-cache-service-example
            version: v1
          annotations:
            sidecar.istio.io/inject: "true"
        spec:
          tolerations:
          - key: "node.kubernetes.io/disk-pressure"
            operator: "Equal"
            value: ""
            effect: "NoSchedule"
          serviceAccountName: asm-wasm-cache-service-example
          containers:
          - image: registry-cn-hangzhou.ack.aliyuncs.com/acs/asm-wasm-cache-service-example:v1.22.6.9-g6fc05c9-aliyun # The image address of the sample Redis implementation provided by ASM.
            imagePullPolicy: IfNotPresent
            name: asm-wasm-cache-service-example
            ports:
            - containerPort: 8080
            env:
            - name: REDIS_ADDRESS
              value: ${YOUR_REDIS_ADDRESS_AND_PORT}
            - name: REDIS_PASSWORD
              value: ${YOUR_REDIS_PASSWORD}
            - name: REDIS_EXPIRED_SECONDS
              value: ${EXPIRATION_TIME_IN_SECONDS, e.g., "600"}
            resources:
              limits:
                memory: 256Mi
                cpu: 200m
              requests:
                memory: 64Mi
                cpu: 50m
  2. Use the kubeconfig file of the data plane cluster to run the following command.

    kubectl apply -f cache.yaml

    ASM allows you to use a custom LLM cache service and provides a default implementation that uses exact matching with Redis. For more information, see the code repository. If you have other requirements, you can develop your own LLM cache service based on this example.

Step 2: Deploy the LLM cache plug-in

  1. Create a file named wasm.yaml with the following content.

    apiVersion: extensions.istio.io/v1alpha1
    kind: WasmPlugin
    metadata:
      name: llm-cache
      namespace: istio-system
    spec:
      selector:
        matchLabels:
          istio: ingressgateway
      failStrategy: FAIL_OPEN
      imagePullPolicy: IfNotPresent
      match:
      - mode: CLIENT
        ports:
        - number: 80
      phase: STATS
      pluginConfig:
        host_match: "dashscope.aliyuncs.com" # Supports regular expression matching.
        path_match: ".*" # Supports regular expression matching.
        service: "asm-wasm-cache-service-example.default.svc.cluster.local"
        port: "80"
      priority: -10
      url: registry-cn-hangzhou.ack.aliyuncs.com/acs/asm-wasm-llm-cache:v1.22.6.9-g6fc05c9-aliyun
  2. Deploy the cache plug-in on the gateway.

    kubectl apply -f wasm.yaml

Step 3: Test

Run the following command twice to test the feature.

time curl --location '${ASM_GATEWAY_IP}:80' --header 'Content-Type: application/json' --header "host: test.com" --data '{
    "messages": [
        {"role": "user", "content": "Tell me about yourself"}
    ]
}'

Expected output:

{"choices":[{"message":{"role":"assistant","content":"I am a large-scale language model from Alibaba Cloud, and my name is Qwen. As an AI assistant, my primary function is to understand and answer various questions. I can provide accurate information and suggestions based on your needs, and I can adjust the content and style to your preferences. No matter what questions you have or help you need, please feel free to ask me, and I will do my best to provide you with support."},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion","usage":{"prompt_tokens":12,"completion_tokens":65,"total_tokens":77},"created":1732068820,"system_fingerprint":null,"model":"qwen1.5-72b-chat","id":"chatcmpl-30581ce8-e120-97ea-b9ac-488dbd346a75"}
real    0m 4.09s
user    0m 0.00s
sys     0m 0.00s
{"choices":[{"message":{"role":"assistant","content":"I am a large-scale language model from Alibaba Cloud, and my name is Qwen. As an AI assistant, my primary function is to understand and answer various questions. I can provide accurate information and suggestions based on your needs, and I can adjust the content and style to your preferences. No matter what questions you have or help you need, please feel free to ask me, and I will do my best to provide you with support."},"finish_reason":"stop","index":0,"logprobs":null}],"object":"chat.completion","usage":{"prompt_tokens":12,"completion_tokens":65,"total_tokens":77},"created":1732068930,"system_fingerprint":null,"model":"qwen1.5-72b-chat","id":"chatcmpl-30581ce8-e120-97ea-b9ac-488dbd346a75"}
real    0m 0.00s
user    0m 0.00s
sys     0m 0.00s

The output shows that the response time for the second request is significantly lower, indicating that the cache is working.