Check Session and Server Memory from ysqlsh

When troubleshooting query behavior, connection sizing, or general node health, it can be useful to answer a few simple questions:

  • ● How much memory is my current YSQL session using?
  • ● How much memory does the server have?
  • ● How much memory is still available?
  • ● Is swap configured?

In standard PostgreSQL-compatible SQL, there is no single built-in query that returns all of this information. Session-level memory is visible from inside the database, but server-level memory belongs to the operating system.

Fortunately, from ysqlsh, you can combine both approaches.

🧠 Key Insight

YugabyteDB exposes memory used by your current YSQL session through PostgreSQL-compatible views, but host-level memory such as total RAM, available RAM, and swap are operating-system metrics. From ysqlsh, you can quickly inspect both without leaving the database prompt.

Check Memory Used by the Current YSQL Session

YugabyteDB supports the PostgreSQL-compatible pg_backend_memory_contexts view. This view shows memory allocated by the backend process for your current session.

Run:

				
					SELECT
    pg_size_pretty(sum(total_bytes)) AS session_total_allocated,
    pg_size_pretty(sum(used_bytes))  AS session_used_memory,
    pg_size_pretty(sum(free_bytes))  AS session_free_memory
FROM
    pg_backend_memory_contexts;
				
			

Example output:

				
					.session_total_allocated | session_used_memory | session_free_memory
-------------------------+---------------------+---------------------
 2545 kB                 | 2166 kB             | 379 kB
(1 row)
				
			

This tells us that the current YSQL session has allocated about 2.5 MB, with about 2.1 MB currently used.

📌 Note

This query only reports memory for your current backend session. It does not show total memory used by the entire YugabyteDB node, other sessions, DocDB, or the Linux operating system.

📌 Version Note

pg_backend_memory_contexts was introduced upstream in PostgreSQL 14 and imported into YugabyteDB’s YSQL layer around the YugabyteDB 2.14 release line. Although ysqlsh in YugabyteDB 2024.2 still reports PostgreSQL compatibility as 11.2-YB, this view is available there as a backported YSQL feature.

Inspect the Largest Memory Contexts

If you want more detail than the summary query, you can inspect the largest memory contexts in your current YSQL backend session.

				
					SELECT
    name,
    parent,
    level,
    pg_size_pretty(total_bytes) AS total,
    pg_size_pretty(used_bytes)  AS used,
    pg_size_pretty(free_bytes)  AS free
FROM
    pg_backend_memory_contexts
ORDER BY
    total_bytes DESC
LIMIT 10;
				
			

Example output:

				
					.         name           |      parent      | level |  total  |   used    |    free
-------------------------+------------------+-------+---------+-----------+------------
 TopMemoryContext        |                  |     0 | 1179 kB | 1147 kB   | 32 kB
 CacheMemoryContext      | TopMemoryContext |     1 | 512 kB  | 480 kB    | 32 kB
 MessageContext          | TopMemoryContext |     1 | 128 kB  | 101 kB    | 27 kB
 Timezones               | TopMemoryContext |     1 | 102 kB  | 99 kB     | 2608 bytes
 ExecutorState           | PortalContext    |     3 | 88 kB   | 58 kB     | 31 kB
 WAL record construction | TopMemoryContext |     1 | 49 kB   | 43 kB     | 6352 bytes
 Type information cache  | TopMemoryContext |     1 | 40 kB   | 37 kB     | 2608 bytes
 TupleSort main          | ExecutorState    |     4 | 32 kB   | 26 kB     | 6544 bytes
 TransactionAbortContext | TopMemoryContext |     1 | 32 kB   | 272 bytes | 32 kB
 Relcache by OID         | TopMemoryContext |     1 | 16 kB   | 13 kB     | 3496 bytes
(10 rows)
				
			

The full view can return many rows because PostgreSQL/YSQL organizes backend memory into a hierarchy of memory contexts. The level column shows where each context sits in that hierarchy, and the parent column shows which memory context owns it.

For most quick checks, start with the aggregate query. If the session looks larger than expected, use the top memory-context query to see where the biggest allocations are.

🧠 Practical Tip

