Inferensys

Glossary

Mark-and-Sweep

Mark-and-sweep is a fundamental garbage collection algorithm that operates in two distinct phases: marking all reachable objects from root references, then sweeping to deallocate memory used by unmarked objects.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
MEMORY UPDATE AND EVICTION

What is Mark-and-Sweep?

A foundational garbage collection algorithm for automatic memory management.

Mark-and-sweep is a two-phase, tracing garbage collection algorithm that automatically reclaims memory allocated to objects no longer reachable by a program. In the mark phase, the collector traverses the object graph starting from root references (like global variables and stack frames) and marks every reachable object as 'in-use'. The subsequent sweep phase iterates through all allocated memory, deallocating any object not marked during the first phase, returning its memory to the free pool. This process prevents memory leaks by identifying unreachable, 'garbage' objects.

The algorithm's primary advantage is its ability to handle reference cycles, where objects reference each other but are collectively unreachable from the roots. Its main drawbacks include stop-the-world pauses during collection and potential memory fragmentation. In agentic systems, analogous logic can be applied for cache eviction or pruning an agent's episodic memory buffer. Related memory management concepts include garbage collection (GC), reference counting, and eviction policies like Least Recently Used (LRU).

GARBAGE COLLECTION ALGORITHM

Key Characteristics of Mark-and-Sweep

Mark-and-sweep is a fundamental, two-phase garbage collection algorithm that identifies and reclaims memory occupied by objects no longer reachable from the program's root set.

01

Two Distinct Phases

The algorithm operates in two strictly sequential, non-interleaved phases:

  • Mark Phase: Starting from a set of root references (e.g., global variables, active stack frames), the collector traverses the entire object graph, marking every reachable object as 'alive'.
  • Sweep Phase: The collector linearly scans the entire heap. Any object not marked during the previous phase is deemed unreachable garbage. Its memory is reclaimed and added to a free list for future allocations. This clear separation simplifies implementation but introduces a stop-the-world pause, as all mutator (application) threads must be halted to ensure a consistent view of the object graph.
02

Handles Cyclic References

A key strength of mark-and-sweep is its ability to correctly collect cyclic reference structures, which are fatal to simple reference-counting collectors.

  • In a cycle (e.g., Object A references Object B, which references Object A), reference counts never drop to zero even if the cycle is unreachable from the roots.
  • Because mark-and-sweep uses graph reachability from external roots as its liveness criterion, it correctly identifies the entire cycle as garbage if no root points to it. The collector will fail to mark any object in the cycle and the sweep phase will reclaim all their memory.
03

Heap Fragmentation

A major drawback is the potential for memory fragmentation. Since objects are reclaimed in-place during the sweep, free memory becomes scattered in gaps between live objects.

  • This external fragmentation can lead to allocation failures even when total free memory is sufficient, as no single contiguous block may be large enough for a new allocation.
  • Mitigation strategies include compacting collectors (like mark-compact) that relocate live objects after sweeping to consolidate free space, or sophisticated free list allocators that can coalesce adjacent free blocks.
04

Algorithmic Complexity

The time and space complexity of the algorithm is defined by its phases:

  • Time Complexity: O(L + H) where L is the number of live objects (traversed during mark) and H is the total size of the heap (scanned during sweep). Performance degrades as heap size grows.
  • Space Complexity: Requires auxiliary space for the mark bits. Typically, a dedicated bit (the 'mark bit') is stored in the object header or in a separate mark bitmap. This overhead is minimal but non-zero. The pause time is proportional to the heap size, not the amount of garbage, making it less suitable for real-time systems without modifications.
05

Tracing Collector Foundation

Mark-and-sweep is the archetypal tracing garbage collector. Its core principle—determining liveness by tracing references from roots—underpins most modern GC algorithms.

  • Generational Collectors (like in Java's G1, ZGC) use mark-and-sweep (or mark-compact) for old generation collection.
  • Incremental and Concurrent variants (e.g., Tri-color marking) were developed to reduce its long pause times by interleaving marking/sweeping with mutator execution.
  • It contrasts with direct collectors like reference counting, which track liveness per-object without a global tracing phase.
06

Application in Agentic Systems

In agentic memory management, mark-and-sweep principles inform context window eviction and long-term memory pruning.

  • Episodic Buffer Cleanup: An agent's short-term working memory (e.g., a conversation buffer) can be viewed as a heap. Unreachable intermediate thoughts or deprecated tool call results are 'garbage'.
  • Vector Store Maintenance: In a vector database backing agent memory, old, irrelevant, or low-quality embeddings that are no longer linked to any active agent context or knowledge graph entity can be identified (marked) via metadata and swept (deleted) in batch jobs to manage storage costs and retrieval performance.
MEMORY UPDATE AND EVICTION

Frequently Asked Questions

Essential questions about the mark-and-sweep algorithm, a foundational garbage collection technique critical for managing memory in long-running agentic systems.

Mark-and-sweep is a fundamental, two-phase garbage collection (GC) algorithm that automatically reclaims memory occupied by objects no longer reachable by a program. In the first marking phase, the algorithm traverses the object graph starting from root references (like global variables and active stack frames) and marks all reachable objects. In the subsequent sweeping phase, it scans the entire heap, deallocating the memory of any objects not marked as reachable, effectively treating them as garbage.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.