Python

Python Memory Management: Understanding Garbage Collection, Reference Counting, and Profiling

When we write Python code, we usually focus on whether it works correctly, how quickly it executes, and how easy it is to maintain. Memory management often…

D
DevByteTechnical Author
Published
24 min read5 views
Python Memory Management: Understanding Garbage Collection, Reference Counting, and Profiling

When we write Python code, we usually focus on whether it works correctly, how quickly it executes, and how easy it is to maintain. Memory management often gets less attention, especially when an application is small.

But as an application grows, memory usage can become a real problem.

Imagine you're building a Python API that processes thousands of requests every minute. Everything works fine during development, but after running for a few hours, the application starts consuming more RAM. Response times increase, background jobs become slower, and eventually, the process may run out of memory.

At first, you might assume that the problem is caused by a large dataset or an inefficient algorithm. Sometimes that's true. In other cases, the real issue is how objects are created, referenced, and released from memory.

Python handles most memory management automatically. You generally don't need to allocate and free memory manually, as you might in languages such as C. However, automatic memory management doesn't mean that memory problems cannot occur.

Understanding how Python manages memory helps you write more efficient applications, investigate memory leaks, and optimize resource-intensive code.

In this guide, we'll explore Python's memory management system, reference counting, garbage collection, common memory problems, and practical profiling tools.

1. What Is Memory Management in Python?

Memory management is the process of allocating memory to objects, keeping track of their usage, and making memory available again when objects are no longer needed.

Consider a simple example:

user_name = "Manjeet"
user_age = 25
user_skills = ["Python", "Node.js", "React"]

When Python executes this code, it creates objects representing the string, integer, and list. The variables refer to those objects.

The important distinction is that a variable is a name that refers to an object; it isn't the object itself.

For example:

first_name = "Manjeet"
second_name = first_name

Both variables refer to the same string object in this example. Python doesn't necessarily create a second copy of the string simply because another variable refers to it.

Now consider what happens when we reassign a variable:

first_name = "Manjeet"
first_name = "Developer"

The variable now refers to the new string object. If no references to the previous object remain, Python can reclaim its memory when appropriate.

This is one of the basic ideas behind Python's automatic memory management.

How Python Organizes Memory

In a typical Python implementation, especially CPython, memory management involves several components:

  • Object allocation: Memory is allocated when objects are created.

  • Reference counting: CPython tracks references to objects.

  • Garbage collection: A cyclic garbage collector helps identify unreachable reference cycles.

  • Memory allocators: Python uses allocation strategies to manage memory efficiently.

  • Operating system interaction: Python's memory allocator manages memory internally and may request memory from or return memory to the operating system.

These components work together, but they don't all behave in the same way.

For example, an object becoming unnecessary doesn't guarantee that the operating system will immediately report a decrease in the Python process's RAM usage.

To understand why, we first need to look at reference counting.

2. Understanding Reference Counting

Reference counting is one of the primary mechanisms CPython uses to manage object lifetimes.

The basic idea is straightforward: Python keeps track of references to an object. When its reference count reaches zero, the object can be deallocated.

Let's look at a simple example.

import sys

user = {
    "name": "Manjeet",
    "role": "Python Developer"
}

print(sys.getrefcount(user))

The sys.getrefcount() function returns the reference count for an object in CPython.

However, there's an important detail: calling sys.getrefcount() temporarily creates an additional reference to the object, so the displayed number is generally higher than the number of references you might expect from your code alone.

The exact number can also depend on the Python version and execution environment.

How Reference Counts Change

Consider this example:

user = {"name": "Manjeet"}

another_user = user

print(user is another_user)

Output:

True

Both variables refer to the same dictionary.

When we assign user to another_user, we create another reference to the existing object.

Now let's remove one reference:

user = {"name": "Manjeet"}

another_user = user

del user

print(another_user)

Output:

{'name': 'Manjeet'}

Deleting user doesn't delete the dictionary because another_user still refers to it.

The object remains accessible.

If we subsequently remove the final reference:

del another_user

The dictionary may now be deallocated because no references remain.

The del statement removes a name or reference; it doesn't directly guarantee that the underlying object's memory is immediately returned to the operating system.

