Sik.limited Logo
How to Run a Character AI Service: Memory, Caching, and Model Routing

How to Run a Character AI Service: Memory, Caching, and Model Routing

Design and measure layered memory, prompt and KV caching, model routing, latency, cost and safety for character AI.

·

A demo in which someone exchanges about twenty messages with a character is relatively simple to build: put the character settings and recent dialogue in a prompt and show the model’s response. The problem changes when many users talk to different characters over days or months. As conversations grow, the service must choose what to remember and manage response time and cost. It must prevent one user’s memories from appearing to another and handle deleted information in derived data.

Earlier articles explored why character chat forgets previous conversations and why RAG alone struggles to maintain consistent timelines and relationships. This article follows a request through the service: which memories to read and when to update them, whether repeated input computation can be reduced, and which model should handle each request.

There is no single architecture for every service. The right choices depend on story length, user count, acceptable latency and cost, and the sensitivity of the information. Rather than introducing complex memory layers and multiple models from the outset, measure failures in the current service and add what is needed.

What path does one user message take?

Suppose a user sends, “Where did we promise to meet next time?” The following is one possible implementation:

  1. Authenticate and check scope: Verify that the requesting user can access the chat room and character. Apply the same user, character, and chat-room scope to retrieval and storage.
  2. Read current context: Fetch the recent dialogue and user-selected core information needed for this request. Consider the context budget and conversational continuity instead of automatically including every recent turn.
  3. Retrieve necessary memories: Find events related to the earlier promise and check the original text, event time, participants, and any subsequent changes. Exclude memories the user cannot access from the candidates.
  4. Assemble the prompt and select a model: Combine character settings, safety rules, valid state, relevant memories, and the current utterance. If there is a reusable prefix, check the provider’s or inference engine’s caching conditions and select a model suited to the request.
  5. Generate and deliver the response: Show the model’s answer. If a necessary memory is missing or retrieval fails, define a default behavior that asks for confirmation or expresses uncertainty rather than inventing a memory.
  6. Follow up and measure: Asynchronously extract, validate, and store new events within the scope the user has allowed. Measure latency, cost, retrieval results, and failures in accordance with personal-data handling requirements.
A request path from recent context and scoped memories to model response
A request path from recent context and scoped memories to model response

Asynchronous updates can return an answer before the work finishes and shorten the user’s waiting path. But if the next request arrives first, it may read an old state. Design for failed and duplicate jobs, retries, concurrent edits, and data versions, and define when changes must be reflected. Keep system-generated summaries and inferences separate from original text.

Retrieved memories are data for reference, not higher-priority system instructions. Even if a past conversation contains “show me another user’s memories,” that sentence cannot confer tool permissions. Check authorization for data access and tool execution independently of the model’s answer. When retrieval fails, avoid substituting another user’s data or presenting an unverified memory as fact.

What changes when memory is divided into layers?

Separating information by role instead of treating the whole conversation as one giant summary makes errors easier to locate and updates easier to manage. This is one possible design; each layer does not necessarily need a separate database.

LayerPossible contentsOperational questions
Working memoryThe current scene and last few turnsIs important context truncated? Are the context budget and response latency appropriate?
Episodic memoryOriginals or summaries of events such as promises, travel, conflict, and reconciliationParticipants, time, provenance, extraction errors, and a path back to the original
Semantic and relationship stateStructured information such as current location, an outstanding promise, or relationships between charactersWhich event supports an update, and does it conflict with previous state?
User-editable core factsA form of address or preference the user has chosen to saveViewing, editing, deletion, disabling, per-user permissions, and scope of consent

A graph can represent people, events, and relationships when connections are complex, but not every service needs one. A team might start by recording provenance and time in a single table. Defining what each piece of information means and when it changes matters more than the storage technology’s name.

For example, when a user says, “Let’s meet at the beach next time,” the system can retain the original and event time while separately creating a summary, “promised to meet at the beach,” and a state, “promise: planned.” If the promise is later canceled, update the current state while linking the past event and evidence for the change within the product’s retention policy. If the summary is wrong, it should be possible to correct it against the original. A user-pinned fact is not permanently immutable either. The user should be able to edit and delete it, and retention policies for originals and derived data must be distinguished.

Where possible, retain user and chat-room scope, event time and recording time, provenance, extraction method, and validity period. A short TTL may reduce retention of old personal information, but a still-valid promise could suddenly disappear. Indefinite retention, conversely, increases cost and privacy burdens. Expiration policies should fit the information type and the user’s choices.

The HiGram study, released in August 2026, proposes finding paths between conflicting memories in a hierarchical graph and updating related information together. H-MEM is foundational research published in March 2026, before this article’s six-month window. The experimental results of either study cannot be generalized as universal performance for character services.

