Python’s Cyclic Garbage Collector
Python’s cyclic garbage collector is a backup to reference counting: it finds groups of objects that still reference one another but can no longer be reached by a running program. Reference counting can reclaim most objects immediately, but it cannot reclaim those isolated cycles.
The problem reference counting cannot solve
CPython, the standard Python implementation, normally stores a count of the references to each object. Assigning an object to a variable increments its count; removing that reference decrements it. When the count reaches zero, CPython can destroy the object immediately and release its memory.
That works until objects form a cycle:
class Node:
pass
a = Node()
b = Node()
a.other = b
b.other = a
del a, b
After the del, no live variable points to either node. However, each node still has one reference—from the other node—so neither count reaches zero. The objects are unreachable (the program cannot get to them) but not reference-free. Without another mechanism, every such cycle would remain allocated until the process ended.
The cyclic collector exists to find these islands of unreachable objects and reclaim them. It is not the main way ordinary short-lived objects are freed: reference counting usually handles those first.
What the collector examines
A reference cycle can only involve objects that contain references to other objects, such as lists, dictionaries, sets, class instances, and many extension types. These are called container objects. An integer or a string, for example, cannot by itself form a cycle because it does not hold references to other Python objects.
CPython keeps eligible container objects on internal tracking lists. During a cyclic collection, it makes a temporary accounting pass over them:
- It starts with each object’s current reference count.
- It subtracts references that come from other objects in the group being examined.
- Objects whose remaining temporary count reaches zero have no reference from outside that group.
- The collector follows references from the surviving objects and identifies the unreachable subgraph.
- It clears or breaks references in that unreachable group, allowing normal reference counting to destroy the objects.
The important distinction is between an object with references and an object reachable from the program. A cycle has the former but not the latter. The collector does not simply look for objects whose ordinary reference count is zero; that is precisely what cycles prevent.
The algorithm must also account for objects reachable through global variables, stack frames, module state, and other live structures. Those references keep an object alive even if it participates in a larger graph containing unreachable objects.
Modern CPython can generally collect cycles involving finalizers such as __del__, but finalization has ordering and side-effect complications. Code that relies on destructors to release important resources should use explicit cleanup, context managers, or try/finally instead of waiting for garbage collection.
Why collection is generational
Checking every tracked container after every allocation would be expensive. Python therefore uses generational garbage collection: it assumes that objects created recently are more likely to become unreachable soon, while objects that survive collections are more likely to keep surviving.
A new tracked object starts in the young generation. If it survives a collection, it is promoted to an older generation. A routine collection concentrates on the young generation and examines some older objects as well, rather than rescanning the entire heap every time.
The policy is controlled by thresholds exposed through the gc module:
import gc
print(gc.get_threshold())
# For example: (700, 10, 10) on some Python versions
The first threshold is tied to the net number of tracked allocations: allocations minus deallocations. When that amount grows past the threshold, CPython schedules a young-generation collection. The other thresholds control how often older generations are included and how much older data is examined.
The exact generation layout is version-dependent. Traditional CPython releases used three generations, numbered 0, 1, and 2; in that model, the second and third values controlled promotion and full older-generation collections. Python 3.14 removed the middle generation, so there are now young and old generations, and the third value returned by gc.get_threshold() is ignored. In current releases, the second threshold controls the proportion of the old generation examined during a collection.
That version detail matters when interpreting tuning advice or monitoring output. The stable idea is simpler: thresholds trade collection frequency against collection work. Lower thresholds find cycles sooner but cause more collections. Higher thresholds reduce collection overhead in the short term but allow more cyclic garbage to accumulate and can make a later collection larger.
You can inspect or change the policy with gc.get_threshold() and gc.set_threshold(), but changing it should follow measurement. Threshold tuning cannot make a fundamentally unbounded cycle disappear; it only changes when the collector looks for it.
The pauses collection can introduce
Reference-counting destruction is often small and immediate: decrement a count, run cleanup, and continue. A cyclic collection is different. CPython has to traverse object graphs, classify objects, and sometimes clear many references. During this work, application execution can be delayed.
These are stop-the-world pauses: in the usual CPython model, the thread performing collection holds the Global Interpreter Lock, so other Python threads cannot run Python bytecode at the same time. A young-generation collection is usually modest. A collection involving a large old generation, many connected objects, or expensive finalizers can produce a noticeable latency spike.
That is why a service may show an occasional pause even when CPU usage and request volume look steady. The relevant log line may mention gc.collect(), or a profile may attribute time to the gc module. Explicit calls can also create intentional pauses:
import gc
unreachable = gc.collect()
print(f"Collected {unreachable} objects")
This is useful for diagnostics and controlled maintenance, but calling it on every request usually defeats the generational design. If pauses matter, measure collection duration and frequency, look for code creating large temporary graphs or persistent cycles, and release resources explicitly where possible.
The collector’s role is therefore precise: reference counting handles immediate reclamation, while generational cycle detection periodically searches for unreachable containers that reference counting alone cannot free.