Zero Labs
Industry News / AI

Long-Term vs Short-Term Memory for AI Agents: A Practical Guide Without the Hype

Source · Towards AI By Andrii Tkachuk

From the publisher’s feed, collected in the ZeroLabs newsroom.

Over the past year, memory has become one of the most overused — and misunderstood — concepts in AI agent design.But before I start, I want to add a few words, most of us building AI agents today didn’t start as “AI engineers”. We come from backend engineering, data engineering, or data science.That background shapes how we think about systems: scalability, reliability, clear lifecycles, and predictable failure modes.And when we bring LLMs and agents into production, we still care about the same things:we don’t want state explosionswe don’t want hidden couplingand we definitely don’t want to create systems that make life harder for backend engineers and architects down the line.This article is written from that mindset, not “what sounds impressive in demos”, but what leads to a reasonable trade-off between AI capabilities, backend architecture, and long-term system health.You hear phrases like long-term memory, short-term memory, context engineering, persistent agents, and stateful conversations everywhere. But if you look closely at most real implementations, many teams either:don’t actually use memory at all, oruse it in ways that introduce serious scalability and reliability issues.This article aims to cut through the hype and explain, in practical terms, how memory for AI agents actually works, which approaches exist today, and what trade-offs they come with.Photo by dianne clifford on UnsplashBefore we start!🦾If this piece gives you something practical you can take into your own system:👏 leave 50 claps (yes, you can!) — Medium’s algorithm favors this, increasing visibility to others who then discover the article.🔔 Follow me on Medium and LinkedIn for more deep dives into agentic systems, LLM architecture, and production-grade AI engineering.First, Let’s Define the Terms ClearlyLong-Term Memory (LTM)Long-term memory is anything that persists across sessions, restarts, and disconnections (includes the agent’s past behaviors and thoughts that need to be retained and recalled over an extended period of time; this often leverages an external vector store accessible through fast and scalable retrieval to provide relevant information for the agent as needed).Typical characteristics:Stored in databases, object storage, or vector storesSurvives process restartsNot necessarily injected into the model on every requestCommon forms of LTM:Full chat history stored in a relational databaseEvents or messages stored in an append-only logVector embeddings of conversations or summariesUser preferences, profiles, or behavioral factsThink of long-term memory as durable knowledge, not working context.Short-Term Memory (STM) / Working MemoryShort-term memory (often called working memory or execution state, includes context information about the agent’s current situations; this is typically realized by in-context learning which means it is short and finite due to context window constraints) is:EphemeralSession-scopedTypically stored in RAMUsed during active interactionIn practice, what we call “short-term memory” in agents usually combines:conversational state (messages)execution state (tool outputs, intermediate results)control flow metadataShort-term memory exists to reduce overhead and improve reasoning continuity, not to replace persistence.Approach #1 — The Legacy Stateless Approach (Still Very Common)The most widespread approach today is actually stateless.How it worksFor every user request:Fetch chat history from a persistent data storeTruncate or limit itInject it into the promptRun the agentRepeat on the next requesthistory = db.load_last_messages(user_id, limit=20)prompt = build_prompt(history, user_message)response = llm(prompt)ProsExtremely simpleEasy to reason aboutNo RAM management concernsWorks well in serverless environmentsConsDatabase is hit on every requestContext is always injected, even when not neededHard limits must be enforced aggressivelyBecomes expensive and slow at scaleThis approach does not use short-term memory at all. Each request is fully independent.Approach #2 — Short-Term Memory via In-Memory State (LangGraph-Style)A more advanced approach introduces explicit short-term memory.This is the model used by frameworks like LangGraph.Core ideaLoad long-term memory onceKeep a mutable state object in RAMUpdate it as messages arriveUse it throughout the agent flowDispose of it when the session endsConceptually:class ChatState(TypedDict): user_id: str messages: list[dict]Typical flow (e.g., with WebSockets or Socket.IO)SocketIO one of the most common and well-known framework for building chat based applications.On connectLoad chat history from the databaseStore it in an in-memory state objectOn each messageRead state from RAMUpdate messagesRun the agentOn disconnectOptionally persist summaryRemove state from memoryProsNo database calls on every messageMuch faster per interactionNatural conversational continuityClean separation between LTM and STMCons (and they are important)RAM usage grows with:number of concurrent userslength of conversationsRequires:strict size limitstrimming or summarizationTTL / garbage collectionSocket-based systems have edge cases:dropped connectionsmultiple tabs per usermissing disconnect eventsThis approach can be production-ready, but only if memory management is treated as a first-class concern.Context Variables: What They Are (and What They Are Not)Many implementations add context variables (for example, ContextVar in Python) to avoid passing state through every function.This is useful — but limited.Context variables:✔️ Improve code readability✔️ Allow access to state “from anywhere” in the execution flow❌ Do NOT persist state across events❌ Do NOT replace an in-memory storeThey are an access pattern, not a memory strategy.What context variables are good forAvoiding passing state through dozens of function callsAccessing the current execution state inside deep agent logicImproving code readabilitystate = get_current_state()state["messages"].append(new_message)What they do not doThey do not persist memory across eventsThey do not replace an in-memory storeThey do not solve session lifecycle problemsContext variables are a convenience layer, not a memory system.Approach #3 — Memory as a Tool (The New Emerging Pattern)A newer and increasingly popular approach is Memory as a Tool.Before dismissing this approach as “too complex”, I would strongly recommend trying it at least once.Even if you don’t end up using Memory as a Tool in production, it forces you to think differently about agent design:how and when an agent decides to fetch informationhow tool invocation is triggered intentionally rather than implicitlyand how much context is actually needed to solve a task.In practice, this approach is one of the best ways to truly understand:how tool usage workshow to guide an agent to call the right tool at the right timeand how modern reasoning-based agents operate internally.Many engineers are familiar with prompts and APIs, but far fewer have hands-on experience with ReAct-style loops or explicit reasoning-driven tool calls. Trying this pattern — even in a small prototype — helps close that gap.I’ll link a few articles below that go deeper into ReAct, reasoning models, and tool-based agents for those who want to explore this further.Building AI Agents: Reasoning, Tools, and the Role of MCPDesigning AI Agents Like Microservices: A Practical Mental Model for Modern ArchitecturesCore ideaInstead of automatically injecting memory, you expose memory retrieval as a tool:Tool: retrieve_chat_history(user_id, chat_id, offset=0, limit=10)The agent decides:whether it needs past contexthow much of itwhen to fetch moreHow it worksAgent receives a user messageAgent reasons whether history is requiredAgent calls the retrieval toolTool returns paginated historyAgent may repeat if neededProsMinimal context injectionLower token usageMemory is fetched only when relevantExcellent fit for modern reasoning modelsConsRequires stronger modelsHarder to debugMore complex agent logicLatency depends on retrieval callsCritical requirement: Reasoning + ReAct loopThis pattern assumes:a reasoning-capable modelmulti-step planningtool invocation loopsreflection on observationsWithout a ReAct-style agent:the model may never request memoryor request it too lateor request irrelevant partsThis is not a drop-in replacement for traditional memory injection.When it works bestStrong reasoning modelsWell-designed ReAct promptsNon-critical memory requirementsSystems tolerant to occasional mistakesWhen it’s riskyIf history is always requiredIf correctness is criticalIf missing context causes failureIf the model is weak or unstableWith modern multi-step reasoning models, this approach is becoming increasingly viable — and often superior for large-scale systems.!!! Many people might immediately start talking about security risks and so on, and they will be absolutely right, but let’s figure it out.Memory used as a tool does introduce security considerations, but not fundamentally different from any other tool.Prompt injection can attempt to trigger a memory read or write, but it cannot access anything beyond what the memory tool explicitly allows. The real security boundary is not the prompt, but the tool implementation.This is why memory must:be accessed only via a tool (never auto-injected)be strictly scoped (user_id / tenant_id / namespace)validate both read and write operationsexplicitly control what can be recalled and how much (so called wrapper should always be)In practice, prompt injection cannot recall another user’s memory unless there is already a bug in isolation or authorization logic. The larger risk is memory poisoning (writing bad memory), which should be mitigated by validation and write policies inside the tool wrapper, but that’s an absolutely different topic, my folks. If you are interested in this topic, I can also write my observations, experience, and thoughts on this matter.Choosing the Right ApproachThere is no single “correct” memory strategy.Use hybrid memory, since it integrates both short-term memory and long-term memory to improve an agent’s ability for long-range reasoning and accumulation of experiences.In practice, hybrid architectures work best:Long-term memory for durabilityShort-term memory for performanceTool-based retrieval for flexibilityFinal ThoughtsMemory is not magic.Most problems attributed to “lack of memory” are actually:poor context selectionuncontrolled state growthmissing lifecycle managementBefore adding complexity, ask:Does the agent really need this context?For how long?Who is responsible for cleaning it up?If you answer those questions honestly, the right architecture usually becomes obvious.And that’s a wrap! If you’ve read this far, it probably means you found this article useful or insightful. If that’s the case, consider leaving a few claps or sharing it with your team, please. Thanks for reading! 🚀Long-Term vs Short-Term Memory for AI Agents: A Practical Guide Without the Hype was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.