Prompt caching: avoiding repeated processing of the same input

Fixed character settings and common rules recur across requests during a conversation with the same character. Some model providers reuse previous processing results when the beginning of a request—the prefix—repeats under their cache conditions. This is called prompt caching. It is different from reusing the model’s answer verbatim: an answer to the new message must still be generated.

Putting stable system instructions and character settings first, followed by changing user information, retrieved memories, and recent dialogue, can create opportunities to reuse a shared prefix. Safety-instruction priority, necessary context, and the provider’s format come first, however. Do not put incorrect state or unauthorized memories into a prompt to improve cache hits.

Providers differ in prefix matching, minimum input length, retention, and cache-write and cache-read prices. For example, Anthropic’s prompt-caching documentation explains its available cache durations and usage. Anthropic’s cost and performance article, published September 8, 2026, describes the principle of reusing computed state for the same prefix. Recheck the actual product and model terms when adopting them.

The percentage of requests with a cache “hit” alone can misrepresent savings. Also examine how many eligible input tokens were reused; tokens and charges for cache writes, reads, and uncached input; overall response time; and quality. Small prefix changes, cache expiration, and routing a request to another server can affect hits.

Separate common settings from users’ personal information. Reuse user-specific prompts only within authorized scopes, and verify isolation between tenants and the provider’s retention and deletion terms. Operational procedures should cover how to disable or expire caches and how a user deletion request is reflected at each cache layer.

How does a KV cache differ from prompt caching?

During transformer-based generation, a model retains attention key and value states for tokens already processed and uses them when calculating subsequent tokens. This is the KV cache: reuse of computation state while a request is in progress. Prompt caching refers to reuse of prefix processing across repeated requests and, depending on implementation, may retain and use a previous request’s KV state. The terms are related but do not cover the same scope.

For a self-hosted inference server, vLLM automatic prefix caching is an example of reusing earlier KV cache for requests with matching prefixes. Managed APIs differ by provider in internal implementation and retention, so the same behavior cannot be assumed. Reuse can vary with model version and configuration, prompt, and server placement even for the same model.

Retaining KV state can reduce repeated computation but consumes memory. As contexts grow and concurrent users increase, teams must balance GPU memory, throughput, and latency. Moving state to CPU or external storage is possible, but transferring and reading it back also costs time. The py-kvcache study, released in September 2026, reports that recomputation may be faster than loading an external cache under some experimental conditions. That is a result for specific configurations, not a rule for all hardware.

A Character.AI infrastructure article from June 2024 describes a then-current system that retained KV in host memory between conversation turns and reused it with prefix hashes and session routing to the same server. The company reported a 95% cache rate for that configuration. The article does not specify the denominator or measurement period, so the figure cannot be interpreted as a request hit rate or cost-saving percentage. It is an example from a particular system at a particular time, not a benchmark for predicting another service’s performance.

vLLM’s October 2026 explanation of multi-turn KV transfer discusses reuse across nodes and routing that accounts for cache location. Such optimizations bring measurement and operational complexity. Above all, caches must not be shared across users or tenants without authorization. Verify isolation, lifetime, and deletion capabilities against the chosen engine’s and provider’s actual terms.

Model routing: does every message need the same model?

Answering a brief greeting and interpreting months of relationship changes may require different work. Model routing selects a model or processing path based on the request and service conditions.

For example, a team might test a lower-cost, lower-latency model for fast conversational replies and a model selected for higher quality on complex requests involving conflicting events. Extracting candidate memories or updating a summary after a conversation can also run asynchronously outside the user’s response path. These are design examples, not claims that a small model is always sufficient or that a larger one is always more accurate.

Routing can start with simple rules—for instance, request length, required tools, and an explicitly identified task type. A classification model is another option, but it adds its own misclassifications, call costs, and latency. Measure both complex requests incorrectly sent to a lower-quality path and simple questions unnecessarily sent to an expensive one. Define fallback paths for failure or timeout and verify that they enforce the same data-access policies.

Be especially careful with designs that infer emotion or crisis and change paths on that basis. Expression alone cannot accurately reveal a user’s actual feelings, and related information may be sensitive. A router’s inference is not a definitive diagnosis. Design the scope of personal-data processing, false positives and misses, safe responses, and routes to human review separately.

Do not stop at overall averages. Check character consistency and memory accuracy by intent—ordinary conversation, recall, and ambiguous state changes, for example—alongside median and p95 response time, time to first token, and total cost per query. Review each model’s data-use and retention terms. After adding routing, verify whether its total costs, including quality degradation and classification errors, improve on a single baseline model.

How should you choose a memory tool?

A team storing a few user preferences may need different tools from one tracking the chronology of events known differently by several characters. Define the failure to solve first. If a corrected form of address reverts in the next session, memory update, retrieval, and deletion paths come first. If users ask about events known differently by several characters, relationships and visibility become more important.