Why Reference Counting Is Useful

Reference counting has several advantages:

  1. It allows CPython to reclaim many objects as soon as their reference counts reach zero.

  2. It reduces the amount of work that would otherwise be required by a periodic garbage collector.

  3. It makes object lifetimes relatively predictable for objects without reference cycles.

For example, a function that creates a temporary list can release references to that list when the function finishes, provided nothing else retains it.

def calculate_total():
    numbers = [10, 20, 30, 40, 50]
    return sum(numbers)


result = calculate_total()

print(result)

After the function returns, its local variable numbers no longer exists as a local reference. If no other references to the list remain, the list can be deallocated.

This works automatically. You don't need to manually free the list.

However, reference counting has a limitation: it cannot independently reclaim objects that reference each other in a cycle.

That's where garbage collection becomes important.

3. What Is Garbage Collection in Python?

Garbage collection is a process used to reclaim memory associated with objects that are no longer reachable.

In CPython, reference counting handles many object lifetimes, but cyclic references can prevent an object from reaching a reference count of zero.

Consider this example:

class Employee:
    def __init__(self, name):
        self.name = name
        self.manager = None


employee_a = Employee("Amit")
employee_b = Employee("Rahul")

employee_a.manager = employee_b
employee_b.manager = employee_a

Here, employee_a references employee_b, while employee_b references employee_a.

The two objects form a reference cycle.

Now remove the external references:

del employee_a
del employee_b

Neither object is accessible through those variable names anymore. However, each object still references the other.

Their reference counts therefore may not reach zero immediately.

In CPython, the cyclic garbage collector can identify and reclaim suitable unreachable reference cycles.

This is why Python uses both reference counting and cyclic garbage collection rather than relying on reference counting alone.

Does Python Run Garbage Collection Automatically?

Yes. CPython's cyclic garbage collector normally runs automatically when its allocation and collection thresholds indicate that a collection may be useful.

You don't generally need to call it manually.

The gc module provides functions for inspecting and controlling aspects of cyclic garbage collection.

For example:

import gc

print(gc.isenabled())

This tells you whether automatic cyclic garbage collection is enabled.

You can also request a collection:

import gc

collected = gc.collect()

print(f"Objects collected: {collected}")

The return value indicates the number of unreachable objects found and collected by that operation.

However, calling gc.collect() doesn't guarantee that your application's overall memory usage will decrease. It only performs a garbage-collection pass; it doesn't fix references that your application still holds.

Practical advice: Don't call gc.collect() after every request or every function call. Start by identifying the actual memory problem before changing garbage-collection behavior.

4. Understanding Generational Garbage Collection

Garbage collection can be expensive if the runtime repeatedly examines every object in a large application.

To reduce unnecessary work, traditional generational garbage collectors use the observation that many objects have short lifetimes, while objects that survive longer tend to remain useful for longer.

This idea is known as the generational hypothesis.

In CPython versions that use the traditional generational cyclic collector, objects are organized into generations. Collection strategies favor examining newer objects more frequently than older ones.

For example, a temporary list created while processing an API request may be needed only for a few milliseconds. A configuration object or a long-lived cache may remain in memory for hours.

The collector can use generational information to make its work more efficient.

Inspecting Garbage Collection Statistics

Python's gc module allows you to inspect collection statistics.

import gc

print(gc.get_stats())

The returned data contains collection statistics for the generations supported by the running Python implementation.

You can also inspect the collection thresholds:

import gc

print(gc.get_threshold())

And the current collection counters:

print(gc.get_count())

These values can help you understand the collector's behavior, but they aren't direct measurements of total application memory usage.

Important Version Differences

Python's garbage collector has changed across releases. In particular, Python 3.14 changed the traditional generational collection model, including removing generation 1 as a separate generation.

As a result, examples that assume three traditional generations shouldn't be treated as universally accurate for every modern Python release.

Before tuning collection thresholds or interpreting generation-specific statistics, check the documentation for your installed Python version.

For most applications, the default garbage-collection configuration is a good starting point.

5. Reference Counting vs. Garbage Collection

These mechanisms are related, but they solve different problems.

Feature

Reference Counting

Cyclic Garbage Collection

Main purpose

