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 TEMP and PGA between 5-minute DBA_* polling intervals, stalling OLTP log file sync I/O and risking ORA-04036 or Linux OOM kills.
  • Answer: Sample V$SQL_WORKAREA_ACTIVE, V$SESSION, and V$PROCESS every second from a local sidecar, compute allocation velocity and Time-To-Exhaustion, and neutralize culprits with ALTER SYSTEM CANCEL SQL.
  • Watch out: PGA_AGGREGATE_LIMIT = 0 disables instance-level protection, DBMS_SQLQ SQL Quarantine requires Exadata (EE-ES) licensing, and automated kills require a BATCH_EXEMPT allowlist plus stale-sample rejection.

Real-time workarea telemetry pipeline from V$ views to surgical SQL cancel

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 RegimeMemory FitTemp Disk I/OOperational Effect
OptimalEntire hash table or sort fits in PGA workarea.Zero TEMP writes.Executes at memory bandwidth.
One-PassExceeds 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-PassSevere 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.

Three constraints turn hash-join spills into instance outages

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.

OptionWhat It Gets RightWhere It BreaksDecision
5-minute OEM / cron pollingLow overhead; built into standard monitoring packs.Blind to sub-minute TEMP spikes and rapid PGA allocation slopes.Rejected
Setting PGA_AGGREGATE_LIMIT = 0Prevents ORA-04036 on legitimate large analytical jobs.Exposes the host to OS OOM kills of Oracle background processes.Rejected
Oracle Resource Manager aloneEnforces 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 SQLTracks 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.

Comparison of four containment options showing why 1s velocity telemetry plus native cancel is chosen

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.

Streaming workarea telemetry architecture from V$ views to surgical cancel

Pipeline Mechanics

  1. Non-Blocking In-Memory Scrape: The sidecar queries V$SQL_WORKAREA_ACTIVE joined to V$SESSION and V$PROCESS. Because V$SQL_WORKAREA_ACTIVE only holds rows for currently executing workareas—rows disappear as soon as a sort or hash join finishes—joining V$SESSION (sql_id, module, serial#) and V$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 MB or tempseg_size > 100 MB) keeps result sets small and avoids scanning idle connections. Using adaptive polling—5 seconds when TEMP usage is calm, dropping to 1 second when TEMP exceeds 60%—prevents unnecessary library-cache latch pressure.
  2. 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 from fleetRegistry once 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}}}$$

  1. Surgical Cancellation (ALTER SYSTEM CANCEL SQL): Introduced in Oracle 18c and standard in 19c, ALTER SYSTEM CANCEL SQL aborts only the offending sql_id inside a session while keeping the client connection alive (returning ORA-01013: user requested cancel of current operation to the caller). Before issuing a cancel, the evaluator checks the session’s module and sql_id against a BATCH_EXEMPT allowlist 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 to ALTER 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.

