[id='cep-memory-management-con_{context}']

= Memory management for events

In stream mode, the {RULE_ENGINE} uses automatic memory management to maintain events that are stored in KIE sessions. The {RULE_ENGINE} can retract from a KIE session any events that no longer match any rule due to their temporal constraints and release any resources held by the retracted events.

The {RULE_ENGINE} uses either explicit or inferred expiration to retract outdated events:

* *Explicit expiration:* The {RULE_ENGINE} removes events that are explicitly set to expire in rules that declare the `@expires` tag:
+
--
.DRL rule snippet with explicit expiration
[source]
----
declare StockPoint
  @expires( 30m )
end
----

This example rule sets any `StockPoint` events to expire after 30 minutes and to be removed from the KIE session if no other rules use the events.
--

* *Inferred expiration:* The {RULE_ENGINE} can calculate the expiration offset for a given event implicitly by analyzing the temporal constraints in the rules:
+
--
.DRL rule with temporal constraints
[source]
----
rule "Correlate orders"
when
  $bo : BuyOrder($id : id)
  $ae : AckOrder(id == $id, this after[0,10s] $bo)
then
  // Perform an action.
end
----

For this example rule, the {RULE_ENGINE} automatically calculates that whenever a `BuyOrder` event occurs, the {RULE_ENGINE} needs to store the event for up to 10 seconds and wait for the matching `AckOrder` event. After 10 seconds, the {RULE_ENGINE} infers the expiration and removes the event from the KIE session. An `AckOrder` event can only match an existing `BuyOrder` event, so the {RULE_ENGINE} infers the expiration if no match occurs and removes the event immediately.

The same is applied to a sliding window of time `window:time()`, but a sliding window of length `window:length()` doesn't calculate its expiration.

The {RULE_ENGINE} analyzes the entire KIE base to find the offset for every event type and to ensure that no other rules use the events that are pending removal. Whenever an implicit expiration clashes with an explicit expiration value, the {RULE_ENGINE} uses the greater time frame of the two to store the event longer.
--