Track references to objects

Find unreachable reference cycles

Typical behavior

Reclaims objects when their reference count reaches zero

Periodically examines tracked objects for unreachable cycles

Timing

Often immediate when the count reaches zero

Depends on collection activity

Handles cycles by itself?

No

Yes, for supported unreachable cycles

Requires manual calls?

No

Usually no

Python interface

sys.getrefcount() for inspection in CPython

gc module

Performance consideration

Reference-count updates have a cost

Collection passes have a cost

One important detail: the cyclic garbage collector isn't responsible for all memory cleanup in Python.

In CPython, reference counting normally handles most object deallocation. The cyclic collector complements it by dealing with unreachable reference cycles.

Other Python implementations may use different memory-management strategies.

6. Common Causes of High Memory Usage in Python

Memory problems aren't always caused by garbage collection.

In many applications, objects remain in memory because the application still has references to them.

Let's look at several common causes.

6.1 Keeping Too Much Data in Lists

Imagine an API that loads a large dataset into memory before processing it.

def load_records():
    records = []

    for i in range(1_000_000):
        records.append({
            "id": i,
            "status": "active"
        })

    return records

This function creates one million dictionaries and stores references to them in a list.

The resulting memory usage can be substantial.

If you only need to process each record once, holding the entire dataset in memory may be unnecessary.

A generator can process values incrementally:

def generate_records():
    for i in range(1_000_000):
        yield {
            "id": i,
            "status": "active"
        }


for record in generate_records():
    process_record(record)

Here, process_record() represents your application's processing logic.

The generator produces records on demand instead of retaining every generated dictionary in a list.

This approach can significantly reduce peak memory usage when the consumer processes records without accumulating them.

Keep in mind that a generator doesn't make the entire workflow memory-efficient automatically. If process_record() stores every record in another list, the application can still consume a large amount of memory.

6.2 Accidentally Retaining Objects

Consider a service that stores every API response in a global list.

response_history = []


def handle_request(request):
    response = process_request(request)

    response_history.append(response)

    return response

This may appear harmless during development.

But if the service receives thousands of requests, response_history continues growing because the application retains references to every response.

The garbage collector cannot reclaim those response objects while they remain reachable.

A better solution depends on the actual requirement.

If you only need recent responses, use a bounded cache or queue. If you need request history, store it in a database or logging system rather than retaining the entire history in process memory.

For example:

from collections import deque

recent_responses = deque(maxlen=1000)


def handle_request(request):
    response = process_request(request)

    recent_responses.append(response)

    return response

This keeps at most 1,000 response references in the deque.

However, a bounded deque limits the number of retained responses, not their total size. If individual responses are very large, you may need a byte-based limit or a different storage strategy.

6.3 Loading Large Files Entirely Into Memory

This pattern can be expensive:

with open("large_dataset.txt", "r", encoding="utf-8") as file:
    content = file.read()

process_content(content)

The entire file is read into a string.

For a large file, that string may consume a significant amount of memory.

If you can process the file line by line, use iteration:

with open("large_dataset.txt", "r", encoding="utf-8") as file:
    for line in file:
        process_line(line)

This avoids creating one large string containing the entire file.

The same principle applies to database queries, CSV processing, log analysis, and document ingestion pipelines.

Instead of loading everything at once, consider streaming or batching.

6.4 Caches That Never Expire

Caching can improve performance, but an unbounded cache can become a memory problem.

For example:

cache = {}


def get_user(user_id):
    if user_id not in cache:
        cache[user_id] = fetch_user_from_database(user_id)

    return cache[user_id]

If user_id has millions of possible values, the dictionary can grow indefinitely.

A production application should define a caching strategy that matches its requirements.

Possible approaches include:

  • Maximum cache size.

  • Time-to-live expiration.

  • Least-recently-used eviction.

  • Explicit invalidation.

  • External caching systems such as Redis.

The right choice depends on whether the data can become stale, how frequently it is accessed, and how much memory the application can use.

6.5 Reference Cycles in Long-Lived Applications

Reference cycles are not automatically memory leaks. Python's cyclic garbage collector can handle many unreachable cycles.

However, problems may arise when objects remain reachable through global collections, caches, callbacks, or other long-lived references.

Some objects also require explicit cleanup of external resources, such as files, sockets, and database connections. Garbage collection alone is not a substitute for proper resource management.

For example, use a context manager for file operations:

with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()

The file is closed when execution leaves the with block, including when an exception occurs.

This is preferable to depending on object destruction to close the file at some later point.

7. What Is Memory Profiling?

Memory profiling is the process of measuring memory usage to understand how an application allocates and retains memory.

Instead of guessing which function causes a problem, profiling provides evidence about what is happening.

Suppose a Python API consumes 150 MB of memory after startup and gradually grows to 1.5 GB.

You could rewrite several functions, remove caching, or disable garbage collection. But without measurements, you might change code that has nothing to do with the problem.

Profiling helps answer questions such as:

  • Which parts of the application allocate the most memory?

  • Which objects are still alive?

  • Is memory usage increasing after every request?

  • Does a particular operation cause a large memory spike?

  • Are objects accumulating even when requests have completed?

  • Is memory usage stable after the application warms up?

Different tools answer different questions.

Python's built-in tracemalloc module is an excellent place to start.

8. Using tracemalloc to Track Memory Allocations

tracemalloc is a standard-library module that traces memory allocations made through Python's supported memory-allocation interfaces.

It can record allocation tracebacks, compare snapshots, and identify where traced memory is being used.

Let's build a simple example.

import tracemalloc


tracemalloc.start()

data = [
    {"id": i, "value": f"record-{i}"}
    for i in range(100_000)
]

current, peak = tracemalloc.get_traced_memory()

print(f"Current traced memory: {current / 1024 / 1024:.2f} MB")
print(f"Peak traced memory: {peak / 1024 / 1024:.2f} MB")

The code starts tracing before creating the list, then reports current and peak traced memory.

The values are expressed in bytes by the API, so dividing by 1024 twice converts them to MiB.

The reported numbers are not necessarily equal to the operating system's measurement of total process memory. Native extensions and other allocations may not be fully represented.

Comparing Snapshots

Sometimes, the most useful question isn't how much memory an application uses, but what changed between two points in time.

import tracemalloc


tracemalloc.start()

snapshot_before = tracemalloc.take_snapshot()

data = [
    {"id": i, "value": f"record-{i}"}
    for i in range(100_000)
]

snapshot_after = tracemalloc.take_snapshot()

differences = snapshot_after.compare_to(
    snapshot_before,
    "lineno"
)

for statistic in differences[:10]:
    print(statistic)

This compares two snapshots and displays the lines associated with the largest differences in traced memory.

The output can include information such as the number of additional allocations, their total size, and the source location.

This is particularly useful when investigating an operation that unexpectedly increases memory usage.

Measuring Memory Around a Function

You can create a small helper to measure the difference in traced memory before and after a function runs.

import tracemalloc


def measure_memory(function, *args, **kwargs):
    if not tracemalloc.is_tracing():
        tracemalloc.start()

    before, _ = tracemalloc.get_traced_memory()

    result = function(*args, **kwargs)

    after, peak = tracemalloc.get_traced_memory()

    print(f"Change in traced memory: {(after - before) / 1024:.2f} KiB")
    print(f"Peak traced memory: {peak / 1024:.2f} KiB")

    return result

Example usage:

def create_records(count):
    return [
        {"id": i, "name": f"user-{i}"}
        for i in range(count)
    ]


records = measure_memory(create_records, 50_000)

There is an important limitation here: the function's returned list remains referenced by records. The measured change can therefore reflect memory that remains live after the function returns.

Also, get_traced_memory() reports the tracing session's current and peak values. The peak is not automatically reset when this helper is called, so it may reflect an earlier operation.

For repeatable measurements, you can reset the peak with tracemalloc.reset_peak() before the operation, and compare snapshots to separate allocations more carefully.

Profiling itself also adds overhead, so avoid treating instrumented measurements as identical to normal production performance.

9. Using memory_profiler to Inspect Python Functions

Another tool you may encounter is memory_profiler, which provides line-by-line memory usage information for Python code.

It is a third-party package rather than part of Python's standard library.

Install it in your virtual environment:

pip install memory-profiler