Avoid showing the full SELECT * FROM pg_backend_memory_contexts output in normal troubleshooting notes. It can return many rows and be difficult to read. Sorting by total_bytes or used_bytes and limiting the result usually gives a much clearer picture of where session memory is going.

YugabyteDB-Specific Memory Helpers

In addition to PostgreSQL-compatible views like pg_backend_memory_contexts, YugabyteDB also provides built-in memory helper functions that can be useful when inspecting the current session.

For example:

				
					SELECT yb_mem_usage_kb();
				
			

Example output:

				
					.yb_mem_usage_kb
-----------------
           47556
(1 row)
				
			

And:

				
					SELECT yb_mem_usage_sql_kb();
				
			

Example output:

				
					 yb_mem_usage_sql_kb
---------------------
                1941
(1 row)
				
			

These functions give you a compact YugabyteDB-specific view of memory usage for the current session.

🧠 Key Insight

pg_backend_memory_contexts is useful when you want a PostgreSQL-style breakdown of memory contexts. The YugabyteDB-specific functions yb_mem_usage_kb() and yb_mem_usage_sql_kb() are useful when you want a quick current-session memory number from YugabyteDB itself.

A simple way to compare them is:

Tool What It Shows
pg_backend_memory_contexts PostgreSQL/YSQL memory context details for the current backend session. In YugabyteDB, this may also include YugabyteDB-specific memory context rows such as PGGate and TCMalloc-related memory.
yb_mem_usage_kb() Current session memory usage in the proxy server, reported in KB.
yb_mem_usage_sql_kb() Current session SQL-layer memory usage, reported in KB.
pg_backend_pid() plus ps Operating system view of the current backend process memory, including RSS and VSZ.
\! free -h Overall Linux server memory, including total, used, free, cache, available memory, and swap.

Compare with the Operating System View

pg_backend_memory_contexts shows the PostgreSQL/YSQL memory-context breakdown for the current backend session. Sometimes you may also want to compare that with what Linux sees for the same backend process.

First, get the backend process ID:

				
					SELECT pg_backend_pid();
				
			

Example:

				
					 pg_backend_pid
----------------
        1354147
(1 row)
				
			

Then, from inside ysqlsh, use the \! meta-command to run ps against that process ID:

				
					\! ps -o pid,user,rss,vsz,comm,args -p 1354147
				
			

Example output:

				
					.   PID USER       RSS    VSZ COMMAND         COMMAND
1354147 root     49868 70684384 postgres      postgres: yugabyte yugabyte 127.0.0.1(56912) idle
				
			

In this example, the current YSQL backend process is using about 49 MB of resident memory, based on the RSS value.

The RSS value is reported in kilobytes:

				
					49868 KB ≈ 49 MB
				
			

Understanding the columns:

Column Meaning
PID The operating system process ID for the current YSQL backend.
USER The operating system user running the backend process.
RSS Resident Set Size. This is the amount of physical memory currently used by the process, shown in KB.
VSZ Virtual memory size. This includes memory the process has mapped, but not necessarily physically used.
COMMAND The process command and session state.

The important distinction is that this method shows the operating system’s view of process memory, not PostgreSQL’s internal memory-context breakdown.

For example, RSS tells you how much physical memory the backend process is currently using, but it does not break that memory down by PostgreSQL memory context, such as parser, planner, executor, cache, or other internal allocations.

Check Server Memory Without Leaving ysqlsh

To check host-level memory, use the \! meta-command from ysqlsh..

The \! command lets you run an operating system command from inside the SQL shell.

For example:

				
					\! free -h
				
			

Example output:

				
					.              total        used        free      shared  buff/cache   available
Mem:            11Gi       9.1Gi       470Mi       665Mi       2.8Gi       2.3Gi
Swap:             0B          0B          0B
				
			

This is a fast way to see the memory profile of the server hosting the ysqlsh session.

Understanding the Important Columns

The free -h output includes several useful columns:

Column Meaning
total Total physical memory on the server.
used Memory currently used by applications, processes, and the OS.
free Completely unused memory. This number is often low on healthy Linux systems.
buff/cache Memory used by Linux for buffers and filesystem cache.
available The best estimate of memory available for new processes without swapping.
Swap Configured swap space, if any.

The key number to watch is usually available, not free.

Linux aggressively uses unused RAM for caching. That can make free memory look low even when the server is healthy. The available column gives a better estimate of how much memory can be used by new processes or workload growth.

In the example above:

				
					total:     11Gi
used:      9.1Gi
free:      470Mi
available: 2.3Gi
swap:      0B
				
			

Even though only 470Mi is completely free, the server still has about 2.3Gi available.

Use /proc/meminfo for More Detail

The free command is essentially a human-friendly summary of Linux memory information. If you want the raw details, you can inspect /proc/meminfo directly:

				
					\! cat /proc/meminfo
				
			

Example excerpt:

				
					MemTotal:       11949284 kB
MemFree:          485956 kB
MemAvailable:    2410608 kB
Cached:          2772348 kB
SwapTotal:             0 kB
SwapFree:              0 kB
				
			

This maps directly to the free -h output.

For example:

				
					MemTotal:     11949284 kB  -> about 11 GiB total
MemAvailable: 2410608 kB   -> about 2.3 GiB available
SwapTotal:          0 kB   -> no swap configured
				
			

Why This Is Useful for YugabyteDB

YugabyteDB nodes run multiple processes, including YSQL, DocDB, masters, tservers, and supporting system processes. When diagnosing performance or sizing issues, it helps to separate two different questions:

  • ● How much memory is my current YSQL session using?
  • ● How much memory is available on the node?

The SQL query answers the first question:

				
					SELECT
    pg_size_pretty(sum(total_bytes)) AS session_total_allocated,
    pg_size_pretty(sum(used_bytes))  AS session_used_memory,
    pg_size_pretty(sum(free_bytes))  AS session_free_memory
FROM
    pg_backend_memory_contexts;
				
			

The shell command answers the second:

				
					\! free -h
				
			

Together, they give you a quick view of both session-level and server-level memory.

A Note About Swap

In the example output, swap is disabled:

				
					Swap: 0B 0B 0B
				
			

For database nodes, avoiding swap is often preferred because swapping database memory to disk can introduce severe latency. However, no swap also means there is no safety net if the server runs out of memory.

If memory is exhausted, the Linux Out-of-Memory killer may terminate processes to protect the operating system.

⚠️ Caution

A server with no swap can be good for predictable database latency, but it also means memory pressure must be monitored carefully. If the node runs out of memory, processes may be killed abruptly.

Quick Reference

Goal Command
Check current YSQL session memory summary SELECT pg_size_pretty(sum(total_bytes)) FROM pg_backend_memory_contexts;
Inspect largest session memory contexts SELECT ... FROM pg_backend_memory_contexts ORDER BY total_bytes DESC LIMIT 10;
Check YugabyteDB session memory usage SELECT yb_mem_usage_kb();
Check YugabyteDB SQL-layer session memory usage SELECT yb_mem_usage_sql_kb();
Find the current backend process ID SELECT pg_backend_pid();
Check current backend process memory from Linux \! ps -o pid,user,rss,vsz,comm,args -p <pid>
Check host memory summary \! free -h
Check detailed Linux memory information \! cat /proc/meminfo
Check running YugabyteDB processes \! top -c -u yugabyte
🔗 Related YugabyteDB Tips

This tip focuses on checking memory from the current ysqlsh session and comparing that with the Linux host view. For broader node-level memory troubleshooting, these related tips are useful follow-ups:

Measure Total Postgres Backend Usage: Shows how to estimate total PostgreSQL/YSQL backend memory usage on a node using PSS, which helps avoid over-counting shared memory.

Use VmHWM to Catch Memory-Heavy YSQL Backends and Help Prevent OOMs: Shows how to identify backend processes that have reached high peak memory usage, even if their current memory usage has dropped.

Final Takeaway

YugabyteDB gives you PostgreSQL-compatible visibility into your current YSQL session’s memory through pg_backend_memory_contexts.

For host-level memory, use operating system tools. From inside ysqlsh, the \! meta-command makes this easy:

				
					\! free -h
				
			

Use the SQL view to inspect session memory. Use Linux tools to inspect server memory. Together, they provide a simple and practical first step when troubleshooting memory usage on a YugabyteDB node.

Have Fun!

VIP seating at the sunflower seed buffet! The ground crew is just down there waiting for the messy eaters up top to drop some crumbs.