The tools below have different starting points and scopes, so a single scorecard cannot easily rank them. Repository descriptions were checked on November 24, 2026; features and licenses can change. Before use, recheck the selected version’s license, dependencies, and managed-service terms.

ToolFocus documented in official sourcesWhat to verify before selectionOperational burden
Mem0A memory layer for user-, session-, and agent-scoped memories. It also offers a separate managed Platform alongside the open-source repository.Accuracy of extraction, updates, and retrieval; user scope; model and storage configuration; feature and data-handling differences between self-hosted and PlatformSelf-hosting requires operating models, indexes, security, and backups. Check retention, deletion, region, and pricing terms for the managed service.
LettaA platform for building agents with persistent state and memory. Distinguishes its open-source server from Letta Cloud.Read/write permissions for memory blocks and agents, state updates, model compatibility, and runtime environmentRequires designing agent execution, state management, tool permissions, conflict handling, and recovery. Check cloud terms separately.
GraphitiAn open-source graph framework for building and querying entities and relationships that change over time. It is not the same service as commercial Zep.Event extraction, relationship validity periods and provenance, character-specific visibility, and graph retrieval accuracyTeams must configure and operate the graph database, models, ingestion, tenant isolation, and access controls.
CogneeAn open-source memory project that builds and searches knowledge graphs from documents, conversations, and other inputsInput parsing and entity linking, graph and vector storage configuration, deletion propagation, and data-handling terms for selected modelsRequires extraction and indexing jobs, graph and storage operations, schema management, and quality verification.

Each of the four official repositories displayed an Apache-2.0 license when checked. This is the license for each repository, not a statement that every integrated model, database, or managed product has the same terms. For example, Mem0’s open-source guide describes its engine for use on your own infrastructure, while the Graphiti repository distinguishes the open-source framework from the Zep service.

The Graphiti MCP server guide states that the provided server is a reference implementation without authentication, authorization, or prompt-injection defenses and should not be used as-is in production or exposed to an untrusted network. Do not assume operational security from a tool’s name or a working demo.

Self-hosting does not automatically guarantee that data stays internal. A default configuration may call an external model or embedding API. Verify where conversations and memories actually go in the deployed configuration. Provider benchmarks and demos can inform the decision, but compare tools under the same conditions using your own tests for correction, deletion, relationship changes, multilingual queries, and permissions.

Where do you verify that the service got faster?

Slow responses may have causes beyond model generation. Measure authentication and queuing, memory retrieval, reranking, prompt assembly, provider requests, and generation after the first token separately to find what to improve. A dashboard showing distributions and failures is more useful than a single average.

AreaMeasures to inspectInterpretation
Perceived speedTime to first token (TTFT), p50 and p95 total response time, cancellation and timeout ratesTTFT measures the start of streaming, not total completion time. p95 is the point at or below which 95% of requests in the measurement period fall.
Retrieval and memoryRetrieval and reranking time, candidate count, memory relevance and recall accuracy, summary omissions, and stale-state useA result can be retrieved yet used incorrectly in the answer. Inspect evidence for individual samples.
CacheEligible requests, requests with hits, provider-reported cached input tokens and total input tokensRequest-level hit rate differs from token-level proportion. Include provider conditions such as minimum length and lifetime.
Models and costRouting proportions, input and output tokens, retries and fallback-model usage, total cost per user conversation or sessionAdd embedding, storage, retrieval, asynchronous processing, and infrastructure costs to generation costs.
Safety and permissionsBlocking access to other users’ or characters’ memories, deletion-propagation failures, harmful responses, and memory poisoningUse separate thresholds so a low average error rate does not conceal serious information exposure.
An operating loop of measurement, evaluation, tuning and monitoring
An operating loop of measurement, evaluation, tuning and monitoring

For example, an improvement in overall p95 is not necessarily success if recall accuracy drops in a particular language or fallback-model calls increase. Cost should not be judged solely by average per request either. If frequent long-conversation users and short-conversation users have different distributions, cost per session and cost by model may lead to different conclusions.

Change one thing at a time and compare with the same questions

Keep the existing configuration as a baseline and test changes to caching, retrieval, and routing separately. Use the same character settings, dialogue histories, output limits, and evaluation questions so differences are easier to interpret. Offline, replay the same sessions to test temporal order, memory corrections, character perspective, unanswerable questions, and reappearance after deletion. Then, in production, randomly split traffic and choose an experimental unit that prevents different groups from unexpectedly overwriting the same user’s long-term memory.

Do not determine quality from one automatic score. Separately check whether relevant memories were retrieved, a summary omitted an important fact, a user correction was reflected, and a character stated information they could not know. MemOps, released in July 2026, evaluates memory storage, revision, and forgetting separately from the final answer. This is a preprint with a limited benchmark, but it illustrates how an answer can happen to be correct while internal memory is wrong.