You can annotate a function using its profile decorator:

from memory_profiler import profile


@profile
def create_large_list():
    data = [
        {"id": i, "value": i * 2}
        for i in range(100_000)
    ]

    return data


if __name__ == "__main__":
    result = create_large_list()

Run the script using the tool's documented invocation for your installed version.

The output can show how memory usage changes across lines of the function.

This is useful when you want to determine whether a particular operation causes a large increase in memory.

However, memory_profiler has had periods of limited maintenance, and its environment and dependencies may affect compatibility. Check its current documentation before adopting it in a new project.

For many modern Python applications, starting with tracemalloc and an operating-system-level memory monitor is a practical approach.

10. Understanding RSS and Why RAM Doesn't Always Decrease

One of the most confusing things about Python memory management is this:

You delete a large object, but the application's reported memory usage doesn't decrease.

Why?

Because there is a difference between an object becoming reclaimable, Python's allocator reusing the associated memory, and the operating system receiving that memory back.

Consider this example:

import gc


data = [bytearray(1024) for _ in range(500_000)]

del data

gc.collect()

After data is deleted, its list and the objects it references can be reclaimed if no other references exist.

But the process's resident set size, or RSS, may not fall by the same amount.

RSS is the amount of physical memory currently resident for a process, as reported by the operating system.

Several factors can explain why RSS stays high:

  • Python's allocator may retain memory for future allocations.

  • The underlying allocator may keep memory arenas instead of returning them immediately.

  • Other live Python objects may still occupy memory.

  • Native libraries may retain their own allocations.

  • The process may have a different memory profile after initialization or a workload spike.

Retained memory isn't automatically a leak.

A leak-like problem is more likely when memory usage continues growing during repeated, equivalent workloads and doesn't stabilize.

Measuring Process Memory

On many Unix-like systems, process memory can be inspected with operating-system tools. On Linux, for example, you can use:

ps -o pid,rss,vsz,comm -p <PID>

Replace <PID> with the process ID.

The rss field is generally reported in kilobytes, while vsz represents virtual memory size.

On macOS, the available tools and reported units differ, so consult the local ps documentation or use an appropriate process-monitoring tool.

Remember that RSS and tracemalloc measure different things. Comparing both can help distinguish Python-traced allocations from broader process memory behavior.

11. A Practical Example: Investigating Memory Growth in an API

Let's imagine a Python service that processes customer events.

Initially, the service works well. After several hours, its memory usage keeps increasing.

Here's a simplified version of a problematic implementation:

event_history = []


def process_event(event):
    normalized_event = {
        "id": event["id"],
        "type": event["type"],
        "payload": event["payload"]
    }

    event_history.append(normalized_event)

    return {"success": True}

Every event is added to event_history.

If the service processes millions of events, the list continues growing.

The issue isn't necessarily garbage collection. The objects are still reachable through event_history, so Python is correctly keeping them alive.

Step 1: Reproduce the Workload

Create a repeatable workload that processes a known number of events.

def run_workload(count):
    for i in range(count):
        process_event({
            "id": i,
            "type": "user_activity",
            "payload": {
                "action": "view",
                "page": "/dashboard"
            }
        })

Run the workload multiple times while monitoring memory.

If each run adds more retained events, memory usage is likely to increase.

Step 2: Measure Allocations

Use tracemalloc snapshots before and after each workload.

import tracemalloc

tracemalloc.start()

before = tracemalloc.take_snapshot()

run_workload(10_000)

after = tracemalloc.take_snapshot()

for item in after.compare_to(before, "lineno")[:10]:
    print(item)

This can help identify which lines account for the increase in traced memory.

Step 3: Fix the Retention Problem

If the application only needs recent events, use a bounded collection:

from collections import deque

event_history = deque(maxlen=10_000)


def process_event(event):
    normalized_event = {
        "id": event["id"],
        "type": event["type"],
        "payload": event["payload"]
    }

    event_history.append(normalized_event)

    return {"success": True}

This limits the number of retained event references to 10,000.

If the service needs a complete audit trail, don't simply discard old events. Store them in an appropriate persistent system and keep only the data required for fast access in memory.

Step 4: Verify the Fix

