Leanpub Header

Skip to main content

Engineering Memory for AI Agents

From First Principles to Production Systems

This book is 100% completeLast updated on 2026-08-14

AI agents don’t fail because they forget everything. They fail because they remember badly. This book shows you how to engineer memory that stays accurate, efficient and useful over time. From SQLite and PostgreSQL to vector indexes and multi-agent systems, you’ll learn what it takes to build agents that can run for days without losing the plot.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
169
Pages
About

About

About the Book

Most AI agents are built without a deliberate memory architecture. They accumulate conversation history until context windows overflow, retrieve documents with brittle vector searches and fail in unpredictable ways when information changes or contradicts itself. This book treats agent memory as an engineering discipline rather than a feature. You will learn how to design systems that remember what matters, forget what does not, retrieve accurately under pressure, scale without exploding costs and operate reliably across days of continuous use with multiple agents sharing state. The material progresses from first principles through working implementations in SQLite, PostgreSQL and vector indexes to production architectures for long-running autonomous agents. No single model, vendor or framework is assumed correct; the emphasis is on understanding mechanisms deeply enough to make your own trade-offs with confidence.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 420 engineers and researchers. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

From First Principles to Production Systems

Introduction

  1. The Problem with “Just Use a Larger Context Window”
  2. What Agent Memory Actually Is
  3. How This Book Is Organized
  4. Prerequisites

Chapter 1: Why Agents Need Memory

  1. The Context Window Is Not Memory
  2. What Happens When Agents Forget
  3. Defining Agent Memory vs Related Concepts
  4. The Cost of Forgetting in Real Systems

Chapter 2: A Taxonomy of Agent Memory

  1. Working Memory and Short-Term State
  2. Episodic Memory for Interaction Histories
  3. Semantic Memory for Facts and Knowledge
  4. Procedural Memory for Skills and Patterns
  5. Entity, User, Task and Environmental Memory
  6. Shared Multi-Agent Memory

Chapter 3: The Memory Lifecycle from Capture to Retrieval

  1. Observing and Capturing Candidate Memories
  2. Deciding What Is Worth Remembering
  3. Extracting Facts, Entities and Relations
  4. Structuring and Enriching Raw Observations
  5. From Capture to Storage: The Memory Pipeline

Chapter 4: Representing Memories: Schemas and Data Structures

  1. Designing a Memory Schema
  2. Generating Embeddings for Semantic Search
  3. Importance, Confidence and Decay Scores
  4. Deduplication and Consolidation Strategies
  5. Temporal Versioning and History Tracking
  6. Forgetting Policies and Expiration

Chapter 5: Storage Foundations from Files to Databases

  1. In-Memory Structures and File-Based Storage
  2. SQLite with Full-Text Search (FTS5)
  3. PostgreSQL for Structured Memory at Scale
  4. Vector Indexes and Approximate Nearest Neighbor
  5. Document Stores, Key-Value Stores, and Object Storage
  6. Graph Databases for Relational Memory

Chapter 6: Retrieval Systems for Finding What Matters

  1. Lexical Retrieval with BM25
  2. Vector Similarity Search Internals
  3. Hybrid Retrieval: Combining Lexical and Semantic
  4. Metadata Filtering and Constrained Search
  5. Reciprocal Rank Fusion and Multi-Signal Ranking
  6. Rerankers and Cross-Encoders
  7. Temporal and Graph-Based Retrieval

Chapter 7: Context Engineering for Injecting Memories into Prompts

  1. Token Budgets and Context Constraints
  2. Relevance vs Recency in Memory Selection
  3. Dynamic Context Assembly Strategies
  4. Hierarchical and Recursive Summarization
  5. Memory Scopes, Namespaces, and Isolation
  6. Prompt Construction with Retrieved Memories

Chapter 8: Memory Architectures for Agent Types

  1. Memory for Tool-Using Agents
  2. Coding Agents and Repository-Aware Memory
  3. Research Agents and Long-Horizon Reasoning
  4. Personal Assistants and User-Centric Memory
  5. Multi-Agent Systems and Shared Memory
  6. Autonomous Workflows, Plans, and Checkpoints

Chapter 9: Frameworks, Integrations, and Interoperability

  1. Vendor-Independent Memory Architecture
  2. Integrating with Model APIs and Tool Calling
  3. The Model Context Protocol (MCP) for Memory Tools
  4. Plugging into Agent Frameworks Without Lock-In
  5. Designing a Memory Service API

Chapter 10: Correctness, Reliability, and Consistency

  1. Stale Memories and Knowledge Drift
  2. Contradictions and Conflicting Information
  3. Provenance, Attribution, and Trust
  4. Deterministic vs Probabilistic Retrieval Guarantees
  5. Concurrency, Race Conditions, and Consistency
  6. Backups, Migrations, and Disaster Recovery

Chapter 11: Security, Privacy, and Access Control

  1. Access Control and Tenant Isolation
  2. Encryption at Rest and in Transit
  3. Handling Secrets and Sensitive Data
  4. Prompt Injection Through Stored Memories
  5. Memory Poisoning and Malicious Content
  6. Deletion, Retention, and Auditability

Chapter 12: Evaluating Agent Memory

  1. Retrieval Metrics: Precision, Recall, and Ranking
  2. Task-Success Measurement with Memory
  3. Long-Horizon Benchmarks and Stability Tests
  4. Cost, Latency, and Efficiency Metrics
  5. Ablation Testing and Causal Attribution
  6. Building Repeatable Evaluation Pipelines

Chapter 13: Observability, Debugging, and Diagnostics

  1. Memory Traces and Retrieval Logs
  2. Ranking Explanations and Decision Auditing
  3. Token Accounting and Context Visibility
  4. Interactive Memory Inspection Tools
  5. Diagnosing Common Failure Modes

Chapter 14: Performance, Cost, and Scale Engineering

  1. Embedding Costs and Optimization Strategies
  2. Query Latency and Indexing Performance
  3. Storage Growth Modeling and Cost Projections
  4. Caching, Batching, and Throughput
  5. Partitioning, Sharding, and Replication
  6. Token Cost Engineering

Chapter 15: Building a Production Memory System via a Staged Roadmap

  1. Stage 1: Minimal Memory with Conversation History
  2. Stage 2: Persistent Structured Memory in SQLite
  3. Stage 3: Lexical and Semantic Retrieval with Hybrid Ranking
  4. Stage 4: Consolidation, Forgetting, and Temporal Reasoning
  5. Stage 5: Provenance, Evaluation, Observability, and Security
  6. Stage 6: Scalable Multi-Agent Production Architecture

Conclusion: The Engineering Discipline of Agent Memory

  1. What We Know
  2. What Remains Uncertain
  3. When Simple Is Better
  4. The Path Forward

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub