Predictive PGA and Temp Tablespace Exhaustion: Real-Time Telemetry and Automated Remediation
Reacting to memory and temporary-tablespace exhaustion alerts fails in consolidated Oracle fleets because storage queues saturate and ORA-04036 or ORA-01652 fires long before five-minute monitoring pollers ever notice the spike.
TL;DR
- Problem: Runaway hash joins and Cartesian sorts exhaust
TEMPand PGA between 5-minuteDBA_*polling intervals, stalling OLTPlog file syncI/O and riskingORA-04036or Linux OOM kills.- Answer: Sample
V$SQL_WORKAREA_ACTIVE,V$SESSION, andV$PROCESSevery second from a local sidecar, compute allocation velocity and Time-To-Exhaustion, and neutralize culprits withALTER SYSTEM CANCEL SQL.- Watch out:
PGA_AGGREGATE_LIMIT = 0disables instance-level protection,DBMS_SQLQSQL Quarantine requires Exadata (EE-ES) licensing, and automated kills require aBATCH_EXEMPTallowlist plus stale-sample rejection.
Situation
In multi-tenant Oracle Database 19c environments, Pluggable Databases (PDBs) share host RAM and storage bandwidth across independent application workloads. Oracle manages private session memory through the Program Global Area (PGA) and spills overflowing sort or hash workareas to disk in the Temporary Tablespace (TEMP).
When the optimizer chooses a hash join, the server process first reads the smaller row source (the build input) to construct an in-memory hash table inside its PGA workarea, then streams the larger row source (the probe input) to match join keys. If stale statistics or join-key skew cause the build input to exceed the workarea budget, the engine partitions the hash table and writes overflowing buckets directly to TEMP tempfiles via direct path write temp—bypassing the SGA buffer cache—and reads them back during the probe phase via direct path read temp.
Depending on how much PGA the workarea receives relative to the input size, execution falls into one of three regimes:
| Execution Regime | Memory Fit | Temp Disk I/O | Operational Effect |
|---|---|---|---|
| Optimal | Entire hash table or sort fits in PGA workarea. | Zero TEMP writes. | Executes at memory bandwidth. |
| One-Pass | Exceeds workarea; partitions spill once via direct path write temp. | Proportional to spill volume (direct path read temp on probe). | Predictable I/O overhead if storage has headroom. |
| Multi-Pass | Severe PGA deficit forces repeated spill and re-partition cycles. | Heavy read/write amplification in TEMP. | Saturates shared storage queues and starves OLTP. |
To bound private memory, Oracle provides PGA_AGGREGATE_TARGET (a soft sizing target that enables WORKAREA_SIZE_POLICY = AUTO) and PGA_AGGREGATE_LIMIT (a hard instance ceiling introduced in Oracle 12c).
The Problem
Even with automatic workarea management enabled, runaway queries—such as missing join predicates, skewed parallel hash joins, or unbounded PL/SQL collections—can destabilize a consolidated host along three operational constraints.
First, storage queue saturation before ORA-01652. A multi-pass hash join spilling gigabytes through direct path write temp and direct path read temp floods shared storage controllers well before TEMP reaches zero free extents and raises ORA-01652: unable to extend temp segment. Latency-sensitive OLTP waits (db file sequential read and log file sync) degrade across every PDB sharing the array.
Second, PGA_AGGREGATE_LIMIT boundaries and OS OOM risk. PGA_AGGREGATE_TARGET is only a soft advisory target: Oracle’s workarea manager can shrink tunable sort and hash buffers, but it cannot shrink untunable PGA such as PL/SQL associative arrays, open cursor state, or client LOB buffers. When MEMORY_TARGET is unset, Oracle 19c defaults PGA_AGGREGATE_LIMIT to the greatest of 2 GB, 200% of PGA_AGGREGATE_TARGET, or 3 MB times PROCESSES (5 MB times PROCESSES on RAC). Crossing that ceiling triggers ORA-04036: PGA memory used by the instance exceeds PGA_AGGREGATE_LIMIT, forcing Oracle to abort calls or terminate the highest untunable PGA consumers. Conversely, administrators who set PGA_AGGREGATE_LIMIT = 0 to silence ORA-04036 remove the safety valve entirely: untunable PL/SQL heaps or concurrent workareas can exhaust host RAM (ORA-04030: out of process memory) and trigger the Linux OOM killer against critical background processes such as PMON or LGWR.
Third, velocity mismatch against periodic polling. Traditional monitoring agents query dictionary views like DBA_TABLESPACE_USAGE_METRICS or V$PGASTAT on 5-minute intervals. A runaway join can consume available TEMP or trip PGA_AGGREGATE_LIMIT between two consecutive polls, leaving operators with post-mortem logs rather than early containment. Even V$TEMPSEG_USAGE only gives a point-in-time snapshot unless sampled continuously to compute allocation rate.
How do platform teams detect explosive PGA and TEMP allocation trajectories in real time and cancel offending SQL statements before shared storage or instance memory collapses?
Options Considered
Platform teams typically evaluate four containment strategies before combining high-frequency telemetry with native Oracle SQL cancellation.
| Option | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|
| 5-minute OEM / cron polling | Low overhead; built into standard monitoring packs. | Blind to sub-minute TEMP spikes and rapid PGA allocation slopes. | Rejected |
Setting PGA_AGGREGATE_LIMIT = 0 | Prevents ORA-04036 on legitimate large analytical jobs. | Exposes the host to OS OOM kills of Oracle background processes. | Rejected |
| Oracle Resource Manager alone | Enforces native CPU shares, MAX_EST_EXEC_TIME, and session temp pool caps. | Static thresholds do not measure cross-session TEMP growth velocity or Time-To-Exhaustion. | Partial (pair) |
1s V$ velocity stream + ALTER SYSTEM CANCEL SQL | Tracks dTemp/dt and dPGA/dt per session; cancels only the offending sql_id. | Requires a local sidecar, allowlisting for batch jobs, and stale-event guards. | Chosen |
Disabling PGA_AGGREGATE_LIMIT trades predictable ORA-04036 errors for unpredictable host-level OOM crashes. Oracle Resource Manager (DBMS_RESOURCE_MANAGER) remains valuable as a defensive baseline—directives like MAX_EST_EXEC_TIME, SWITCH_TIME, and SWITCH_FOR_CALL can demote long-running queries to a lower-priority consumer group, and MAX_UTILIZATION_LIMIT caps CPU share—but Resource Manager directives do not compute aggregate TEMP allocation velocity or project Time-To-Exhaustion across concurrent sessions. Pairing explicit PGA_AGGREGATE_LIMIT and Resource Manager bounds with a 1-second V$SQL_WORKAREA_ACTIVE velocity detector gives teams early surgical cancellation before TEMP or RAM runs dry.
The Streaming Workarea Telemetry Architecture
Instead of running heavy DBA_* dictionary queries over remote connections, a lightweight local sidecar samples in-memory dynamic performance views (V$SQL_WORKAREA_ACTIVE, V$SESSION, and V$PROCESS) every second, streams deltas to a velocity evaluator, and dispatches surgical cancellations back to a local remediation handler.
Pipeline Mechanics
- Non-Blocking In-Memory Scrape: The sidecar queries
V$SQL_WORKAREA_ACTIVEjoined toV$SESSIONandV$PROCESS. BecauseV$SQL_WORKAREA_ACTIVEonly holds rows for currently executing workareas—rows disappear as soon as a sort or hash join finishes—joiningV$SESSION(sql_id,module,serial#) andV$PROCESS(pga_alloc_mem) in a single pass captures both tunable workarea spills and total process PGA. Filtering to sessions above a baseline floor (for example,actual_mem_used > 50 MBortempseg_size > 100 MB) keeps result sets small and avoids scanning idle connections. Using adaptive polling—5 seconds whenTEMPusage is calm, dropping to 1 second whenTEMPexceeds 60%—prevents unnecessary library-cache latch pressure. - Velocity, Time-To-Exhaustion (TTE), and State Eviction: Rather than alerting only on static fill percentages, the stream processor computes the rate of change per
(sid, serial#)and evicts stale entries fromfleetRegistryonce a session closes so the sidecar’s own Go heap stays bounded:
$$\text{Velocity} = \frac{\Delta \text{TempAllocated}}{\Delta t} \quad \left[\frac{\text{MB}}{\text{sec}}\right], \qquad \text{TTE} = \frac{\text{Capacity}{\text{remaining}}}{\sum \text{Velocity}{\text{active}}}$$
- Surgical Cancellation (
ALTER SYSTEM CANCEL SQL): Introduced in Oracle 18c and standard in 19c,ALTER SYSTEM CANCEL SQLaborts only the offendingsql_idinside a session while keeping the client connection alive (returningORA-01013: user requested cancel of current operationto the caller). Before issuing a cancel, the evaluator checks the session’smoduleandsql_idagainst aBATCH_EXEMPTallowlist so legitimate nightly ETL or month-end close jobs are never interrupted. Only if a non-exempt session ignores cancellation and continues holding memory past a short grace window does the handler escalate toALTER SYSTEM DISCONNECT SESSION ... IMMEDIATE.
1. High-Frequency Workarea Collector Query
SELECT /*+ LEADING(wa) USE_HASH(s) */
s.sid,
s.serial#,
s.username,
s.module,
s.sql_id,
ROUND(wa.actual_mem_used / 1024 / 1024, 2) AS mem_used_mb,
ROUND(wa.tempseg_size / 1024 / 1024, 2) AS temp_spill_mb,
wa.number_passes,
ROUND(p.pga_alloc_mem / 1024 / 1024, 2) AS pga_alloc_mb
FROM v$sql_workarea_active wa
JOIN v$session s ON wa.sid = s.sid
JOIN v$process p ON s.paddr = p.addr
WHERE wa.actual_mem_used > 52428800
OR wa.tempseg_size > 104857600;
2. Stream-Processing Velocity Evaluator (Go)
The evaluator tracks the previous sample per sid-serial#, discards out-of-order or stale ticks, and flags sessions whose TEMP TTE drops below 30 seconds or whose PGA allocation rate crosses the configured slope ceiling.
func EvaluateTelemetryTick(cur SessionTelemetry, freeTempMb float64) AnomalyDecision {
key := fmt.Sprintf("%d-%d", cur.Sid, cur.SerialNum)
prev, exists := fleetRegistry[key]
fleetRegistry[key] = &SessionTracker{lastSample: cur}
if !exists {
return AnomalyDecision{}
}
dt := cur.SampleTime.Sub(prev.lastSample.SampleTime).Seconds()
if dt <= 0 || time.Since(cur.SampleTime) > 5*time.Second {
return AnomalyDecision{} // Ignore stale or out-of-order samples
}
tempVel := (cur.TempSpillMb - prev.lastSample.TempSpillMb) / dt
pgaVel := (cur.PgaAllocMb - prev.lastSample.PgaAllocMb) / dt
if tempVel > 350.0 && cur.TempSpillMb > 10240.0 && (freeTempMb/tempVel) < 30.0 {
return AnomalyDecision{ShouldRemediate: true, Sid: cur.Sid, SerialNum: cur.SerialNum, SqlId: cur.SqlId}
}
if pgaVel > 150.0 && cur.PgaAllocMb > 4096.0 {
return AnomalyDecision{ShouldRemediate: true, Sid: cur.Sid, SerialNum: cur.SerialNum, SqlId: cur.SqlId}
}
return AnomalyDecision{}
}
3. Native Cancellation and Plan Prevention
Do not use undocumented internal DBMS_SYSTEM event workarounds (event 10237) in Oracle 19c; use the documented ALTER SYSTEM CANCEL SQL statement, which targets the exact sid,serial#,sql_id tuple and cleans up automatically.
-- 1. Surgical SQL cancellation (Oracle 18c/19c+); returns ORA-01013 to caller
ALTER SYSTEM CANCEL SQL '412,58912,a98b42cd71efg';
-- 2. Escalation only if session remains active after grace window
ALTER SYSTEM DISCONNECT SESSION '412,58912' IMMEDIATE;
To stop an application from immediately re-submitting the same bad plan, bind a fixed execution plan with SQL Plan Management (DBMS_SPM) or a SQL Patch on standard Enterprise Edition. Note that DBMS_SQLQ.CREATE_QUARANTINE_BY_SQL_ID (SQL Quarantine) is licensed strictly for Engineered Systems (Exadata, Exadata Cloud Service, and Autonomous Database)—never enable _exadata_feature_on on non-Exadata hosts to use DBMS_SQLQ.
How It Rolls Out
Automated session termination should never go live on day one without baseline calibration. Roll out the pipeline in four gated stages.
- Stage 1 — Harden Instance Bounds and Per-PDB
TEMP: VerifyPGA_AGGREGATE_LIMITis explicitly set (not0) and checkV$PGASTAT(over allocation count,total PGA allocated, andmaximum PGA allocated) to confirm normal workloads fit cleanly below the ceiling. Confirm every PDB uses its own local temporary tablespace (ALTER DATABASE DEFAULT TEMPORARY TABLESPACEinside each PDB) withEXTENT MANAGEMENT LOCAL UNIFORM SIZEso one tenant cannot exhaustTEMPfor unrelated PDBs and extent deallocation stays predictable. - Stage 2 — Deploy Sidecar in Observe-Only Mode: Run the
V$SQL_WORKAREA_ACTIVEcollector and Go velocity evaluator withdry_run=true. Capture legitimate ETL and month-end jobs to populate theBATCH_EXEMPTmodule/sql_idallowlist, and tunetempVelandpgaVelthresholds against real baseline slopes. - Stage 3 — Enable Soft Cancellation (
ALTER SYSTEM CANCEL SQL): Flipdry_run=falseforALTER SYSTEM CANCEL SQLonly, keepingDISCONNECT SESSIONdisabled. Validate in staging with a synthetic Cartesian join thatORA-01013aborts the runaway cursor while leaving the session intact, then monitor productionORA-01013counts for zero false positives on allowlisted batch workloads. Rollback is settingdry_run=true. - Stage 4 — Enable Escalation and Plan Controls: Enable the
DISCONNECT SESSION IMMEDIATEfallback for sessions that ignoreCANCEL SQL, and wire repeatedsql_idoffenders into SQL Plan Baselines (orDBMS_SQLQon Exadata) so client retry loops do not immediately re-trigger the same spill.
In Practice
This architecture aligns directly with documented Oracle Database 19c memory and workarea behavior:
- Explicit
PGA_AGGREGATE_LIMITprotection: Because Oracle 19c defaultsPGA_AGGREGATE_LIMITto the maximum of2 GB,200%ofPGA_AGGREGATE_TARGET, or3 MB * PROCESSES(5 MB * PROCESSESon RAC), leaving the limit active ensuresORA-04036aborts runaway sessions before host RAM exhaustion triggers the Linux OOM killer. SettingPGA_AGGREGATE_LIMITexplicitly inspfilealso prevents unexpected ceiling shifts if a DBA increasesPROCESSESwithout reviewing host memory headroom. - Workarea vs untunable PGA visibility:
V$SQL_WORKAREA_ACTIVEcaptures tunable SQL workareas (sorts, hash joins, bitmap merges), whileV$PROCESS.PGA_ALLOC_MEMandV$PROCESS_MEMORYexpose total process PGA including untunable PL/SQL associative arrays and Java heaps. Querying both together catches both hash-joinTEMPspills and PL/SQL memory leaks. - Temporary extent cleanup and
V$TEMPSEG_USAGE: When a large sort or hash join is cancelled viaALTER SYSTEM CANCEL SQL, the session’s temporary segments are marked for cleanup, andSMONdeallocates the extents back to the tablespace. UsingEXTENT MANAGEMENT LOCAL UNIFORM SIZE(for example,64Mor128Mfor analytical PDBs) avoids the dictionary-extent fragmentation that slows downSMONcleanup after a multi-gigabyte spill. - Native 18c/19c
CANCEL SQLsemantics:ALTER SYSTEM CANCEL SQL 'sid,serial#,sql_id'interrupts only the active cursor without tearing down connection-pool sockets, whereasALTER SYSTEM DISCONNECT SESSIONtears down the session cleanly when a process is stuck outside an interruptible SQL fetch. Pairing cancellation logs withV$SQL_PLAN_MONITOR(where Diagnostics and Tuning Pack is licensed) lets database engineers pinpoint the exact hash join or sort step that triggered the spill.
Where It Breaks
Sub-second automated remediation introduces four operational hazards that require explicit guardrails in the collector and evaluator. Each failure mode stems from treating a live transactional database like a stateless worker without accounting for batch exemptions, client retry loops, or multi-tenant TEMP sharing.
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Legitimate batch sort hits velocity threshold | Month-end ETL job gets cancelled mid-run (ORA-01013). | Spikes in cancelled BATCH module jobs during nightly windows. | Maintain a BATCH_EXEMPT allowlist by module / sql_id and isolate batch in Resource Manager. |
App framework retries ORA-01013 immediately | Cancelled query reconnects in a tight loop, repeating the TEMP spike. | Same sql_id cancelled repeatedly within seconds. | Fix plan via DBMS_SPM / SQL Patch (or DBMS_SQLQ on Exadata) and rate-limit at API gateway. |
| Kafka lag delivers stale telemetry ticks | Evaluator triggers CANCEL SQL minutes late against a reused SID. | Event timestamp delta exceeds 5 seconds. | Drop samples older than 5 seconds and always require exact (sid, serial#, sql_id) match. |
Shared CDB$ROOT TEMP across PDBs | One runaway tenant fills shared TEMP, failing queries in all sibling PDBs. | ORA-01652 errors across multiple PDBs simultaneously. | Provision dedicated local TEMP tablespaces per PDB with UNIFORM SIZE extents. |
V$SQL_WORKAREA_ACTIVE polled too aggressively | Sub-second polling during heavy concurrency adds library-cache latch contention. | Rising collector query latency or CPU overhead on the host. | Use adaptive 5s/1s polling and filter to sessions above 50 MB PGA or 100 MB TEMP. |
| Untunable PL/SQL heap fragmentation | ORA-04030 or ORA-04036 fires even while V$SQL_WORKAREA_ACTIVE looks small. | V$PROCESS_MEMORY PL/SQL category growing rapidly. | Include V$PROCESS.PGA_ALLOC_MEM velocity in the evaluator alongside tempseg_size. |
Key Takeaways
- Never set
PGA_AGGREGATE_LIMIT = 0to silenceORA-04036; keep the hard ceiling enabled so Oracle terminates runaway sessions before the Linux OOM killer hitsPMONorLGWR. - Sample
V$SQL_WORKAREA_ACTIVEjoined toV$SESSIONandV$PROCESS(with adaptive 5s/1s polling and a minimum size filter) rather than pollingDBA_*dictionary views on 5-minute intervals. - Trigger remediation on allocation velocity (
dTemp/dt,dPGA/dt) and projected Time-To-Exhaustion rather than static fill percentages alone. - Use Oracle’s supported
ALTER SYSTEM CANCEL SQL 'sid,serial#,sql_id'(18c/19c+) instead of legacyDBMS_SYSTEMevent workarounds, and reserveDBMS_SQLQSQL Quarantine strictly for Exadata (EE-ES) environments. - Isolate multi-tenant
TEMPblast radiuses by assigning each Pluggable Database its own local temporary tablespace and protecting batch workloads with aBATCH_EXEMPTallowlist.
What to Do Next
- Problem: Runaway hash joins and PL/SQL leaks saturate
TEMPI/O and breach PGA ceilings faster than 5-minute monitoring pollers can detect. - Solution: Deploy a 1-second adaptive sidecar on
V$SQL_WORKAREA_ACTIVE,V$SESSION, andV$PROCESS, compute per-session allocation velocity and Time-To-Exhaustion, and neutralize non-exempt culprits withALTER SYSTEM CANCEL SQLbeforeTEMPor PGA limits trip. - Proof: Run the collector in
dry_run=truemode for one week against production workloads, verify zero false-positive triggers against allowlisted batch jobs, and confirm synthetic runaway spills in staging are cancelled beforeORA-01652orORA-04036occurs. - Action: Audit
PGA_AGGREGATE_LIMIT,V$PGASTATover-allocation counts, and per-PDBTEMPtablespace isolation across your 19c fleet this week before enabling automatedCANCEL SQLin non-production. Document any long-running ETL modules inBATCH_EXEMPTduring shadow mode.