Run the same workload several times.

Check whether:

  • The collection remains within its configured limit.

  • Traced memory stabilizes after repeated runs.

  • RSS remains within acceptable operating limits.

  • The application still meets its response-time requirements.

  • No important event history is lost.

The important lesson is that profiling helps locate the problem, but the solution usually involves changing how the application retains or processes data.

12. Best Practices for Reducing Memory Usage

You don't need to optimize every Python object manually. Most applications benefit more from a few sensible design decisions.

Prefer Generators for Streaming Workloads

When you don't need all results simultaneously, process them incrementally.

def get_numbers(limit):
    for number in range(limit):
        yield number

Generators are useful for file processing, ETL jobs, data pipelines, and large database exports.

They can reduce memory consumption when downstream code also processes values incrementally.

Use Appropriate Data Structures

A list is convenient, but it isn't always the best option.

Depending on the task, consider:

  • A set for efficient membership checks.

  • A dictionary for keyed lookups.

  • A deque for efficient operations at both ends.

  • Generators for incremental processing.

  • Arrays or specialized numerical libraries for large homogeneous numeric datasets.

The goal is to choose a structure based on the operations you actually need.

Avoid Unbounded Caches

Caches should have a clear lifecycle.

Decide how much data can be retained, when it expires, and what should happen when the cache reaches its limit.

For a simple function cache, Python's functools module provides lru_cache:

from functools import lru_cache


@lru_cache(maxsize=1024)
def calculate_score(user_id):
    return expensive_calculation(user_id)

This limits the cache to 1,024 entries.

It doesn't guarantee a fixed memory limit because each cached key and result can have a different size. For large values, use a caching strategy that considers memory cost as well as entry count.

Release References When They Are No Longer Needed

If a long-running function creates a large object that is no longer required, make sure your application doesn't accidentally retain it.

large_result = generate_large_result()

save_result(large_result)

del large_result

Deleting the variable can make the object eligible for reclamation if no other references exist.

However, adding del statements everywhere isn't a substitute for sound memory design. Python already releases local references as functions return. Focus on genuine retention problems rather than trying to manually manage every variable.

Be Careful With Global Variables

Global lists, dictionaries, caches, and registries can retain objects for the lifetime of a process.

They're not inherently bad, but their lifecycle should be intentional.

If a global collection grows with every request, ask whether it really needs to retain all those objects.

Use Context Managers for External Resources

Files, sockets, and database connections need appropriate cleanup.

with open("report.txt", "w", encoding="utf-8") as file:
    file.write("Processing completed")

The context manager ensures the file is closed when the block finishes.

For database connections, sessions, and network resources, use the cleanup mechanism provided by the relevant library.

This is primarily resource management rather than ordinary Python heap-memory management, but it is equally important for reliable applications.

Profile Before Optimizing

A complicated optimization may save very little memory while making the code harder to maintain.

Measure first, make one meaningful change, and measure again under the same workload.

This is much more reliable than optimizing based on assumptions.

13. Should You Disable Python's Garbage Collector?

Python allows you to disable automatic cyclic garbage collection:

import gc

gc.disable()

You can re-enable it:

gc.enable()

But should you do this in production?

Usually, no.

Disabling cyclic collection doesn't disable reference counting in CPython. Objects whose reference counts reach zero can still be deallocated, but unreachable reference cycles may accumulate until collection is enabled and a suitable collection occurs.

There are specialized workloads where temporarily changing garbage-collection behavior may be useful, but such changes should be based on profiling and careful testing.

If you suspect garbage collection is affecting performance, first measure collection statistics and application latency. Check whether collections actually correlate with the problem.

Don't disable garbage collection simply because memory usage is high. If the underlying issue is a growing global list or an unbounded cache, disabling collection won't fix it.

14. Python Memory Management in AI and Data Applications

Memory management becomes particularly important when working with machine learning, document processing, and AI applications.

For example, a local retrieval-augmented generation (RAG) pipeline may load PDFs, split them into chunks, generate embeddings, and store those embeddings in a vector database.

If the pipeline loads every document into memory and creates all chunks at once, memory consumption can grow quickly.