Four-stage rollout from bounds hardening to automated SQL cancellation

  1. Stage 1 — Harden Instance Bounds and Per-PDB TEMP: Verify PGA_AGGREGATE_LIMIT is explicitly set (not 0) and check V$PGASTAT (over allocation count, total PGA allocated, and maximum PGA allocated) to confirm normal workloads fit cleanly below the ceiling. Confirm every PDB uses its own local temporary tablespace (ALTER DATABASE DEFAULT TEMPORARY TABLESPACE inside each PDB) with EXTENT MANAGEMENT LOCAL UNIFORM SIZE so one tenant cannot exhaust TEMP for unrelated PDBs and extent deallocation stays predictable.
  2. Stage 2 — Deploy Sidecar in Observe-Only Mode: Run the V$SQL_WORKAREA_ACTIVE collector and Go velocity evaluator with dry_run=true. Capture legitimate ETL and month-end jobs to populate the BATCH_EXEMPT module/sql_id allowlist, and tune tempVel and pgaVel thresholds against real baseline slopes.
  3. Stage 3 — Enable Soft Cancellation (ALTER SYSTEM CANCEL SQL): Flip dry_run=false for ALTER SYSTEM CANCEL SQL only, keeping DISCONNECT SESSION disabled. Validate in staging with a synthetic Cartesian join that ORA-01013 aborts the runaway cursor while leaving the session intact, then monitor production ORA-01013 counts for zero false positives on allowlisted batch workloads. Rollback is setting dry_run=true.
  4. Stage 4 — Enable Escalation and Plan Controls: Enable the DISCONNECT SESSION IMMEDIATE fallback for sessions that ignore CANCEL SQL, and wire repeated sql_id offenders into SQL Plan Baselines (or DBMS_SQLQ on 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_LIMIT protection: Because Oracle 19c defaults PGA_AGGREGATE_LIMIT to the maximum of 2 GB, 200% of PGA_AGGREGATE_TARGET, or 3 MB * PROCESSES (5 MB * PROCESSES on RAC), leaving the limit active ensures ORA-04036 aborts runaway sessions before host RAM exhaustion triggers the Linux OOM killer. Setting PGA_AGGREGATE_LIMIT explicitly in spfile also prevents unexpected ceiling shifts if a DBA increases PROCESSES without reviewing host memory headroom.
  • Workarea vs untunable PGA visibility: V$SQL_WORKAREA_ACTIVE captures tunable SQL workareas (sorts, hash joins, bitmap merges), while V$PROCESS.PGA_ALLOC_MEM and V$PROCESS_MEMORY expose total process PGA including untunable PL/SQL associative arrays and Java heaps. Querying both together catches both hash-join TEMP spills and PL/SQL memory leaks.
  • Temporary extent cleanup and V$TEMPSEG_USAGE: When a large sort or hash join is cancelled via ALTER SYSTEM CANCEL SQL, the session’s temporary segments are marked for cleanup, and SMON deallocates the extents back to the tablespace. Using EXTENT MANAGEMENT LOCAL UNIFORM SIZE (for example, 64M or 128M for analytical PDBs) avoids the dictionary-extent fragmentation that slows down SMON cleanup after a multi-gigabyte spill.
  • Native 18c/19c CANCEL SQL semantics: ALTER SYSTEM CANCEL SQL 'sid,serial#,sql_id' interrupts only the active cursor without tearing down connection-pool sockets, whereas ALTER SYSTEM DISCONNECT SESSION tears down the session cleanly when a process is stuck outside an interruptible SQL fetch. Pairing cancellation logs with V$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.

ConditionBreaks HowDetectMitigate
Legitimate batch sort hits velocity thresholdMonth-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 immediatelyCancelled 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 ticksEvaluator 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 PDBsOne 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 aggressivelySub-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 fragmentationORA-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.

Four failure paths in automated workarea remediation

Key Takeaways

  • Never set PGA_AGGREGATE_LIMIT = 0 to silence ORA-04036; keep the hard ceiling enabled so Oracle terminates runaway sessions before the Linux OOM killer hits PMON or LGWR.
  • Sample V$SQL_WORKAREA_ACTIVE joined to V$SESSION and V$PROCESS (with adaptive 5s/1s polling and a minimum size filter) rather than polling DBA_* 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 legacy DBMS_SYSTEM event workarounds, and reserve DBMS_SQLQ SQL Quarantine strictly for Exadata (EE-ES) environments.
  • Isolate multi-tenant TEMP blast radiuses by assigning each Pluggable Database its own local temporary tablespace and protecting batch workloads with a BATCH_EXEMPT allowlist.

What to Do Next

  • Problem: Runaway hash joins and PL/SQL leaks saturate TEMP I/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, and V$PROCESS, compute per-session allocation velocity and Time-To-Exhaustion, and neutralize non-exempt culprits with ALTER SYSTEM CANCEL SQL before TEMP or PGA limits trip.
  • Proof: Run the collector in dry_run=true mode for one week against production workloads, verify zero false-positive triggers against allowlisted batch jobs, and confirm synthetic runaway spills in staging are cancelled before ORA-01652 or ORA-04036 occurs.
  • Action: Audit PGA_AGGREGATE_LIMIT, V$PGASTAT over-allocation counts, and per-PDB TEMP tablespace isolation across your 19c fleet this week before enabling automated CANCEL SQL in non-production. Document any long-running ETL modules in BATCH_EXEMPT during shadow mode.