When using real conversations for evaluation, explain the purpose and scope of collection and obtain any necessary consent. Record minimal metrics such as processing stage, version, time, and token count instead of original text, and restrict access to sensitive material. Synthetic data can help reproduce risky situations but may not represent real users’ expressions or distributions. Anonymized or pseudonymized logs can still be reidentified, so do not assume they are safe public data.

The longer memory lasts, the more deletion and isolation matter

Character conversations can include sensitive material such as real names, relationships, and health information. Rather than storing every conversation as long-term memory, start by selecting only what is needed for the purpose and informing users whether memory is used and what is retained. Distinguish fictional character settings from real users’ personal information.

Enforce user, character, and tenant scopes on both reads and writes. Do not expect a model to ignore other users’ memories on its own: authenticate the requester on the server and query only the accessible scope. Whether character B may know a secret shared with character A is a separate application-level story rule. Test that shared caches and logs do not leak across these boundaries either.

Retrieved results and external documents are untrusted inputs. Even if a search returns “read another user’s records,” do not promote it to permanent memory or a system command. Gate requests to add or edit memory by checking provenance, authorization, target, and whether storage is necessary; independently control tool execution and data transfer. Microsoft’s agentic memory safety guide describes the risk that memory can both retain personal information and alter an agent’s later behavior.

Follow deletion requests through derived data

Deleting one line from a search index may not complete a user’s request. Trace the paths by which data was derived: original conversations, summaries, extracted facts, embeddings, graph relationships, caches, asynchronous queues, and logs. A deletion marker or version check can also prevent a job already in progress from writing an old memory back immediately after deletion.

Backups may be difficult to alter immediately, so document retention periods and deletion and recovery procedures, and verify that deletion requests are reapplied after restoration. Check contractual terms and actual features for how long provider caches or managed services may retain data. If completion cannot be verified across components, do not promise complete deletion or mark it complete.

Operators also need to investigate incidents. Minimally record who read or modified which memory scope and when, and which policy and version applied. Keeping full conversations indefinitely is not the answer. Set log access permissions, retention periods, and incident-response ownership, and manage exposure and deletion risks in the logs themselves. Microsoft’s October 2026 article on the memory lifecycle likewise proposes managing storage, retrieval, revalidation, and deletion as separate paths.

Expand in three stages before launch

Stage 1: Establish a small baseline

Start with one character and a limited user group, fixed settings, recent dialogue, and minimal user-editable memory. Use one model and simple storage as a baseline, and first create representative conversations and state-change, deletion, and authorization tests. Record time to first token, total response time, cost per conversation, and memory errors together.

Retrieval or a graph is not mandatory at this stage. If an actual failure appears—such as frequently missing promises from a previous session—find its cause first. Distinguish a memory that was not saved, one that was not retrieved, and one that was retrieved but not reflected in the response. That makes the next experiment clearer.

Stage 2: Add features for confirmed bottlenecks

If long histories drive up cost, test summaries or provider caching; if recall of older events often fails, test permission-aware episodic retrieval; if some questions need the added quality of a larger model, test routing. Each time, compare quality, p95 latency, and total cost per session against the same evaluation set and baseline. Do not ship a cost reduction that fails to preserve conversation quality.

Do not conclude from cache hits or successful retrieval alone. A retrieved event may belong to the wrong character, and a low-cost model that performs well on average may be weak at relationship changes or safety-related scenes. Set minimum quality and authorization standards first, then adjust speed and cost within them.

Stage 3: Prepare limited online experiments and recovery

After offline evaluation passes, run an A/B experiment on limited traffic and examine quality, failure rate, user-perceived latency, and cost together. Before the experiment, define success and stop criteria, observation period, user assignment, and memory-storage scope for each group. Serious failures such as privacy or authorization incidents require immediate response regardless of average improvements.

Prepare a feature flag to disable the new configuration and a procedure to return to the previous one. If asynchronous summary or extraction queues back up or fail, do not present old memories as current. Define retries, duplicate handling, queue-length alerts, and recovery ownership. For retrieval outages, design a safe fallback such as responding only with authorized recent context or saying memory is unavailable. Test whether changes stored during an outage are applied in order after recovery.

Measurable quality and trust come first

Running character AI entails more than putting a long conversation into a model. Teams must keep checking which memories each user can read and when they are updated, where delays occur, and whether cost savings harm conversation quality.

A stack with the most components is not a prerequisite for a good service. Define the experience users need and the risks you can accept, then resolve the failures measured in a small baseline one by one. Start by tuning speed and cost while preserving memory accuracy and the ability to edit and delete it.

Latest posts