A more efficient design might:

  1. Load documents in manageable batches.

  2. Avoid retaining both raw files and unnecessary intermediate copies.

  3. Generate embeddings in batches when supported.

  4. Persist processed chunks rather than keeping every intermediate object in memory.

  5. Monitor the memory used by the Python process and any external model or database processes.

  6. Reuse model instances where appropriate instead of repeatedly loading large models.

There's an important distinction here: Python's garbage collector manages Python objects, but it doesn't automatically control all memory allocated by native machine-learning libraries, GPU runtimes, vector databases, or separate processes.

For example, a local language model served by another process may consume substantial RAM even when the Python application itself uses relatively little.

In these situations, combine Python-level profiling with process-level monitoring and the diagnostics provided by the relevant libraries.

This is especially useful when building AI APIs that process documents, generate embeddings, or serve multiple requests concurrently.

15. Choosing the Right Memory Profiling Tool

Different tools are useful for different problems.

Tool

Best Use Case

Included With Python?

Important Limitation

tracemalloc

Finding Python allocation sites and comparing snapshots

Yes

Doesn't represent every native allocation or total process memory

gc

Inspecting cyclic garbage collection and unreachable objects

Yes

Doesn't explain all memory retention

sys.getsizeof()

Measuring the shallow size of an individual object

Yes

Doesn't include the full size of referenced objects

memory_profiler

Examining memory changes line by line

No

Compatibility and maintenance should be checked

Operating-system process tools

Monitoring RSS and overall process memory

Depends on the operating system

Doesn't directly identify the Python line responsible

Application monitoring

Tracking memory trends in long-running services

Usually requires additional tooling

Requires appropriate instrumentation and interpretation

A Note About sys.getsizeof()

You may come across code like this:

import sys

numbers = [1, 2, 3, 4, 5]

print(sys.getsizeof(numbers))

This returns the shallow size of the list object.

It does not recursively measure the full memory occupied by every object referenced by the list.

For a rough comparison of container sizes, it can be useful. For estimating the total memory cost of a complex nested data structure, it isn't sufficient by itself.

Use tracemalloc, a suitable deep-size measurement tool, or a combination of profiling techniques when you need a more complete picture.

16. A Practical Workflow for Debugging Memory Problems

When a Python application starts consuming too much memory, follow a structured process instead of immediately changing garbage-collection settings.

Step 1: Establish a baseline.

Measure memory after startup and after the application has warmed up. Record the workload, process RSS, and relevant application metrics.

Step 2: Reproduce the issue.

Run a repeatable workload. For example, process 10,000 records or execute a fixed number of API requests.

Step 3: Compare memory over time.

Determine whether memory grows continuously, increases and then stabilizes, or spikes only during a particular operation.

Step 4: Inspect Python allocations.

Use tracemalloc snapshots to identify where traced memory increases.

Step 5: Investigate retained references.

Check global collections, caches, queues, event handlers, closures, and objects stored in long-lived service instances.

Step 6: Inspect native and external memory.

If RSS grows while Python-traced allocations remain relatively stable, investigate native extensions, model runtimes, database clients, and other processes.

Step 7: Make one targeted change.

For example, introduce batching, limit a cache, stream file processing, or remove an unnecessary retained collection.

Step 8: Repeat the same test.

Compare memory usage and performance before and after the change.

This workflow helps distinguish actual memory leaks from normal allocator behavior and temporary memory spikes.

Conclusion

Python makes memory management easier by handling object allocation, reference counting, and garbage collection automatically. But automatic management doesn't mean developers can ignore memory usage.

Reference counting allows CPython to reclaim many objects when their reference counts reach zero. The cyclic garbage collector complements it by identifying unreachable reference cycles that reference counting alone cannot reclaim.

When an application consumes too much memory, the cause may be something as simple as an unbounded list, an oversized cache, or loading an entire dataset into memory. In other cases, the problem may involve native allocations or memory retained by external libraries.

Tools such as tracemalloc, the gc module, and operating-system process monitors help you investigate these problems with real measurements.

The most important habit is to measure memory usage before trying to optimize it.

Start with a repeatable workload, identify where memory is increasing, make a targeted change, and test the result. With this approach, you can build Python applications that remain efficient and reliable as their workloads grow.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